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:
Python virtualbox API
Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address
A:
Looking into some PyVB Source and API doc would be good idea.
A:
This might sound really snide but: Let me Google that for you
... though I have to admit that I had to try the fourth link from my results to find something that looked like it might actually be useful. Also it looks like you'll get quite a bit more from the "view source" than from the docstring generated web pages. However your mileage may vary.
|
Python virtualbox API
|
Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address
|
[
"Looking into some PyVB Source and API doc would be good idea.\n",
"This might sound really snide but: Let me Google that for you\n... though I have to admit that I had to try the fourth link from my results to find something that looked like it might actually be useful. Also it looks like you'll get quite a bit more from the \"view source\" than from the docstring generated web pages. However your mileage may vary.\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"virtualbox"
] |
stackoverflow_0002212286_python_virtualbox.txt
|
Q:
where does defined the Table 'test.sphinx_test_file'?
look the end line:ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist")
Traceback (most recent call last):
File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 280, in run
self.finish_response()
File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 319, in finish_response
for data in self.result:
File "D:\Python25\Lib\site-packages\django\http\__init__.py", line 374, in __iter__
self._iterator = iter(self._container)
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 240, in __iter__
return iter(self._get_data())
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 404, in _get_data
self._result_cache = list(self._get_results())
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 570, in _get_results
queryset = dict([(', '.join([unicode(getattr(o, p.attname)) for p in pks]), o) for o in queryset])
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 106, in _result_iter
self._fill_cache()
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 692, in _fill_cache
self._result_cache.append(self._iter.next())
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 238, in iterator
for row in self.query.results_iter():
File "D:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "D:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "D:\Python25\Lib\site-packages\django\db\backends\util.py", line 19, in execute
return self.cursor.execute(sql, params)
File "D:\Python25\Lib\site-packages\django\db\backends\mysql\base.py", line 84, in execute
return self.cursor.execute(query, args)
File "D:\Python25\Lib\site-packages\MySQLdb\cursors.py", line 163, in execute
self.errorhandler(self, exc, value)
File "D:\Python25\Lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist")
A:
Did you run syncdb after adding the app (I'm guessing the app is named sphinx) to your settings.py?
|
where does defined the Table 'test.sphinx_test_file'?
|
look the end line:ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist")
Traceback (most recent call last):
File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 280, in run
self.finish_response()
File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 319, in finish_response
for data in self.result:
File "D:\Python25\Lib\site-packages\django\http\__init__.py", line 374, in __iter__
self._iterator = iter(self._container)
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 240, in __iter__
return iter(self._get_data())
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 404, in _get_data
self._result_cache = list(self._get_results())
File "D:\zjm_code\sphinx_test\djangosphinx\models.py", line 570, in _get_results
queryset = dict([(', '.join([unicode(getattr(o, p.attname)) for p in pks]), o) for o in queryset])
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 106, in _result_iter
self._fill_cache()
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 692, in _fill_cache
self._result_cache.append(self._iter.next())
File "D:\Python25\Lib\site-packages\django\db\models\query.py", line 238, in iterator
for row in self.query.results_iter():
File "D:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "D:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "D:\Python25\Lib\site-packages\django\db\backends\util.py", line 19, in execute
return self.cursor.execute(sql, params)
File "D:\Python25\Lib\site-packages\django\db\backends\mysql\base.py", line 84, in execute
return self.cursor.execute(query, args)
File "D:\Python25\Lib\site-packages\MySQLdb\cursors.py", line 163, in execute
self.errorhandler(self, exc, value)
File "D:\Python25\Lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist")
|
[
"Did you run syncdb after adding the app (I'm guessing the app is named sphinx) to your settings.py?\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002211579_django_python.txt
|
Q:
How can I get a total count of a model's related objects and the model's children's related objects?
In Django, I've got a Checkout model, which is a ticket for somebody checking out equipment. I've also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the checkout belongs to an OrganizationalUnit on our campus.
The OrganizationalUnit has a self relation, so several OUs can be the children of a certain OU, and those children can have children, and so on. Here are the models, somewhat simplified.
class OrganizationalUnit(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey(
'self',
blank=True, null=True,
related_name='children',
)
class Checkout(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
department = models.ForeignKey(
OrganizationalUnit,
null=True,
blank=True,
related_name='checkouts',
)
I want to get a count of the Checkouts that are related to a certain OrganizationalUnit and all of its children. I know how to get the count of all the checkouts that are related to an OU.
ou = OrganizationalUnit.objects.get(pk=1)
count = ou.checkouts.all().count()
But how do I make that count reflect the checkouts of this OU's children and their children? Do I use some sort of iterative loop?
EDIT: I guess I still can't quite wrap my head around the while command to do this. The organizational units can go as deep as the user wants to nest them, but right now the most it goes in the DB is 5 deep. I've written this…
for kid in ou.children.all():
child_checkout_count += kid.checkouts.all().count()
for kid2 in kid.children.all():
child_checkout_count += kid2.checkouts.all().count()
for kid3 in kid2.children.all():
child_checkout_count += kid3.checkouts.all().count()
for kid4 in kid3.children.all():
child_checkout_count += kid4.checkouts.all().count()
for kid5 in kid4.children.all():
child_checkout_count += kid5.checkouts.all().count()
…which is total crap. And it takes a while to run because it pretty much traverses a major chunk of the database. Help! (I can't seem to think very well today.)
A:
What you need is a recursive function that traverse OrganizationalUnit relation tree and gets number of related Checkouts for each OrganizationalUnit. So your code will look like this:
def count_checkouts(ou):
checkout_count = ou.checkouts.count()
for kid in ou.children.all():
checkout_count += count_checkouts(kid)
return checkout_count
Also note, that to get a number of related checkouts I use:
checkout_count = ou.checkouts.count()
insted of:
count = ou.checkouts.all().count()
My variant is more efficient (see http://docs.djangoproject.com/en/1.1/ref/models/querysets/#count).
A:
I think the most efficient way of calculating this is at write time. You should modify OrganizationalUnit like this:
class OrganizationalUnit(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey(
'self',
blank=True, null=True,
related_name='children',
)
checkout_number = models.IntegerField(default=0)
create the functions that will update the OrganizationalUnit and its parents at write time:
def pre_save_checkout(sender, instance, **kwargs):
if isinstance(instance,Checkout) and instance.id and instance.department:
substract_checkout(instance.department)
def post_save_checkout(sender, instance, **kwargs):
if isinstance(instance,Checkout) and instance.department:
add_checkout(instance.department)
def substract_checkout(organizational_unit):
organizational_unit.checkout_number-=1
organizational_unit.save()
if organizational_unit.parent:
substract_checkout(organizational_unit.parent)
def add_checkout(organizational_unit):
organizational_unit.checkout_number+=1
organizational_unit.save()
if organizational_unit.parent:
add_checkout(organizational_unit.parent)
now all you need is connect those functions to the pre_save, post_save and pre_delete signals:
from django.db.models.signals import post_save, pre_save, pre_delete
pre_save.connect(pre_save_checkout, Checkout)
pre_delete.connect(pre_save_checkout, Checkout)
post_save.connect(post_save_checkout, Checkout)
That should do it...
A:
I'm not sure how does SQL perform on this one but what you want to do is exactly what you explained.
Get all OU and it's parents with While loop and then count Checkouts and sum them.
ORM brings you dynamic operations over SQL but kill performance:)
|
How can I get a total count of a model's related objects and the model's children's related objects?
|
In Django, I've got a Checkout model, which is a ticket for somebody checking out equipment. I've also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the checkout belongs to an OrganizationalUnit on our campus.
The OrganizationalUnit has a self relation, so several OUs can be the children of a certain OU, and those children can have children, and so on. Here are the models, somewhat simplified.
class OrganizationalUnit(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey(
'self',
blank=True, null=True,
related_name='children',
)
class Checkout(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
department = models.ForeignKey(
OrganizationalUnit,
null=True,
blank=True,
related_name='checkouts',
)
I want to get a count of the Checkouts that are related to a certain OrganizationalUnit and all of its children. I know how to get the count of all the checkouts that are related to an OU.
ou = OrganizationalUnit.objects.get(pk=1)
count = ou.checkouts.all().count()
But how do I make that count reflect the checkouts of this OU's children and their children? Do I use some sort of iterative loop?
EDIT: I guess I still can't quite wrap my head around the while command to do this. The organizational units can go as deep as the user wants to nest them, but right now the most it goes in the DB is 5 deep. I've written this…
for kid in ou.children.all():
child_checkout_count += kid.checkouts.all().count()
for kid2 in kid.children.all():
child_checkout_count += kid2.checkouts.all().count()
for kid3 in kid2.children.all():
child_checkout_count += kid3.checkouts.all().count()
for kid4 in kid3.children.all():
child_checkout_count += kid4.checkouts.all().count()
for kid5 in kid4.children.all():
child_checkout_count += kid5.checkouts.all().count()
…which is total crap. And it takes a while to run because it pretty much traverses a major chunk of the database. Help! (I can't seem to think very well today.)
|
[
"What you need is a recursive function that traverse OrganizationalUnit relation tree and gets number of related Checkouts for each OrganizationalUnit. So your code will look like this:\ndef count_checkouts(ou):\n checkout_count = ou.checkouts.count()\n for kid in ou.children.all():\n checkout_count += count_checkouts(kid)\n return checkout_count\n\nAlso note, that to get a number of related checkouts I use:\ncheckout_count = ou.checkouts.count()\n\ninsted of:\ncount = ou.checkouts.all().count()\n\nMy variant is more efficient (see http://docs.djangoproject.com/en/1.1/ref/models/querysets/#count).\n",
"I think the most efficient way of calculating this is at write time. You should modify OrganizationalUnit like this:\nclass OrganizationalUnit(models.Model):\n name = models.CharField(max_length=100)\n parent = models.ForeignKey(\n 'self',\n blank=True, null=True,\n related_name='children',\n )\n checkout_number = models.IntegerField(default=0)\n\ncreate the functions that will update the OrganizationalUnit and its parents at write time:\ndef pre_save_checkout(sender, instance, **kwargs):\n if isinstance(instance,Checkout) and instance.id and instance.department:\n substract_checkout(instance.department)\n\ndef post_save_checkout(sender, instance, **kwargs):\n if isinstance(instance,Checkout) and instance.department:\n add_checkout(instance.department)\n\ndef substract_checkout(organizational_unit):\n organizational_unit.checkout_number-=1\n organizational_unit.save()\n if organizational_unit.parent:\n substract_checkout(organizational_unit.parent)\n\ndef add_checkout(organizational_unit):\n organizational_unit.checkout_number+=1\n organizational_unit.save()\n if organizational_unit.parent:\n add_checkout(organizational_unit.parent)\n\nnow all you need is connect those functions to the pre_save, post_save and pre_delete signals:\nfrom django.db.models.signals import post_save, pre_save, pre_delete\n\npre_save.connect(pre_save_checkout, Checkout)\npre_delete.connect(pre_save_checkout, Checkout)\npost_save.connect(post_save_checkout, Checkout)\n\nThat should do it...\n",
"I'm not sure how does SQL perform on this one but what you want to do is exactly what you explained.\nGet all OU and it's parents with While loop and then count Checkouts and sum them. \nORM brings you dynamic operations over SQL but kill performance:)\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"django",
"django_select_related",
"many_to_many",
"models",
"python"
] |
stackoverflow_0002150644_django_django_select_related_many_to_many_models_python.txt
|
Q:
virtualbox and python API
0 vote down
I have installed virtualbox . but i cant import the module xpcom. but the synaptic package shows that it is installed. what could be wrong?
-ASK
A:
To be able to import xpcom, you would need to install pyxpcom extension, and build instructions are here.
In Synaptic Package Manager, it would be python-xpcom
|
virtualbox and python API
|
0 vote down
I have installed virtualbox . but i cant import the module xpcom. but the synaptic package shows that it is installed. what could be wrong?
-ASK
|
[
"To be able to import xpcom, you would need to install pyxpcom extension, and build instructions are here.\nIn Synaptic Package Manager, it would be python-xpcom\n"
] |
[
1
] |
[] |
[] |
[
"python",
"xpcom"
] |
stackoverflow_0002212706_python_xpcom.txt
|
Q:
Convention for checking the existence of a Django model?
What is the accepted way of checking a model's existence in a Django app?
I've seen this method used:
def profile_exists(user):
try:
UserProfile.objects.get(user = user)
return True
except:
return False
Is there a built-in function suited for this purpose?
A:
Bare excepts should not be used. Instead the model's DoesNotExist inner exception or django.core.exceptions.ObjectDoesNotExist should be caught.
Beyond that, either this or using len(SomeModel.objects.filter(...)) are acceptable.
A:
As an additional note, you could make a general purpose function out of it with:
def object_exists(model, **kwargs):
try:
model.objects.get(**kwargs)
return True
except model.DoesNotExist:
return False
And then simply call:
profile_exists = object_exists(UserProfile, user=user)
A:
That is suitable until the naked except. You always get more than you bargain for with those!
As mentioned by Ignacio Vazquez-Abrams, one should make use of the built in DoesNotExist exception for the model:
def profile_exists(user):
try:
UserProfile.objects.get(user = user)
return True
except UserProfile.DoesNotExist:
return False
Presto!
A:
There's always get_object_or_404, which as its name implies, either returns the object or raises an HttpNotFound error:
from django.shortcuts import get_object_or_404
instance = get_object_or_404(SomeModel, filter_args=whatever)
|
Convention for checking the existence of a Django model?
|
What is the accepted way of checking a model's existence in a Django app?
I've seen this method used:
def profile_exists(user):
try:
UserProfile.objects.get(user = user)
return True
except:
return False
Is there a built-in function suited for this purpose?
|
[
"Bare excepts should not be used. Instead the model's DoesNotExist inner exception or django.core.exceptions.ObjectDoesNotExist should be caught.\nBeyond that, either this or using len(SomeModel.objects.filter(...)) are acceptable.\n",
"As an additional note, you could make a general purpose function out of it with:\ndef object_exists(model, **kwargs):\n try:\n model.objects.get(**kwargs)\n return True\n except model.DoesNotExist:\n return False\n\nAnd then simply call:\nprofile_exists = object_exists(UserProfile, user=user)\n\n",
"That is suitable until the naked except. You always get more than you bargain for with those!\nAs mentioned by Ignacio Vazquez-Abrams, one should make use of the built in DoesNotExist exception for the model:\ndef profile_exists(user):\n try:\n UserProfile.objects.get(user = user)\n return True\n except UserProfile.DoesNotExist:\n return False\n\nPresto!\n",
"There's always get_object_or_404, which as its name implies, either returns the object or raises an HttpNotFound error:\nfrom django.shortcuts import get_object_or_404\ninstance = get_object_or_404(SomeModel, filter_args=whatever)\n\n"
] |
[
2,
2,
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002211530_django_django_models_python.txt
|
Q:
Python IRC Client
When I run the script:
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#tormented'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + channel + '\r\n')
sck.send('PRIVMSG #tormented :supaBOT\r\n')
while True:
data = sck.recv(4096)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
elif data.find ( 'PRIVMSG' ) != -1:
nick = data.split ( '!' ) [ 0 ].replace ( ':', '' )
message = ':'.join ( data.split ( ':' ) [ 2: ] )
destination = ''.join ( data.split ( ':' ) [ :2 ] ).split ( ' ' ) [ -2 ]
if destination == 'supaBOT':
destination = 'PRIVATE'
print '(', destination, ')', nick + ':', message
get = message.split(' ') [1]
if get == 'hi':
try:
args = message.split(' ') [2:]
sck.send('PRIVMSG ' + destination + ' :' + nick + ': ' + 'hello' + '\r\n')
except:
pass
I get this is the error:
get = message.split(' ')[1]
IndexError: list index out of range
How can I fix it?
A:
This means that message has no spaces in it, so when it's split by a space, you get a list containing a single element - you are trying to access the second element of this list. You should insert a check for this case.
EDIT: In reply to your comment: how you add the check depends on the logic of your program. The simplest solution would be something like:
if ' ' in msg:
get = message.split(' ')[1]
else:
get = message
A:
Try
get = message.split(" ",1)[-1]
Example
>>> "abcd".split(" ",1)[-1]
'abcd'
>>> "abcd efgh".split(" ",1)[-1]
'efgh'
|
Python IRC Client
|
When I run the script:
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#tormented'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + channel + '\r\n')
sck.send('PRIVMSG #tormented :supaBOT\r\n')
while True:
data = sck.recv(4096)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
elif data.find ( 'PRIVMSG' ) != -1:
nick = data.split ( '!' ) [ 0 ].replace ( ':', '' )
message = ':'.join ( data.split ( ':' ) [ 2: ] )
destination = ''.join ( data.split ( ':' ) [ :2 ] ).split ( ' ' ) [ -2 ]
if destination == 'supaBOT':
destination = 'PRIVATE'
print '(', destination, ')', nick + ':', message
get = message.split(' ') [1]
if get == 'hi':
try:
args = message.split(' ') [2:]
sck.send('PRIVMSG ' + destination + ' :' + nick + ': ' + 'hello' + '\r\n')
except:
pass
I get this is the error:
get = message.split(' ')[1]
IndexError: list index out of range
How can I fix it?
|
[
"This means that message has no spaces in it, so when it's split by a space, you get a list containing a single element - you are trying to access the second element of this list. You should insert a check for this case.\nEDIT: In reply to your comment: how you add the check depends on the logic of your program. The simplest solution would be something like:\nif ' ' in msg:\n get = message.split(' ')[1]\nelse:\n get = message\n\n",
"Try \nget = message.split(\" \",1)[-1]\n\nExample\n>>> \"abcd\".split(\" \",1)[-1]\n'abcd'\n>>> \"abcd efgh\".split(\" \",1)[-1]\n'efgh'\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002212727_python.txt
|
Q:
Web CMS Performance: pages/second (Joomla, Drupal, Plone, WP)
Note: I am not into web programming, so forgive my ignorance in case the question is trivial. Also, please don't comment about "how flawed" the out-of-box comparison of these products is. The question is not about how they compete against each other, rather about the reason behind the incredible slowness of ALL of them.
Just read about a benchmark, where Joomla, Drupal, Wordpress, Plone3 & 4 had been tested. What shocked me is this: out of the box they performed around 4-14 pages/sec. How is this possible, why are they so damn slow? A CMS should just query a DB and churn out the data packed into nice templates. DBs are fast. Templates should be fast (text replacement, no big deal). Our machines are superfast and yet, these high profile CMSs could only produce a few pages/sec. How come?
A:
A CMS should just query a DB and churn out the data packed into nice templates.
Not so much. Major, modern CMS systems are incredibly complex beasts. A typical page isn't merely body text and a title, but also dynamic category-based content queries that aggregate info across many site areas; not to mention security trimming and user-specific content zones. For example, loading http://www.volvogroup.com involves at least 7 of these queries, plus recursion through the site structure to generate navigation, and connecting to external systems to pull in news and investor relations data. Considering that, it shouldn't be such a surprise that it takes a beefy server farm to serve up several hundred hits per second.
A:
Because it takes a alot of processing to do all of that. ITs not a matter of "query, replace, render". All of thes products are made to fit a wide range of use cases and to be extensible to some degree so really those 3 basic operations your are talking about are split up into many, many operations all of which consume time.
All things being equal - the more flexible he system the slower it will be "out of the box".
A:
They are slow for a few reasons:
1 - Most of them are very modular,that means more files, more code and more DB queries.
2 - They largely (not wordpress so much) try to do everything, again designing a system for every possible situation makes it more complex and harder to tune.
3 - Most of them (currently) support both PHP4 and PHP5, this is again just extra work.
4 - They are allegedly made so non-technical users can use them, which means they often have to do things in a way that is not the most efficient, i.e. Drupals CCK / Views lets people that can't programme effectively create database tables and SQL queries, the flaw being these tables / queries are very general in design and are rather inefficient in comparison to custom coded efforts.
5 - They tend to use lots of DB queries, Drupal uses 40 or so for a very basic page and if you search their forums you will see reports of people claiming some pages make hundreds or even over a thousand queries.
They do of course offer caching and Drupal can get quite good performance from things like its boost module, the flaw being one of Drupal's (and Joomla's) selling points is you can make a community site, forum, Digg like site in it, all sites where caching is of limited use...
A:
They are relatively complex systems. They allow a lot of hooks for plugins, so there's a lot of steps in the workflow from request to response.
In the real world, however, caching (whether in-application or opcode caching) is a tremendous boost to performance.
I'm not familiar with Plone, but the PHP CMSs essentially have to load and interpret almost the entire system with every single request.
A:
Please don't take offense to this, but to preface your question by explaining your unfamiliarity with web programming, and then criticize the performance of what appears to you to be a 'simple' operation is a bit short-sighted.
I would encourage you to learn a bit more about the common problems a CMS solves, and the general theory and practice of how dynamic web pages and HTTP work. It's far from a simple I/O operation.
Also, for practical use, I would highly encourage anyone running a CMS to find a caching solution. Caching is intended to solve a lot of the 'speed' problems that arise in web technology. It should be part of any common web stack.
A:
In my opinion :
Because CMS and frameworks think of all the things you need, that you can use:
like
Filter userinput
Create PDF,AJAX Output Template and alot more
It Depends on your need, what you realy need
Im not agree what you wrote
A CMS should just query a DB and churn out the data packed into nice templates.
A CMS Does a lot more things alot more ...
And at last but not least dont compare Desktop Software Speed with Wep Aplication.
There is a Big Difference
A:
A CMS Does a lot more things alot more ...
And at last but not least dont compare Desktop Software Speed with Wep Aplication.
There is a Big Difference
|
Web CMS Performance: pages/second (Joomla, Drupal, Plone, WP)
|
Note: I am not into web programming, so forgive my ignorance in case the question is trivial. Also, please don't comment about "how flawed" the out-of-box comparison of these products is. The question is not about how they compete against each other, rather about the reason behind the incredible slowness of ALL of them.
Just read about a benchmark, where Joomla, Drupal, Wordpress, Plone3 & 4 had been tested. What shocked me is this: out of the box they performed around 4-14 pages/sec. How is this possible, why are they so damn slow? A CMS should just query a DB and churn out the data packed into nice templates. DBs are fast. Templates should be fast (text replacement, no big deal). Our machines are superfast and yet, these high profile CMSs could only produce a few pages/sec. How come?
|
[
"\nA CMS should just query a DB and churn out the data packed into nice templates. \n\nNot so much. Major, modern CMS systems are incredibly complex beasts. A typical page isn't merely body text and a title, but also dynamic category-based content queries that aggregate info across many site areas; not to mention security trimming and user-specific content zones. For example, loading http://www.volvogroup.com involves at least 7 of these queries, plus recursion through the site structure to generate navigation, and connecting to external systems to pull in news and investor relations data. Considering that, it shouldn't be such a surprise that it takes a beefy server farm to serve up several hundred hits per second.\n",
"Because it takes a alot of processing to do all of that. ITs not a matter of \"query, replace, render\". All of thes products are made to fit a wide range of use cases and to be extensible to some degree so really those 3 basic operations your are talking about are split up into many, many operations all of which consume time.\nAll things being equal - the more flexible he system the slower it will be \"out of the box\".\n",
"They are slow for a few reasons:\n1 - Most of them are very modular,that means more files, more code and more DB queries.\n2 - They largely (not wordpress so much) try to do everything, again designing a system for every possible situation makes it more complex and harder to tune.\n3 - Most of them (currently) support both PHP4 and PHP5, this is again just extra work.\n4 - They are allegedly made so non-technical users can use them, which means they often have to do things in a way that is not the most efficient, i.e. Drupals CCK / Views lets people that can't programme effectively create database tables and SQL queries, the flaw being these tables / queries are very general in design and are rather inefficient in comparison to custom coded efforts.\n5 - They tend to use lots of DB queries, Drupal uses 40 or so for a very basic page and if you search their forums you will see reports of people claiming some pages make hundreds or even over a thousand queries.\nThey do of course offer caching and Drupal can get quite good performance from things like its boost module, the flaw being one of Drupal's (and Joomla's) selling points is you can make a community site, forum, Digg like site in it, all sites where caching is of limited use...\n",
"They are relatively complex systems. They allow a lot of hooks for plugins, so there's a lot of steps in the workflow from request to response.\nIn the real world, however, caching (whether in-application or opcode caching) is a tremendous boost to performance.\nI'm not familiar with Plone, but the PHP CMSs essentially have to load and interpret almost the entire system with every single request.\n",
"Please don't take offense to this, but to preface your question by explaining your unfamiliarity with web programming, and then criticize the performance of what appears to you to be a 'simple' operation is a bit short-sighted.\nI would encourage you to learn a bit more about the common problems a CMS solves, and the general theory and practice of how dynamic web pages and HTTP work. It's far from a simple I/O operation. \nAlso, for practical use, I would highly encourage anyone running a CMS to find a caching solution. Caching is intended to solve a lot of the 'speed' problems that arise in web technology. It should be part of any common web stack.\n",
"In my opinion :\nBecause CMS and frameworks think of all the things you need, that you can use:\nlike \n\nFilter userinput\nCreate PDF,AJAX Output Template and alot more\n\nIt Depends on your need, what you realy need\nIm not agree what you wrote\n\nA CMS should just query a DB and churn out the data packed into nice templates. \n\nA CMS Does a lot more things alot more ... \nAnd at last but not least dont compare Desktop Software Speed with Wep Aplication. \nThere is a Big Difference\n",
"A CMS Does a lot more things alot more ...\nAnd at last but not least dont compare Desktop Software Speed with Wep Aplication.\nThere is a Big Difference\n"
] |
[
3,
2,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"benchmarking",
"content_management_system",
"php",
"python"
] |
stackoverflow_0002120443_benchmarking_content_management_system_php_python.txt
|
Q:
What is a nicer alternative to a namedtuples _replace?
Take this code:
>>> import urlparse
>>> parts = urlparse.urlparse('http://docs.python.org/library/')
>>> parts = parts._replace(path='/3.0'+parts.path)
parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do:
>>> parts = parts[:2] + ('/3.0'+parts.path,) + parts[3:]
Because that makes it an ordinary tuple, and not a namedtuple, and doing:
>>> parts = namedtuple(scheme=parts.scheme, netloc=parts.netloc, etc etc)
is kinda stupid. :)
Ideas?
A:
The reason methods of namedtuple start with an initial underscore is only to prevent name collisions. They should not be considered to be for internal use only:
To prevent conflicts with field names, the method and attribute names start with an underscore.
|
What is a nicer alternative to a namedtuples _replace?
|
Take this code:
>>> import urlparse
>>> parts = urlparse.urlparse('http://docs.python.org/library/')
>>> parts = parts._replace(path='/3.0'+parts.path)
parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do:
>>> parts = parts[:2] + ('/3.0'+parts.path,) + parts[3:]
Because that makes it an ordinary tuple, and not a namedtuple, and doing:
>>> parts = namedtuple(scheme=parts.scheme, netloc=parts.netloc, etc etc)
is kinda stupid. :)
Ideas?
|
[
"The reason methods of namedtuple start with an initial underscore is only to prevent name collisions. They should not be considered to be for internal use only:\n\nTo prevent conflicts with field names, the method and attribute names start with an underscore.\n\n"
] |
[
22
] |
[] |
[] |
[
"namedtuple",
"python"
] |
stackoverflow_0002213102_namedtuple_python.txt
|
Q:
A reliable way to determine if ntfs permissions were inherited
I have a somewhat obscure question here.
What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.
How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.
#!/usr/bin/env python
from win32security import *
import sys
def decode_flags(flags):
_flags = {
SE_DACL_PROTECTED:"SE_DACL_PROTECTED",
SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED",
OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE",
CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE",
INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE",
NO_INHERITANCE:"NO_INHERITANCE",
NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE",
INHERITED_ACE:"INHERITED_ACE"
}
for key in _flags.keys():
if (flags & key):
print '\t','\t',_flags[key],"is set!"
def main(argv):
target = argv[0]
print target
security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION)
dacl = security_descriptor.GetSecurityDescriptorDacl()
for ace_index in range(dacl.GetAceCount()):
(ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index)
name,domain,account_type = LookupAccountSid(None,sid)
print '\t',domain+'\\'+name,hex(ace_flags)
decode_flags(ace_flags)
if __name__ == '__main__':
main(sys.argv[1:])
Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED_ACE access flag. It should be set when the ACE is inherited and not set explicitly.
When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED_ACE flag will NOT be set! But the inherited permissions are there and they DO work.
If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED_ACE flag and, maybe find another reliable way to determine if the ACE was inherited or not.
How to reproduce:
Create an object (file or folder)
Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).
Check the flags using, for example, the script I was using (INHERITED_ACE will NOT be set on any ACEs).
Change permissions of an object (apply changes), change them back even.
Check the flags (INHERITED_ACE will be there)
..shake your head in disbelief (I know I did)
Sorry for a somewhat lengthy post, hope this makes at least a little sense.
A:
You can use the .Net framework
System.Security.AccessControl
This covers ACL and DACL and SACL.
A:
I think the original poster is seeing behavior detailed in
This newsgroup posting
Note that the control flags set on the container can change simply by un-ticking and re-ticking the inheritance box in the GUI.
Further note that simply adding an ACE to the DACL using Microsoft's tools will also change the control flags.
Further note that the GUI, cacls and icacls can NOT be relied on when it comes to inheritance due to many subtle bugs as discussed in the newsgroup posting.
It seems that the "old" way of controlling inheritance was to use the control flags on the container in combination with inheritance related ACE flags.
The "new" way does not use the control flags on the container and instead uses duplicate ACEs; one to control the access on the object and a second one to control what is inherited by child objects.
BUT, it seems the existing Microsoft tools (e.g. Vista) can not work in the "new" way yet, so when you make a simple change using the tools, it resorts to the old way of using control flags on the container.
If you create a new partition on Vista, then create a new folder, then look at the flags and ACEs, it will look something like this
ControlFlags : 0x8004
Owner : BUILTIN\Administrators
Group : WS1\None
S-1-5-32-544 : BUILTIN\Administrators : 0x0 : 0x0 : 0x1F01FF
S-1-5-32-544 : BUILTIN\Administrators : 0x0 : 0xB : 0x10000000
S-1-5-18 : NT AUTHORITY\SYSTEM : 0x0 : 0x0 : 0x1F01FF
S-1-5-18 : NT AUTHORITY\SYSTEM : 0x0 : 0xB : 0x10000000
S-1-5-11 : NT AUTHORITY\Authenticated Users : 0x0 : 0x0 : 0x1301BF
S-1-5-11 : NT AUTHORITY\Authenticated Users : 0x0 : 0xB : 0xE0010000
S-1-5-32-545 : BUILTIN\Users : 0x0 : 0x0 : 0x1200A9
S-1-5-32-545 : BUILTIN\Users : 0x0 : 0xB : 0xA0000000
Note the ControlFlags and the duplicated ACEs.
A:
On my Win XP Home Edition this code doesn't seem to work at all :-)
I get this stack trace:
Traceback (most recent call last):
File "C:\1.py", line 37, in
main(sys.argv[1:])
File "C:\1.py", line 29, in main
for ace_index in range(dacl.GetAceCount()):
AttributeError: 'NoneType' object has no attribute 'GetAceCount'
Can you just try to "nudge" the DACL to be filled?
I mean, if you know it's going to work after you make a slight change in it... do a slight change programmatically, add a stub ACE and remove it. Can you?
UPDATE. I made an experiment with a C# program on my work machine (with Win XP Prof) and I must tell you that the .net way of getting this security information actually works. So, when I create a new file, my C# program detects that the ACEs were inherited, while your python code doesn't.
Here is the sample output of my runs:
C:>csharp_tricks.exe 2.txt
FullControl --> IsInherited: True
FullControl --> IsInherited: True
ReadAndExecute, Synchronize --> IsInherited: True
C:>1.py 2.txt
2.txt
BUILTIN\Administrators 0x0
NT AUTHORITY\SYSTEM 0x0
BUILTIN\Users 0x0
My C# class:
public class InheritedAce
{
public static string GetDACLReport(string path)
{
StringBuilder result = new StringBuilder();
FileSecurity fs = new FileSecurity(path, AccessControlSections.Access);
foreach (var rule in fs.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType<FileSystemAccessRule>())
{
result.AppendFormat("{0} --> IsInherited: {1}", rule.FileSystemRights, rule.IsInherited);
result.AppendLine();
}
return result.ToString();
}
}
So, it seems to be a bug in the python pywin32 security library. Maybe they aren't doing all the necessary system calls...
|
A reliable way to determine if ntfs permissions were inherited
|
I have a somewhat obscure question here.
What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.
How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.
#!/usr/bin/env python
from win32security import *
import sys
def decode_flags(flags):
_flags = {
SE_DACL_PROTECTED:"SE_DACL_PROTECTED",
SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED",
OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE",
CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE",
INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE",
NO_INHERITANCE:"NO_INHERITANCE",
NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE",
INHERITED_ACE:"INHERITED_ACE"
}
for key in _flags.keys():
if (flags & key):
print '\t','\t',_flags[key],"is set!"
def main(argv):
target = argv[0]
print target
security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION)
dacl = security_descriptor.GetSecurityDescriptorDacl()
for ace_index in range(dacl.GetAceCount()):
(ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index)
name,domain,account_type = LookupAccountSid(None,sid)
print '\t',domain+'\\'+name,hex(ace_flags)
decode_flags(ace_flags)
if __name__ == '__main__':
main(sys.argv[1:])
Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED_ACE access flag. It should be set when the ACE is inherited and not set explicitly.
When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED_ACE flag will NOT be set! But the inherited permissions are there and they DO work.
If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED_ACE flag and, maybe find another reliable way to determine if the ACE was inherited or not.
How to reproduce:
Create an object (file or folder)
Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).
Check the flags using, for example, the script I was using (INHERITED_ACE will NOT be set on any ACEs).
Change permissions of an object (apply changes), change them back even.
Check the flags (INHERITED_ACE will be there)
..shake your head in disbelief (I know I did)
Sorry for a somewhat lengthy post, hope this makes at least a little sense.
|
[
"You can use the .Net framework \nSystem.Security.AccessControl\n\nThis covers ACL and DACL and SACL.\n",
"I think the original poster is seeing behavior detailed in\nThis newsgroup posting\nNote that the control flags set on the container can change simply by un-ticking and re-ticking the inheritance box in the GUI.\nFurther note that simply adding an ACE to the DACL using Microsoft's tools will also change the control flags.\nFurther note that the GUI, cacls and icacls can NOT be relied on when it comes to inheritance due to many subtle bugs as discussed in the newsgroup posting.\nIt seems that the \"old\" way of controlling inheritance was to use the control flags on the container in combination with inheritance related ACE flags.\nThe \"new\" way does not use the control flags on the container and instead uses duplicate ACEs; one to control the access on the object and a second one to control what is inherited by child objects.\nBUT, it seems the existing Microsoft tools (e.g. Vista) can not work in the \"new\" way yet, so when you make a simple change using the tools, it resorts to the old way of using control flags on the container.\nIf you create a new partition on Vista, then create a new folder, then look at the flags and ACEs, it will look something like this\nControlFlags : 0x8004\nOwner : BUILTIN\\Administrators\nGroup : WS1\\None\nS-1-5-32-544 : BUILTIN\\Administrators : 0x0 : 0x0 : 0x1F01FF\nS-1-5-32-544 : BUILTIN\\Administrators : 0x0 : 0xB : 0x10000000\nS-1-5-18 : NT AUTHORITY\\SYSTEM : 0x0 : 0x0 : 0x1F01FF\nS-1-5-18 : NT AUTHORITY\\SYSTEM : 0x0 : 0xB : 0x10000000\nS-1-5-11 : NT AUTHORITY\\Authenticated Users : 0x0 : 0x0 : 0x1301BF\nS-1-5-11 : NT AUTHORITY\\Authenticated Users : 0x0 : 0xB : 0xE0010000\nS-1-5-32-545 : BUILTIN\\Users : 0x0 : 0x0 : 0x1200A9\nS-1-5-32-545 : BUILTIN\\Users : 0x0 : 0xB : 0xA0000000\n\nNote the ControlFlags and the duplicated ACEs.\n",
"On my Win XP Home Edition this code doesn't seem to work at all :-)\nI get this stack trace:\n\nTraceback (most recent call last):\n File \"C:\\1.py\", line 37, in \n main(sys.argv[1:])\n File \"C:\\1.py\", line 29, in main\n for ace_index in range(dacl.GetAceCount()):\nAttributeError: 'NoneType' object has no attribute 'GetAceCount'\n\nCan you just try to \"nudge\" the DACL to be filled?\nI mean, if you know it's going to work after you make a slight change in it... do a slight change programmatically, add a stub ACE and remove it. Can you?\nUPDATE. I made an experiment with a C# program on my work machine (with Win XP Prof) and I must tell you that the .net way of getting this security information actually works. So, when I create a new file, my C# program detects that the ACEs were inherited, while your python code doesn't.\nHere is the sample output of my runs:\n\nC:>csharp_tricks.exe 2.txt\nFullControl --> IsInherited: True\nFullControl --> IsInherited: True\nReadAndExecute, Synchronize --> IsInherited: True\n\nC:>1.py 2.txt\n2.txt\nBUILTIN\\Administrators 0x0\nNT AUTHORITY\\SYSTEM 0x0\nBUILTIN\\Users 0x0\n\nMy C# class:\npublic class InheritedAce\n{\n public static string GetDACLReport(string path)\n {\n StringBuilder result = new StringBuilder();\n FileSecurity fs = new FileSecurity(path, AccessControlSections.Access);\n foreach (var rule in fs.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType<FileSystemAccessRule>())\n {\n result.AppendFormat(\"{0} --> IsInherited: {1}\", rule.FileSystemRights, rule.IsInherited);\n result.AppendLine();\n }\n\n return result.ToString();\n }\n}\n\nSo, it seems to be a bug in the python pywin32 security library. Maybe they aren't doing all the necessary system calls...\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"acl",
"file_permissions",
"ntfs",
"python",
"winapi"
] |
stackoverflow_0000910696_acl_file_permissions_ntfs_python_winapi.txt
|
Q:
Load blob image data into QPixmap
I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:
def dump_image(imgfile):
i = open(imgfile, 'rb')
i.seek(0)
w = i.read()
i.close()
return cPickle.dumps(w,1)
blob = dump_image(imgfile)
hex_str = blob.encode('hex')
# x"%s"%hex_str will be the string inserted into the SQL command
This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:
(1) Hex str in database -- cPickle&StringIO --> PIL Image Object
def load_image(s):
o = cPickle.loads(s)
c = StringIO.StringIO()
c.write(o)
c.seek(0)
im = Image.open(c)
return im
(2) PIL Image Object -->Temporary image file
(3) Temporary image file --> QPixmap
This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use QPixmap::loadFromData() to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.
TIA,
Bing
A:
You can use the QImage.fromData static method to load an image from a string and then convert it to a pixmap:
image_data = get_image_data_from_blob()
qimg = QtGui.QImage.fromData(image_data)
pixmap = QtGui.QPixmap.fromImage(qimg)
A:
The approach suggested by Ants Aasma works and actually it is also OK to just use the following code:
image_data = cPickle.loads(str(s)) # s is fetched from DB
qp = QPixmap()
qp.loadFromData(image_data)
Thanks a lot for all the help and information.
A:
After a good hour and a half of googleing to solve a similar problem, I ended up loading JPEGs in a compiled .exe with QT. I am using python3.1, and therefore could not use some of the previously mentioned solutions :
tips working for py2exe (because I am using cxfreeze instead of py2exe, as py2exe works only for python2),
tips that require PIL (also only for python2, afaik).
While the solutions posted here didn't work, something very similar did :
I simply copied the [PythonDir]\Lib\site-packages\PyQt4\plugins\imageformats to my exe's folder and removed the qt.conf file that I created in that folder following other solutions. That's all (I think :p).
After that, it worked whether I loaded the jpg using QPixmap's constructor or loading a QImage first. It also worked with no special option needed for both the setup.py and the cxfreeze.bat methods of compiling to exe using cxfreeze.
(this solution was posted by jbz on http://www.thetoryparty.com/wp/2009/08/27/pyqt-and-py2app-seriously-i-dont-know-what-to-do-with-you-when-youre-like-this/)
This question is a bit old, but as the problem seems to be still there, I hope this answer will help python3.1 users out there.
|
Load blob image data into QPixmap
|
I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:
def dump_image(imgfile):
i = open(imgfile, 'rb')
i.seek(0)
w = i.read()
i.close()
return cPickle.dumps(w,1)
blob = dump_image(imgfile)
hex_str = blob.encode('hex')
# x"%s"%hex_str will be the string inserted into the SQL command
This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:
(1) Hex str in database -- cPickle&StringIO --> PIL Image Object
def load_image(s):
o = cPickle.loads(s)
c = StringIO.StringIO()
c.write(o)
c.seek(0)
im = Image.open(c)
return im
(2) PIL Image Object -->Temporary image file
(3) Temporary image file --> QPixmap
This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use QPixmap::loadFromData() to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.
TIA,
Bing
|
[
"You can use the QImage.fromData static method to load an image from a string and then convert it to a pixmap:\n image_data = get_image_data_from_blob()\n qimg = QtGui.QImage.fromData(image_data)\n pixmap = QtGui.QPixmap.fromImage(qimg)\n\n",
"The approach suggested by Ants Aasma works and actually it is also OK to just use the following code: \nimage_data = cPickle.loads(str(s)) # s is fetched from DB \nqp = QPixmap() \nqp.loadFromData(image_data) \n\nThanks a lot for all the help and information.\n",
"After a good hour and a half of googleing to solve a similar problem, I ended up loading JPEGs in a compiled .exe with QT. I am using python3.1, and therefore could not use some of the previously mentioned solutions :\n\ntips working for py2exe (because I am using cxfreeze instead of py2exe, as py2exe works only for python2),\ntips that require PIL (also only for python2, afaik).\n\nWhile the solutions posted here didn't work, something very similar did :\nI simply copied the [PythonDir]\\Lib\\site-packages\\PyQt4\\plugins\\imageformats to my exe's folder and removed the qt.conf file that I created in that folder following other solutions. That's all (I think :p).\nAfter that, it worked whether I loaded the jpg using QPixmap's constructor or loading a QImage first. It also worked with no special option needed for both the setup.py and the cxfreeze.bat methods of compiling to exe using cxfreeze.\n(this solution was posted by jbz on http://www.thetoryparty.com/wp/2009/08/27/pyqt-and-py2app-seriously-i-dont-know-what-to-do-with-you-when-youre-like-this/)\nThis question is a bit old, but as the problem seems to be still there, I hope this answer will help python3.1 users out there.\n"
] |
[
11,
4,
0
] |
[] |
[] |
[
"blob",
"image",
"pyqt",
"python",
"qpixmap"
] |
stackoverflow_0001300908_blob_image_pyqt_python_qpixmap.txt
|
Q:
Python: Why is IDLE so slow?
IDLE is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger.
However, code executed under IDLE is insanely slow. By insanely I mean 3 orders of magnitude slow:
bash
time echo "for i in range(10000): print 'x'," | python
Takes 0.052s,
IDLE
import datetime
start=datetime.datetime.now()
for i in range(10000): print 'x',
end=datetime.datetime.now()
print end-start
Takes:
>>> 0:01:44.853951
Which is roughly 2,000 times slower.
Any thoughts, or ideas how to improve this? I guess it has something to do with the debugger in the background, but I'm not really sure.
Adam
A:
The problem is the text output not the debugger.
I just tried it on my Q6600 (3GHz overclocked) System and my numbers are even worse.
But its easy to see that they are going down the more output text is added.
I tried to run it with
1000 iterations => 7,8 sec
2000 iterations => 28,5 sec
3000 iterations => 70 sec
I did some low level TK stuff in the past and i know that the TkText Widget is keeping the text in a BTree structure. Appending text a character a time is one of the worst ways to do but this seems to be what IDLE is doing. The normal way is to catch more data and append a larger chunk of text.
Amazingly if you write print 'x\n' the output is much faster. 3000 iterations in 7 seconds and your 10000 in 19 sec.
So the problem is definitely with appending single chars to existing lines. The IDLE programmer didn't know how TkText works.
So the advise is to add more newlines into your text or output larger chunks and not only a single 'x' character.
A:
The problem is in the Tkinter Text widget, and its inefficient management of very long lines, and you create one.
You'll notice that, while any part of a very long line is visible, all scrolling is devilishly slow.
|
Python: Why is IDLE so slow?
|
IDLE is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger.
However, code executed under IDLE is insanely slow. By insanely I mean 3 orders of magnitude slow:
bash
time echo "for i in range(10000): print 'x'," | python
Takes 0.052s,
IDLE
import datetime
start=datetime.datetime.now()
for i in range(10000): print 'x',
end=datetime.datetime.now()
print end-start
Takes:
>>> 0:01:44.853951
Which is roughly 2,000 times slower.
Any thoughts, or ideas how to improve this? I guess it has something to do with the debugger in the background, but I'm not really sure.
Adam
|
[
"The problem is the text output not the debugger.\nI just tried it on my Q6600 (3GHz overclocked) System and my numbers are even worse.\nBut its easy to see that they are going down the more output text is added.\nI tried to run it with \n1000 iterations => 7,8 sec\n2000 iterations => 28,5 sec\n3000 iterations => 70 sec\nI did some low level TK stuff in the past and i know that the TkText Widget is keeping the text in a BTree structure. Appending text a character a time is one of the worst ways to do but this seems to be what IDLE is doing. The normal way is to catch more data and append a larger chunk of text.\nAmazingly if you write print 'x\\n' the output is much faster. 3000 iterations in 7 seconds and your 10000 in 19 sec. \nSo the problem is definitely with appending single chars to existing lines. The IDLE programmer didn't know how TkText works.\nSo the advise is to add more newlines into your text or output larger chunks and not only a single 'x' character.\n",
"The problem is in the Tkinter Text widget, and its inefficient management of very long lines, and you create one.\nYou'll notice that, while any part of a very long line is visible, all scrolling is devilishly slow.\n"
] |
[
31,
10
] |
[] |
[] |
[
"performance",
"python",
"python_idle"
] |
stackoverflow_0002212722_performance_python_python_idle.txt
|
Q:
Django model class methods for predefined values
I'm working on some Django-code that has a model like this:
class Status(models.Model):
code = models.IntegerField()
text = models.CharField(maxlength=255)
There are about 10 pre-defined code/text-pairs that are stored in the database. Scattered around the codebase I see code like this:
status = Status.objects.get(code=0) # successful
status = Status.objects.get(code=1) # failed
I would rather have a method for each so that the code would look something like this instead:
status = Status.successful()
status = Status.failed()
etc...
Is this possible? I have looked in to the Manager-stuff but I haven't really found a way. Is it time to really RTFM?
In Java it would be a static method and in Ruby you would just define a method on self, but it's not that easy in Python, is it?
A:
You should perhaps implement this by defining a custom manager for your class, and adding two manager methods on that manager (which I believe is the preferred way for adding table-level functionality for any model). However, another way of doing it is by throwing in two class methods on your class that query and return resulting objects, such as:
class Status(models.Model):
code = models.IntegerField()
text = models.CharField(maxlength=255)
@classmethod
def successful(cls):
return cls.objects.get(code=0)
@classmethod
def failed(cls):
return cls.objects.get(code=1)
Do note please that get() is likely to throw different exceptions, such as Status.DoesNotExist and MultipleObjectsReturned.
And for an example implementation of how to do the same thing using Django managers, you could do something like this:
class StatusManager(models.Manager):
def successful(self):
return self.get(code=1)
def failed(self):
return self.get(code=0)
class Status(models.Model):
code = models.IntegerField()
text = models.CharField(maxlength=255)
objects = StatusManager()
Where, you could do Status.objects.successful() and Status.objects.failed() to get what you desire.
|
Django model class methods for predefined values
|
I'm working on some Django-code that has a model like this:
class Status(models.Model):
code = models.IntegerField()
text = models.CharField(maxlength=255)
There are about 10 pre-defined code/text-pairs that are stored in the database. Scattered around the codebase I see code like this:
status = Status.objects.get(code=0) # successful
status = Status.objects.get(code=1) # failed
I would rather have a method for each so that the code would look something like this instead:
status = Status.successful()
status = Status.failed()
etc...
Is this possible? I have looked in to the Manager-stuff but I haven't really found a way. Is it time to really RTFM?
In Java it would be a static method and in Ruby you would just define a method on self, but it's not that easy in Python, is it?
|
[
"You should perhaps implement this by defining a custom manager for your class, and adding two manager methods on that manager (which I believe is the preferred way for adding table-level functionality for any model). However, another way of doing it is by throwing in two class methods on your class that query and return resulting objects, such as:\nclass Status(models.Model):\n code = models.IntegerField()\n text = models.CharField(maxlength=255)\n\n @classmethod\n def successful(cls):\n return cls.objects.get(code=0)\n\n @classmethod\n def failed(cls):\n return cls.objects.get(code=1)\n\nDo note please that get() is likely to throw different exceptions, such as Status.DoesNotExist and MultipleObjectsReturned. \nAnd for an example implementation of how to do the same thing using Django managers, you could do something like this:\nclass StatusManager(models.Manager):\n def successful(self):\n return self.get(code=1)\n\n def failed(self):\n return self.get(code=0)\n\nclass Status(models.Model):\n code = models.IntegerField()\n text = models.CharField(maxlength=255)\n\n objects = StatusManager()\n\nWhere, you could do Status.objects.successful() and Status.objects.failed() to get what you desire.\n"
] |
[
49
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002213309_django_django_models_python.txt
|
Q:
Hooking str.__getitem__ in Python
Is there a way of hooking str.__getitem__?
Example:
I'd like to be capable of do:
>>> "this is a string"[[1,3,4]]
'hs '
passing a list to [] and get the items in that list.
A more realistic example:
class STR(str):
pass
class INT(int):
pass
It's easy to make that STR("a string")[1] or STR("a string")[INT(1)] return an STR instance.
I'd like to be capable to make "a non STR string"[INT(1)] return an STR instance.
A:
Why hook an often-used internal function when you can
def get_characters (s, l):
return "".join(s[i] for i in l)
>>> get_characters("this is a string", [1,3,4])
"hs "
A:
Methods on objects defined in C cannot be monkeypatched. The best you can do is to use an external function to complete the task.
|
Hooking str.__getitem__ in Python
|
Is there a way of hooking str.__getitem__?
Example:
I'd like to be capable of do:
>>> "this is a string"[[1,3,4]]
'hs '
passing a list to [] and get the items in that list.
A more realistic example:
class STR(str):
pass
class INT(int):
pass
It's easy to make that STR("a string")[1] or STR("a string")[INT(1)] return an STR instance.
I'd like to be capable to make "a non STR string"[INT(1)] return an STR instance.
|
[
"Why hook an often-used internal function when you can \ndef get_characters (s, l):\n return \"\".join(s[i] for i in l)\n\n>>> get_characters(\"this is a string\", [1,3,4])\n\"hs \"\n\n",
"Methods on objects defined in C cannot be monkeypatched. The best you can do is to use an external function to complete the task.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002213325_python.txt
|
Q:
Mac 10.6 Universal Binary scipy: cephes/specfun "_aswfa_" symbol not found
I can't get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1.
My python setup
With the help of this answer, I built a 32/64 bit intel universal binary of python 2.6.4 with the intention of using the arch command to select between the architectures. (I managed to make some universal binaries of a few libraries I wanted using lipo.) That all works. I then installed scipy according to the instructions on hyperjeff's article, only with more up-to-date numpy (1.4.0) and skipping the bit about moving numpy aside briefly during the installation of scipy.
Now, everything except scipy seems to be working as far as I can tell, and I can indeed select between 32 and 64 bit mode using arch -i386 python and arch -x86_64 python.
The error
Scipy complains in 32 bit mode:
$ arch -x86_64 python -c "import scipy.interpolate; print 'success'"
success
$ arch -i386 python -c "import scipy.interpolate; print 'success'"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/interpolate/__init__.py", line 7, in <module>
from interpolate import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/interpolate/interpolate.py", line 13, in <module>
import scipy.special as spec
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/__init__.py", line 8, in <module>
from basic import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/basic.py", line 8, in <module>
from _cephes import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so, 2): Symbol not found: _aswfa_
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so
Attempt at tracking down the problem
It looks like scipy.interpolate imports something called _cephes, which looks for a symbol called _aswfa_ but can't find it in 32 bit mode. Browsing through scipy's source, I find an ASWFA subroutine in specfun.f. The only scipy product file with a similar name is specfun.so, but both that and _cephes.so appear to be universal binaries:
$ cd /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/
$ file _cephes.so specfun.so
_cephes.so: Mach-O universal binary with 2 architectures
_cephes.so (for architecture i386): Mach-O bundle i386
_cephes.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
specfun.so: Mach-O universal binary with 2 architectures
specfun.so (for architecture i386): Mach-O bundle i386
specfun.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
Ho hum. I'm stuck. Things I may try but haven't figured out how yet include compiling specfun.so myself manually, somehow.
I would imagine that scipy isn't broken for all 32 bit machines, so I guess something is wrong with the way I've installed it, but I can't figure out what.
I don't really expect a full answer given my fairly unique (?) setup, but if anyone has any clues that might point me in the right direction, they'd be greatly appreciated.
(edit) More details to address questions:
I'm using gfortran (GNU Fortran from GCC 4.2.1 Apple Inc. build 5646).
Python 2.6.4 was installed more-or-less like so:
cd /tmp
curl -O http://www.python.org/ftp/python/2.6.4/Python-2.6.4.tar.bz2
tar xf Python-2.6.4.tar.bz2
cd Python-2.6.4
# Now replace buggy pythonw.c file with one that supports the "arch" command:
curl http://bugs.python.org/file14949/pythonw.c | sed s/2.7/2.6/ > Mac/Tools/pythonw.c
./configure --enable-framework=/Library/Frameworks --enable-universalsdk=/ --with-universal-archs=intel
make -j4
sudo make frameworkinstall
Scipy 0.7.1 was installed pretty much as described as here, but it boils down to a simple sudo python setup.py install.
It would indeed appear that the symbol is undefined in the i386 architecture if you look at the _cephes library with nm, as suggested by David Cournapeau:
$ nm -arch x86_64 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so | grep _aswfa_
00000000000d4950 T _aswfa_
000000000011e4b0 d _oblate_aswfa_data
000000000011e510 d _oblate_aswfa_nocv_data
(snip)
$ nm -arch i386 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so | grep _aswfa_
U _aswfa_
0002e96c d _oblate_aswfa_data
0002e99c d _oblate_aswfa_nocv_data
(snip)
however, I can't yet explain its absence.
A:
Have you tried using scipy compiled using macports?
sudo port install scipy +universal
(of course you must have the rest of the chain, python, py26-numpycompiled with the same option)
I get:
$ arch -x86_64 /opt/local/bin/python -c "import scipy.interpolate; print 'success'"
success
$ arch -i386 /opt/local/bin/python -c "import scipy.interpolate; print 'success'"
success
you may then use the setting and knowledge that the macports maintainers used to make your own compilation.
A:
How did you install scipy, for which python version, and with which fortran compiler ?
You may also want to check that the missing symbol is indeed in both archs (I don't remember off-hand where the function is, but you should be able to find ti by yourself pretty easily using a combination of nm/otool).
|
Mac 10.6 Universal Binary scipy: cephes/specfun "_aswfa_" symbol not found
|
I can't get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1.
My python setup
With the help of this answer, I built a 32/64 bit intel universal binary of python 2.6.4 with the intention of using the arch command to select between the architectures. (I managed to make some universal binaries of a few libraries I wanted using lipo.) That all works. I then installed scipy according to the instructions on hyperjeff's article, only with more up-to-date numpy (1.4.0) and skipping the bit about moving numpy aside briefly during the installation of scipy.
Now, everything except scipy seems to be working as far as I can tell, and I can indeed select between 32 and 64 bit mode using arch -i386 python and arch -x86_64 python.
The error
Scipy complains in 32 bit mode:
$ arch -x86_64 python -c "import scipy.interpolate; print 'success'"
success
$ arch -i386 python -c "import scipy.interpolate; print 'success'"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/interpolate/__init__.py", line 7, in <module>
from interpolate import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/interpolate/interpolate.py", line 13, in <module>
import scipy.special as spec
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/__init__.py", line 8, in <module>
from basic import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/basic.py", line 8, in <module>
from _cephes import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so, 2): Symbol not found: _aswfa_
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so
Attempt at tracking down the problem
It looks like scipy.interpolate imports something called _cephes, which looks for a symbol called _aswfa_ but can't find it in 32 bit mode. Browsing through scipy's source, I find an ASWFA subroutine in specfun.f. The only scipy product file with a similar name is specfun.so, but both that and _cephes.so appear to be universal binaries:
$ cd /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/
$ file _cephes.so specfun.so
_cephes.so: Mach-O universal binary with 2 architectures
_cephes.so (for architecture i386): Mach-O bundle i386
_cephes.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
specfun.so: Mach-O universal binary with 2 architectures
specfun.so (for architecture i386): Mach-O bundle i386
specfun.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
Ho hum. I'm stuck. Things I may try but haven't figured out how yet include compiling specfun.so myself manually, somehow.
I would imagine that scipy isn't broken for all 32 bit machines, so I guess something is wrong with the way I've installed it, but I can't figure out what.
I don't really expect a full answer given my fairly unique (?) setup, but if anyone has any clues that might point me in the right direction, they'd be greatly appreciated.
(edit) More details to address questions:
I'm using gfortran (GNU Fortran from GCC 4.2.1 Apple Inc. build 5646).
Python 2.6.4 was installed more-or-less like so:
cd /tmp
curl -O http://www.python.org/ftp/python/2.6.4/Python-2.6.4.tar.bz2
tar xf Python-2.6.4.tar.bz2
cd Python-2.6.4
# Now replace buggy pythonw.c file with one that supports the "arch" command:
curl http://bugs.python.org/file14949/pythonw.c | sed s/2.7/2.6/ > Mac/Tools/pythonw.c
./configure --enable-framework=/Library/Frameworks --enable-universalsdk=/ --with-universal-archs=intel
make -j4
sudo make frameworkinstall
Scipy 0.7.1 was installed pretty much as described as here, but it boils down to a simple sudo python setup.py install.
It would indeed appear that the symbol is undefined in the i386 architecture if you look at the _cephes library with nm, as suggested by David Cournapeau:
$ nm -arch x86_64 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so | grep _aswfa_
00000000000d4950 T _aswfa_
000000000011e4b0 d _oblate_aswfa_data
000000000011e510 d _oblate_aswfa_nocv_data
(snip)
$ nm -arch i386 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/special/_cephes.so | grep _aswfa_
U _aswfa_
0002e96c d _oblate_aswfa_data
0002e99c d _oblate_aswfa_nocv_data
(snip)
however, I can't yet explain its absence.
|
[
"Have you tried using scipy compiled using macports?\nsudo port install scipy +universal\n\n(of course you must have the rest of the chain, python, py26-numpycompiled with the same option)\nI get:\n$ arch -x86_64 /opt/local/bin/python -c \"import scipy.interpolate; print 'success'\"\nsuccess\n\n$ arch -i386 /opt/local/bin/python -c \"import scipy.interpolate; print 'success'\"\nsuccess\n\nyou may then use the setting and knowledge that the macports maintainers used to make your own compilation. \n",
"How did you install scipy, for which python version, and with which fortran compiler ?\nYou may also want to check that the missing symbol is indeed in both archs (I don't remember off-hand where the function is, but you should be able to find ti by yourself pretty easily using a combination of nm/otool).\n"
] |
[
3,
1
] |
[] |
[] |
[
"architecture",
"osx_snow_leopard",
"python",
"scipy",
"universal_binary"
] |
stackoverflow_0002155986_architecture_osx_snow_leopard_python_scipy_universal_binary.txt
|
Q:
Why str has no __radd__ method in Python?
str has other methods like __rmod__, __rsub__ or __rmul__
int did have a __radd__ method
Weird, and I'd like to know why.
Example radd beeing called when first term HAS add method:
>>> class STR(str):
... def __radd__(self, other):
... print "jeje"
... return other.__add__(self)
...
>>> 'aaaaa' + STR('bbbbb')
jeje
'aaaaabbbbb'
A:
__radd__ is used when the first term of the addition does not implement __add__. In the case of int, addition is well defined by its mathematical definition, and so int tries to coerce the other term into a number.
with str, there is no such well defined meaning, and the developers of python have decided that there is no obvious need to have something + "a string".
A:
Types only define methods that they use. Since the only objects that can be added to strings are other strings or unicode objects, there is no need for a general __radd__ method. __rmul__ allows you to duplicate strings:
>>> 4 * 'abc'
'abcabcabcabc'
I'm not sure why __rmod__ is needed, but it is somehow related to formatting. Perhaps it eases the implementation of formatting with a single argument, as in "Hello %s" % 'world'. I'm not sure. Contrary to your assertion, there is no __rsub__ on str objects.
In short, those methods are only defined if they actually do something.
|
Why str has no __radd__ method in Python?
|
str has other methods like __rmod__, __rsub__ or __rmul__
int did have a __radd__ method
Weird, and I'd like to know why.
Example radd beeing called when first term HAS add method:
>>> class STR(str):
... def __radd__(self, other):
... print "jeje"
... return other.__add__(self)
...
>>> 'aaaaa' + STR('bbbbb')
jeje
'aaaaabbbbb'
|
[
"__radd__ is used when the first term of the addition does not implement __add__. In the case of int, addition is well defined by its mathematical definition, and so int tries to coerce the other term into a number. \nwith str, there is no such well defined meaning, and the developers of python have decided that there is no obvious need to have something + \"a string\".\n",
"Types only define methods that they use. Since the only objects that can be added to strings are other strings or unicode objects, there is no need for a general __radd__ method. __rmul__ allows you to duplicate strings:\n>>> 4 * 'abc'\n'abcabcabcabc'\n\nI'm not sure why __rmod__ is needed, but it is somehow related to formatting. Perhaps it eases the implementation of formatting with a single argument, as in \"Hello %s\" % 'world'. I'm not sure. Contrary to your assertion, there is no __rsub__ on str objects. \nIn short, those methods are only defined if they actually do something.\n"
] |
[
5,
2
] |
[] |
[] |
[
"implementation",
"python"
] |
stackoverflow_0002213329_implementation_python.txt
|
Q:
How to store python classes into a database with Django?
I have two files:
choices.py
class SomeChoice:
name = u"lorem"
class AnotherChoice:
name = u"ipsum"
# etc...
models.py
from django.db import models
import choices
class SomeModel(models.Model):
CHOICES = (
(1, choices.SomeChoice.name),
(2, choices.AnotherChoice.name),
# etc...
)
somefield = models.IntegerField('field', choices=CHOICES)
The problem: classes from choices.py need something like a primary key to be stored in my database. Here I write these keys (1, 2, ...) by hand, but this is ugly.
For instance, I don't want to do that:
class SomeChoice:
id = 1
name = "lorem"
class AnotherChoice:
id = 2
name = "lorem"
So my question is: what is the best way to store python classes into a database ?
Please excuse my ugly english. If you need more informations, just tell me. ;-)
A:
You could use pickle to store instances of the classes, but then it would be uglier, and you don't need to store the classes in the database in this case, so don't (you want to avoid hitting the database as much as possible).
To avoid repeating the IDs in two places, you could change the code to something like that:
choices.py
_registry = {}
def register(choice_class):
id = len(_registry) + 1
choice_class.id = id
_registry[id] = choice_class
def as_list():
ret = []
for id in sorted(_registry):
ret.append((id, _registry[id].name))
return ret
def get_choice(id):
return _registry[id]
class SomeChoice:
name = u"lorem"
class AnotherChoice:
name = u"ipsum"
register(SomeChoice)
register(AnotherChoice)
models.py
from django.db import models
import choices
class SomeModel(models.Model):
somefield = models.IntegerField('field', choices=choices.as_list())
A:
What's the value of the SomeChoice and AnotherChoice classes? Why not just store the keys and values in a dictionary (kind of link CHOICES in your SomeModel) and have one new class that just represents a choice,
class UserChoice:
def __init__(self, id, name):
self.id = id
self.name = name
and then you get the same functionality of your SomeChoice and AnotherChoice, but if you add more choices, you don't need more classes. Maybe your example was just over-simplified, but I don't see the value of those classes. Sorry if I missed the point completely.
|
How to store python classes into a database with Django?
|
I have two files:
choices.py
class SomeChoice:
name = u"lorem"
class AnotherChoice:
name = u"ipsum"
# etc...
models.py
from django.db import models
import choices
class SomeModel(models.Model):
CHOICES = (
(1, choices.SomeChoice.name),
(2, choices.AnotherChoice.name),
# etc...
)
somefield = models.IntegerField('field', choices=CHOICES)
The problem: classes from choices.py need something like a primary key to be stored in my database. Here I write these keys (1, 2, ...) by hand, but this is ugly.
For instance, I don't want to do that:
class SomeChoice:
id = 1
name = "lorem"
class AnotherChoice:
id = 2
name = "lorem"
So my question is: what is the best way to store python classes into a database ?
Please excuse my ugly english. If you need more informations, just tell me. ;-)
|
[
"You could use pickle to store instances of the classes, but then it would be uglier, and you don't need to store the classes in the database in this case, so don't (you want to avoid hitting the database as much as possible).\nTo avoid repeating the IDs in two places, you could change the code to something like that:\nchoices.py\n_registry = {}\n\ndef register(choice_class):\n id = len(_registry) + 1\n choice_class.id = id\n _registry[id] = choice_class\n\ndef as_list():\n ret = []\n for id in sorted(_registry):\n ret.append((id, _registry[id].name))\n return ret\n\ndef get_choice(id):\n return _registry[id]\n\nclass SomeChoice:\n name = u\"lorem\"\n\nclass AnotherChoice:\n name = u\"ipsum\"\n\nregister(SomeChoice)\nregister(AnotherChoice)\n\nmodels.py\nfrom django.db import models\nimport choices\n\nclass SomeModel(models.Model):\n somefield = models.IntegerField('field', choices=choices.as_list())\n\n",
"What's the value of the SomeChoice and AnotherChoice classes? Why not just store the keys and values in a dictionary (kind of link CHOICES in your SomeModel) and have one new class that just represents a choice, \nclass UserChoice:\n def __init__(self, id, name):\n self.id = id\n self.name = name\n\nand then you get the same functionality of your SomeChoice and AnotherChoice, but if you add more choices, you don't need more classes. Maybe your example was just over-simplified, but I don't see the value of those classes. Sorry if I missed the point completely.\n"
] |
[
4,
0
] |
[] |
[] |
[
"database",
"django",
"django_models",
"python",
"storing_information"
] |
stackoverflow_0002213402_database_django_django_models_python_storing_information.txt
|
Q:
Access a subset of functions of a Python class
Using a class that has an xmlrpc proxy as one of it's object's properties
def __init__(self):
self.proxy = ServerProxy(...)
# ...
I'm trying to ease the use of some of the proxy's functions. Only a subset of the proxy functions are supposed to be used and I thus thought of creating a set of tiny wrapper functions for them like
def sample(self):
""" A nice docstring for a wrapper function. """
self.proxy.sample()
Is there a good way of getting a list of all the wrapper functions? I'm thinking about something like dir(), but then I would need to filter for the object's wrapper functions. xmlrpc introspection (http://xmlrpc-c.sourceforge.net/introspection.html) doesn't help much either since I don't want to use/ provide all the server's functions.
Maybe setting an attribute on the wrappers together with a @staticmethod get_wrappers() would do the trick. Having a _wrapper suffix is not appropriate for my use case. A static list in the class that keeps track of the available is too error prone. So I'm looking for good ideas on how to best getting a list of the wrapper functions?
A:
I'm not 100% sure if this is what you want, but it works:
def proxy_wrapper(name, docstring):
def wrapper(self, *args, **kwargs):
return self.proxy.__getattribute__(name)(*args, **kwargs)
wrapper.__doc__ = docstring
wrapper._is_wrapper = True
return wrapper
class Something(object):
def __init__(self):
self.proxy = {}
@classmethod
def get_proxy_wrappers(cls):
return [m for m in dir(cls) if hasattr(getattr(cls, m), "_is_wrapper")]
update = proxy_wrapper("update", "wraps the proxy's update() method")
proxy_keys = proxy_wrapper("keys", "wraps the proxy's keys() method")
Then
>>> a = Something()
>>> print a.proxy
{}
>>> a.update({1: 42})
>>> print a.proxy
{1: 42}
>>> a.update({"foo": "bar"})
>>> print a.proxy_keys()
[1, 'foo']
>>> print a.get_proxy_wrappers()
['proxy_keys', 'update']
A:
Use xml-rpc introspection to get the server list and intersect it with your object's properties. Something like:
loc = dir(self)
rem = proxy.listMethods() # However introspection gets a method list
wrapped = [x for x in rem if x in loc]
|
Access a subset of functions of a Python class
|
Using a class that has an xmlrpc proxy as one of it's object's properties
def __init__(self):
self.proxy = ServerProxy(...)
# ...
I'm trying to ease the use of some of the proxy's functions. Only a subset of the proxy functions are supposed to be used and I thus thought of creating a set of tiny wrapper functions for them like
def sample(self):
""" A nice docstring for a wrapper function. """
self.proxy.sample()
Is there a good way of getting a list of all the wrapper functions? I'm thinking about something like dir(), but then I would need to filter for the object's wrapper functions. xmlrpc introspection (http://xmlrpc-c.sourceforge.net/introspection.html) doesn't help much either since I don't want to use/ provide all the server's functions.
Maybe setting an attribute on the wrappers together with a @staticmethod get_wrappers() would do the trick. Having a _wrapper suffix is not appropriate for my use case. A static list in the class that keeps track of the available is too error prone. So I'm looking for good ideas on how to best getting a list of the wrapper functions?
|
[
"I'm not 100% sure if this is what you want, but it works:\ndef proxy_wrapper(name, docstring):\n def wrapper(self, *args, **kwargs):\n return self.proxy.__getattribute__(name)(*args, **kwargs)\n wrapper.__doc__ = docstring\n wrapper._is_wrapper = True\n return wrapper\n\nclass Something(object):\n def __init__(self):\n self.proxy = {}\n\n @classmethod\n def get_proxy_wrappers(cls):\n return [m for m in dir(cls) if hasattr(getattr(cls, m), \"_is_wrapper\")]\n\n update = proxy_wrapper(\"update\", \"wraps the proxy's update() method\")\n proxy_keys = proxy_wrapper(\"keys\", \"wraps the proxy's keys() method\") \n\nThen\n>>> a = Something()\n>>> print a.proxy\n{}\n>>> a.update({1: 42})\n>>> print a.proxy\n{1: 42}\n>>> a.update({\"foo\": \"bar\"})\n>>> print a.proxy_keys()\n[1, 'foo']\n>>> print a.get_proxy_wrappers()\n['proxy_keys', 'update']\n\n",
"Use xml-rpc introspection to get the server list and intersect it with your object's properties. Something like:\nloc = dir(self)\nrem = proxy.listMethods() # However introspection gets a method list\nwrapped = [x for x in rem if x in loc]\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"python",
"xml_rpc"
] |
stackoverflow_0002213289_python_xml_rpc.txt
|
Q:
Reading request parameters in Python
I am very new to python and having to get into this stuff for a simple program to integrate with an ASP.NET application that I am building. The pseudo code is as follows.
Get two parameters from request. (A ASP.NET will be calling this url by POST and sending two parameters)
Internally execute some business logic and build some response.
Write the response back so that the ASP.NET app can proceed.
Step 2 and 3 are already in place and working too but not able to find a solution for Step 1 (I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python and the online docs/tutorials are not helping my cause). I am running python on apache using mod_python.
Any help here is greatly appreciated. Thanks in advance
Vijay
A:
Here is a good beginner's tutorial for mod_python.
As far as I understand your question you have a mod_python-based script and you want to read a POST parameter. Therefore you only have to use the form object which is automatically provided by mod_python:
myparameter = form.getfirst("name_of_the_post_parameter")
You can find the documentation over here.
Note that this solution is when your server is configured with PythonHandler mod_python.psp which will allow you to use "Python Server Pages" (special <% %> tags, automatically created variables like form, ...). If you're writing a normal mod_python handler, then it would look something like that:
from mod_python import util
def handler(req):
form = util.FieldStorage(req, keep_blank_values=1)
myparameter = form.getfirst("name_of_the_post_parameter")
...other stuff...
A:
"I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python"
Well, it's not simple in Python -- the language.
It is simple in many Python web frameworks.
Don't make the mistake of comparing Python (the language) with PHP (the web framework) or RoR (the web framework).
Python, like Java or VB or Ruby, is a programming language. Not a web framework.
To get stuff from Apache into Python you have three choices.
A CGI script. A dreadful choice.
mod_python. Not a great choice.
mod_wsgi. A much better choice.
If you're stuck with mod_python -- because this is homework, for instance -- you'll need to read a mod_python tutorial in addition to a python tutorial.
This, for example, seems to be what you're doing. http://www.modpython.org/live/current/doc-html/tut-pub.html
|
Reading request parameters in Python
|
I am very new to python and having to get into this stuff for a simple program to integrate with an ASP.NET application that I am building. The pseudo code is as follows.
Get two parameters from request. (A ASP.NET will be calling this url by POST and sending two parameters)
Internally execute some business logic and build some response.
Write the response back so that the ASP.NET app can proceed.
Step 2 and 3 are already in place and working too but not able to find a solution for Step 1 (I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python and the online docs/tutorials are not helping my cause). I am running python on apache using mod_python.
Any help here is greatly appreciated. Thanks in advance
Vijay
|
[
"Here is a good beginner's tutorial for mod_python.\nAs far as I understand your question you have a mod_python-based script and you want to read a POST parameter. Therefore you only have to use the form object which is automatically provided by mod_python:\nmyparameter = form.getfirst(\"name_of_the_post_parameter\")\n\nYou can find the documentation over here.\nNote that this solution is when your server is configured with PythonHandler mod_python.psp which will allow you to use \"Python Server Pages\" (special <% %> tags, automatically created variables like form, ...). If you're writing a normal mod_python handler, then it would look something like that:\nfrom mod_python import util\n\ndef handler(req):\n form = util.FieldStorage(req, keep_blank_values=1)\n myparameter = form.getfirst(\"name_of_the_post_parameter\")\n ...other stuff...\n\n",
"\"I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python\"\nWell, it's not simple in Python -- the language.\nIt is simple in many Python web frameworks.\nDon't make the mistake of comparing Python (the language) with PHP (the web framework) or RoR (the web framework).\nPython, like Java or VB or Ruby, is a programming language. Not a web framework.\nTo get stuff from Apache into Python you have three choices.\n\nA CGI script. A dreadful choice.\nmod_python. Not a great choice.\nmod_wsgi. A much better choice.\n\nIf you're stuck with mod_python -- because this is homework, for instance -- you'll need to read a mod_python tutorial in addition to a python tutorial.\nThis, for example, seems to be what you're doing. http://www.modpython.org/live/current/doc-html/tut-pub.html\n"
] |
[
5,
0
] |
[] |
[] |
[
"mod_python",
"parameters",
"python",
"request"
] |
stackoverflow_0002213191_mod_python_parameters_python_request.txt
|
Q:
Changing the hour with datetime.replace() in python
Given that foo is a valid datetime object in python,
One can change the hour represented in a datestamp (foo) by doing something something like:
foo2 = foo.replace( hour=5 )
Rather then replacing the hour with a particular value ( as is done above )..is it possible to increment the time in foo by say, 5 hours ? Something along the lines of:
foo2 = foo.replace( hour += 5 )
Which I know is not correct...but maybe that explains better what I am aiming to do...
I am limited to using python 2.5.1 ( the version on OS X 10.5.x) .. and am not able to add any modules such as pyTZ
A:
That's what timedelta is for:
>>> import datetime
>>> d = datetime.datetime(2010, 12, 25, 18, 25)
>>> d + datetime.timedelta(hours = 8)
datetime.datetime(2010, 12, 26, 2, 25)
|
Changing the hour with datetime.replace() in python
|
Given that foo is a valid datetime object in python,
One can change the hour represented in a datestamp (foo) by doing something something like:
foo2 = foo.replace( hour=5 )
Rather then replacing the hour with a particular value ( as is done above )..is it possible to increment the time in foo by say, 5 hours ? Something along the lines of:
foo2 = foo.replace( hour += 5 )
Which I know is not correct...but maybe that explains better what I am aiming to do...
I am limited to using python 2.5.1 ( the version on OS X 10.5.x) .. and am not able to add any modules such as pyTZ
|
[
"That's what timedelta is for:\n>>> import datetime\n>>> d = datetime.datetime(2010, 12, 25, 18, 25)\n>>> d + datetime.timedelta(hours = 8)\ndatetime.datetime(2010, 12, 26, 2, 25)\n\n"
] |
[
26
] |
[] |
[] |
[
"datetime",
"macos",
"python"
] |
stackoverflow_0002213682_datetime_macos_python.txt
|
Q:
How to avoid computation every time a python module is reloaded
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.
To give more information about my problem,
FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min
A:
Just to clarify: the code in the body of a module is not executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.
However, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules.
For a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example:
# Create dict with a million items:
import shelve
d = shelve.open('path/to/my_persistant_dict')
d.update(('key%d' % x, x) for x in xrange(1000000))
d.close()
Then in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory:
>>> d = shelve.open('path/to/my_persistant_dict')
>>> print d['key99999']
99999
It's a bit slower than a real dict, and it will still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.
A:
Calculate your global var on the first use.
class Proxy:
@property
def global_name(self):
# calculate your global var here, enable cache if needed
...
_proxy_object = Proxy()
GLOBAL_NAME = _proxy_object.global_name
Or better yet, access necessery data via special data object.
class Data:
GLOBAL_NAME = property(...)
data = Data()
Example:
from some_module import data
print(data.GLOBAL_NAME)
See Django settings.
A:
I assume you've pasted the dict literal into the source, and that's what's taking a minute? I don't know how to get around that, but you could probably avoid instantiating this dict upon import... You could lazily-instantiate it the first time it's actually used.
A:
You could try using the marshal module instead of the c?Pickle one; it could be faster. This module is used by python to store values in a binary format. Note especially the following paragraph, to see if marshal fits your needs:
Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: None, integers, long integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, dictionaries, and code objects, where it should be understood that tuples, lists and dictionaries are only supported as long as the values contained therein are themselves supported; and recursive lists and dictionaries should not be written (they will cause infinite loops).
Just to be on the safe side, before unmarshalling the dict, make sure that the Python version that unmarshals the dict is the same as the one that did the marshal, since there are no guarantees for backwards compatibility.
A:
If the 'shelve' solution turns out to be too slow or fiddly, there are other possibilities:
shove
Durus
ZopeDB
pyTables
A:
shelve gets really slow with large data sets. I've been using redis quite successfully, and wrote a FreqDist wrapper around it. It's very fast, and can be accessed concurrently.
A:
You can use a shelve to store your data on disc instead of loading the whole data into memory. So startup time will be very fast, but the trade-off will be slower access time.
Shelve will pickle the dict values too, but will do the (un)pickle not at startup for all the items, but only at access time for each item itself.
A:
A couple of things that will help speed up imports:
You might try running python using the -OO flag when running python. This will do some optimizations that will reduce import time of modules.
Is there any reason why you couldn't break the dictionary up into smaller dictionaries in separate modules that can be loaded more quickly?
As a last resort, you could do the calculations asynchronously so that they won't delay your program until it needs the results. Or maybe even put the dictionary in a separate process and pass data back and forth using IPC if you want to take advantage of multi-core architectures.
With that said, I agree that you shouldn't be experiencing any delay in importing modules after the first time you import it. Here are a couple of other general thoughts:
Are you importing the module within a function? If so, this can lead to performance problems since it has to check and see if the module is loaded every time it hits the import statement.
Is your program multi-threaded? I have seen occassions where executing code upon module import in a multi-threaded app can cause some wonkiness and application instability (most notably with the cgitb module).
If this is a global variable, be aware that global variable lookup times can be significantly longer than local variable lookup times. In this case, you can achieve a significant performance improvement by binding the dictionary to a local variable if you're using it multiple times in the same context.
With that said, it's a tad bit difficult to give you any specific advice without a little bit more context. More specifically, where are you importing it? And what are the computations?
A:
Factor the computationally intensive part into a separate module. Then at least on reload, you won't have to wait.
Try dumping the data structure using protocol 2. The command to try would be cPickle.dump(FD, protocol=2). From the docstring for cPickle.Pickler:
Protocol 0 is the
only protocol that can be written to a file opened in text
mode and read back successfully. When using a protocol higher
than 0, make sure the file is opened in binary mode, both when
pickling and unpickling.
A:
I'm going through this same issue...
shelve, databases, etc... are all too slow for this type of problem. You'll need to take the hit once, insert it into an inmemory key/val store like Redis. It will just live there in memory (warning it could use up a good amount of memory so you may want a dedicated box). You'll never have to reload it and you'll just get looking in memory for keys
r = Redis()
r.set(key, word)
word = r.get(key)
A:
Expanding on the delayed-calculation idea, why not turn the dict into a class that supplies (and caches) elements as necessary?
You might also use psyco to speed up overall execution...
A:
OR you could just use a database for storing the values in? Check out SQLObject, which makes it very easy to store stuff to a database.
A:
There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.
So... doing something like this will make sure this code is executed only once.
try:
FD
except NameError:
FD = FreqDist(word for word in brown.words())
|
How to avoid computation every time a python module is reloaded
|
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.
To give more information about my problem,
FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min
|
[
"Just to clarify: the code in the body of a module is not executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.\nHowever, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules.\nFor a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example:\n# Create dict with a million items:\nimport shelve\nd = shelve.open('path/to/my_persistant_dict')\nd.update(('key%d' % x, x) for x in xrange(1000000))\nd.close()\n\nThen in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory:\n>>> d = shelve.open('path/to/my_persistant_dict')\n>>> print d['key99999']\n99999\n\nIt's a bit slower than a real dict, and it will still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.\n",
"Calculate your global var on the first use.\nclass Proxy:\n @property\n def global_name(self):\n # calculate your global var here, enable cache if needed\n ...\n\n_proxy_object = Proxy()\nGLOBAL_NAME = _proxy_object.global_name\n\nOr better yet, access necessery data via special data object.\nclass Data:\n GLOBAL_NAME = property(...)\n\ndata = Data()\n\nExample:\nfrom some_module import data\n\nprint(data.GLOBAL_NAME)\n\nSee Django settings.\n",
"I assume you've pasted the dict literal into the source, and that's what's taking a minute? I don't know how to get around that, but you could probably avoid instantiating this dict upon import... You could lazily-instantiate it the first time it's actually used.\n",
"You could try using the marshal module instead of the c?Pickle one; it could be faster. This module is used by python to store values in a binary format. Note especially the following paragraph, to see if marshal fits your needs:\n\nNot all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: None, integers, long integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, dictionaries, and code objects, where it should be understood that tuples, lists and dictionaries are only supported as long as the values contained therein are themselves supported; and recursive lists and dictionaries should not be written (they will cause infinite loops). \n\nJust to be on the safe side, before unmarshalling the dict, make sure that the Python version that unmarshals the dict is the same as the one that did the marshal, since there are no guarantees for backwards compatibility.\n",
"If the 'shelve' solution turns out to be too slow or fiddly, there are other possibilities:\n\nshove\nDurus\nZopeDB\npyTables\n\n",
"shelve gets really slow with large data sets. I've been using redis quite successfully, and wrote a FreqDist wrapper around it. It's very fast, and can be accessed concurrently.\n",
"You can use a shelve to store your data on disc instead of loading the whole data into memory. So startup time will be very fast, but the trade-off will be slower access time. \nShelve will pickle the dict values too, but will do the (un)pickle not at startup for all the items, but only at access time for each item itself.\n",
"A couple of things that will help speed up imports:\n\nYou might try running python using the -OO flag when running python. This will do some optimizations that will reduce import time of modules.\nIs there any reason why you couldn't break the dictionary up into smaller dictionaries in separate modules that can be loaded more quickly?\nAs a last resort, you could do the calculations asynchronously so that they won't delay your program until it needs the results. Or maybe even put the dictionary in a separate process and pass data back and forth using IPC if you want to take advantage of multi-core architectures.\n\nWith that said, I agree that you shouldn't be experiencing any delay in importing modules after the first time you import it. Here are a couple of other general thoughts:\n\nAre you importing the module within a function? If so, this can lead to performance problems since it has to check and see if the module is loaded every time it hits the import statement.\nIs your program multi-threaded? I have seen occassions where executing code upon module import in a multi-threaded app can cause some wonkiness and application instability (most notably with the cgitb module).\nIf this is a global variable, be aware that global variable lookup times can be significantly longer than local variable lookup times. In this case, you can achieve a significant performance improvement by binding the dictionary to a local variable if you're using it multiple times in the same context.\n\nWith that said, it's a tad bit difficult to give you any specific advice without a little bit more context. More specifically, where are you importing it? And what are the computations?\n",
"\nFactor the computationally intensive part into a separate module. Then at least on reload, you won't have to wait. \nTry dumping the data structure using protocol 2. The command to try would be cPickle.dump(FD, protocol=2). From the docstring for cPickle.Pickler:\n\nProtocol 0 is the\nonly protocol that can be written to a file opened in text\nmode and read back successfully. When using a protocol higher\nthan 0, make sure the file is opened in binary mode, both when\npickling and unpickling. \n\n\n\n",
"I'm going through this same issue... \nshelve, databases, etc... are all too slow for this type of problem. You'll need to take the hit once, insert it into an inmemory key/val store like Redis. It will just live there in memory (warning it could use up a good amount of memory so you may want a dedicated box). You'll never have to reload it and you'll just get looking in memory for keys\nr = Redis()\nr.set(key, word)\n\nword = r.get(key)\n\n",
"Expanding on the delayed-calculation idea, why not turn the dict into a class that supplies (and caches) elements as necessary?\nYou might also use psyco to speed up overall execution...\n",
"OR you could just use a database for storing the values in? Check out SQLObject, which makes it very easy to store stuff to a database.\n",
"There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.\nSo... doing something like this will make sure this code is executed only once.\ntry:\n FD\nexcept NameError:\n FD = FreqDist(word for word in brown.words())\n\n"
] |
[
17,
4,
2,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"nltk",
"python"
] |
stackoverflow_0000195626_nltk_python.txt
|
Q:
how do people normally deal with class variables in django?
I can't see any provision for this in the django docs, so how do people go about doing this.
My specific case is this.
I have a shopping cart, each cart instance has an invoice number field, however the invoice number is only generated if the cart goes to a paid status, so not all shopping cart instances will have an invoice number. I want all invoice numbers to be sequential with no gaps between them, so the default pk isn't perfect in this case, so I want a class variable that acts as a counter for the invoice numbers, and is accessable by all instances.
A:
The default primary key will already be a unique monotonic integer (even in SQLite if you don't delete any records), so you can just use that for it.
A:
You can create a field in a model and state it as primary key or use your current primary key if you are migrating a legacy database primary_key=True.
Django ORM has no support for complex keys. It doesn't allow you to use a table without primary key.
If you need a specific logic for your invoice number generation (for example # of client + '-' + year number), you can create a field for this key, but this will not be a primary key. Call this key generation function on object save in Model.save function if this key is not specified for current object yet.
A:
Have your invoice field in your model:
class Cart(models.Model):
.....
invoice_id = models.PositiveIntegerField(null=True,unique=True)
Only set the value when appropriate.
To find the next ID:
try:
nextID = Cart.objects.exclude(invoice_id=None).order_by('-invoice_id')[0].invoice_id + 1
except IndexError:
nextID = 1
Having thought about it some more... it occurs to me that invoices might be better served as a separate model. You can link them to your carts with ForeignKey("invoice",null=True). They can then be created when needed, the default primary key field can be your monotonically increasing number, and can then have a separate life-cycle to your cart objects.
|
how do people normally deal with class variables in django?
|
I can't see any provision for this in the django docs, so how do people go about doing this.
My specific case is this.
I have a shopping cart, each cart instance has an invoice number field, however the invoice number is only generated if the cart goes to a paid status, so not all shopping cart instances will have an invoice number. I want all invoice numbers to be sequential with no gaps between them, so the default pk isn't perfect in this case, so I want a class variable that acts as a counter for the invoice numbers, and is accessable by all instances.
|
[
"The default primary key will already be a unique monotonic integer (even in SQLite if you don't delete any records), so you can just use that for it.\n",
"You can create a field in a model and state it as primary key or use your current primary key if you are migrating a legacy database primary_key=True.\nDjango ORM has no support for complex keys. It doesn't allow you to use a table without primary key. \nIf you need a specific logic for your invoice number generation (for example # of client + '-' + year number), you can create a field for this key, but this will not be a primary key. Call this key generation function on object save in Model.save function if this key is not specified for current object yet.\n",
"Have your invoice field in your model:\nclass Cart(models.Model):\n .....\n invoice_id = models.PositiveIntegerField(null=True,unique=True)\n\nOnly set the value when appropriate.\nTo find the next ID:\ntry:\n nextID = Cart.objects.exclude(invoice_id=None).order_by('-invoice_id')[0].invoice_id + 1\nexcept IndexError:\n nextID = 1\n\nHaving thought about it some more... it occurs to me that invoices might be better served as a separate model. You can link them to your carts with ForeignKey(\"invoice\",null=True). They can then be created when needed, the default primary key field can be your monotonically increasing number, and can then have a separate life-cycle to your cart objects.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django_models",
"python"
] |
stackoverflow_0002213595_django_models_python.txt
|
Q:
pyparsing question
This code works:
from pyparsing import *
zipRE = "\d{5}(?:[-\s]\d{4})?"
fooRE = "^\!\s+.*"
zipcode = Regex( zipRE )
foo = Regex( fooRE )
query = ( zipcode | foo )
tests = [ "80517", "C6H5OH", "90001-3234", "! sfs" ]
for t in tests:
try:
results = query.parseString( t )
print t,"->", results
except ParseException, pe:
print pe
I'm stuck on two issues:
1 - How to use a custom function to parse a token. For instance, if I wanted to use some custom logic instead of a regex to determine if a number is a zipcode.
Instead of:
zipcode = Regex( zipRE )
perhaps:
zipcode = MyFunc()
2 - How do I determine what a string parses TO. "80001" parses to "zipcode" but how do I determine this using pyparsing? I'm not parsing a string for its contents but simply to determine what kind of query it is.
A:
You could use zipcode and foo separately, so that you know which one the string matches.
zipresults = zipcode.parseString( t )
fooresults = foo.parseString( t )
A:
I do not have the pyparsing module, but Regex must be a class, not a function.
What you can do is subclass from it and override methods as required to customize behaviour, then use your subclasses instead.
A:
Your second question is easy, so I'll answer that first. Change query to assign results names to the different expressions:
query = ( zipcode("zip") | foo("foo") )
Now you can call getName() on the returned result:
print t,"->", results, results.getName()
Giving:
80517 -> ['80517'] zip
Expected Re:('\\d{5}(?:[-\\s]\\d{4})?') (at char 0), (line:1, col:1)
90001-3234 -> ['90001-3234'] zip
! sfs -> ['! sfs'] foo
If you are going to use the result's fooness or zipness to call another function, then you could do this at parse time by attaching a parse action to your foo and zipcode expressions:
# enclose zipcodes in '*'s, foos in '#'s
zipcode.setParseAction(lambda t: '*' + t[0] + '*')
foo.setParseAction(lambda t: '#' + t[0] + '#')
query = ( zipcode("zip") | foo("foo") )
Now gives:
80517 -> ['*80517*'] zip
Expected Re:('\\d{5}(?:[-\\s]\\d{4})?') (at char 0), (line:1, col:1)
90001-3234 -> ['*90001-3234*'] zip
! sfs -> ['#! sfs#'] foo
For your first question, I don't exactly know what kind of function you mean. Pyparsing provides many more parsing classes than just Regex (such as Word, Keyword, Literal, CaselessLiteral), and you compose your parser by combining them with '+', '|', '^', '~', '@' and '*' operators. For instance, if you wanted to parse for a US social security number, but not use a Regex, you could use:
ssn = Combine(Word(nums,exact=3) + '-' +
Word(nums,exact=2) + '-' + Word(nums,exact=4))
Word matches for contiguous "words" made up of the given characters in its constructor, Combine concatenates the matched tokens into a single token.
If you wanted to parse for a potential list of such numbers, delimited by '/'s, use:
delimitedList(ssn, '/')
or if there were between 1 and 3 such numbers, with no delimters, use:
ssn * (1,3)
And any expression can have results names or parse actions attached to them, to further enrich the parsed results, or the functionality during parsing. You can even build recursive parsers, such as nested lists of parentheses, arithmetic expressions, etc. using the Forward class.
My intent when I wrote pyparsing was that this composition of parsers from basic building blocks would be the primary form for creating a parser. It was only in a later release that I added Regex as (what I though was) the ultimate escape valve - if people couldn't build up their parser, they could fall back on regex's format, which has definitely proven its power over time.
Or, as one other poster suggests, you can open up the pyparsing source, and subclass one of the existing classes, or write your own, following their structure. Here is a class that would match for paired characters:
class PairOf(Token):
"""Token for matching words composed of a pair
of characters in a given set.
"""
def __init__( self, chars ):
super(PairOf,self).__init__()
self.pair_chars = set(chars)
def parseImpl( self, instring, loc, doActions=True ):
if (loc < len(instring)-1 and
instring[loc] in self.pair_chars and
instring[loc+1] == instring[loc]):
return loc+2, instring[loc:loc+2]
else:
raise ParseException(instring, loc, "Not at a pair of characters")
So that:
punc = r"~!@#$%^&*_-+=|\?/"
parser = OneOrMore(Word(alphas) | PairOf(punc))
print parser.parseString("Does ** this match @@@@ %% the parser?")
Gives:
['Does', '**', 'this', 'match', '@@', '@@', '%%', 'the', 'parser']
(Note the omission of the trailing single '?')
|
pyparsing question
|
This code works:
from pyparsing import *
zipRE = "\d{5}(?:[-\s]\d{4})?"
fooRE = "^\!\s+.*"
zipcode = Regex( zipRE )
foo = Regex( fooRE )
query = ( zipcode | foo )
tests = [ "80517", "C6H5OH", "90001-3234", "! sfs" ]
for t in tests:
try:
results = query.parseString( t )
print t,"->", results
except ParseException, pe:
print pe
I'm stuck on two issues:
1 - How to use a custom function to parse a token. For instance, if I wanted to use some custom logic instead of a regex to determine if a number is a zipcode.
Instead of:
zipcode = Regex( zipRE )
perhaps:
zipcode = MyFunc()
2 - How do I determine what a string parses TO. "80001" parses to "zipcode" but how do I determine this using pyparsing? I'm not parsing a string for its contents but simply to determine what kind of query it is.
|
[
"You could use zipcode and foo separately, so that you know which one the string matches.\nzipresults = zipcode.parseString( t )\nfooresults = foo.parseString( t )\n\n",
"I do not have the pyparsing module, but Regex must be a class, not a function.\nWhat you can do is subclass from it and override methods as required to customize behaviour, then use your subclasses instead.\n",
"Your second question is easy, so I'll answer that first. Change query to assign results names to the different expressions:\nquery = ( zipcode(\"zip\") | foo(\"foo\") ) \n\nNow you can call getName() on the returned result:\nprint t,\"->\", results, results.getName()\n\nGiving:\n80517 -> ['80517'] zip\nExpected Re:('\\\\d{5}(?:[-\\\\s]\\\\d{4})?') (at char 0), (line:1, col:1)\n90001-3234 -> ['90001-3234'] zip\n! sfs -> ['! sfs'] foo\n\nIf you are going to use the result's fooness or zipness to call another function, then you could do this at parse time by attaching a parse action to your foo and zipcode expressions:\n# enclose zipcodes in '*'s, foos in '#'s\nzipcode.setParseAction(lambda t: '*' + t[0] + '*')\nfoo.setParseAction(lambda t: '#' + t[0] + '#')\n\nquery = ( zipcode(\"zip\") | foo(\"foo\") ) \n\nNow gives:\n80517 -> ['*80517*'] zip\nExpected Re:('\\\\d{5}(?:[-\\\\s]\\\\d{4})?') (at char 0), (line:1, col:1)\n90001-3234 -> ['*90001-3234*'] zip\n! sfs -> ['#! sfs#'] foo\n\nFor your first question, I don't exactly know what kind of function you mean. Pyparsing provides many more parsing classes than just Regex (such as Word, Keyword, Literal, CaselessLiteral), and you compose your parser by combining them with '+', '|', '^', '~', '@' and '*' operators. For instance, if you wanted to parse for a US social security number, but not use a Regex, you could use:\nssn = Combine(Word(nums,exact=3) + '-' + \n Word(nums,exact=2) + '-' + Word(nums,exact=4))\n\nWord matches for contiguous \"words\" made up of the given characters in its constructor, Combine concatenates the matched tokens into a single token.\nIf you wanted to parse for a potential list of such numbers, delimited by '/'s, use:\ndelimitedList(ssn, '/')\n\nor if there were between 1 and 3 such numbers, with no delimters, use:\nssn * (1,3)\n\nAnd any expression can have results names or parse actions attached to them, to further enrich the parsed results, or the functionality during parsing. You can even build recursive parsers, such as nested lists of parentheses, arithmetic expressions, etc. using the Forward class.\nMy intent when I wrote pyparsing was that this composition of parsers from basic building blocks would be the primary form for creating a parser. It was only in a later release that I added Regex as (what I though was) the ultimate escape valve - if people couldn't build up their parser, they could fall back on regex's format, which has definitely proven its power over time.\nOr, as one other poster suggests, you can open up the pyparsing source, and subclass one of the existing classes, or write your own, following their structure. Here is a class that would match for paired characters:\nclass PairOf(Token):\n \"\"\"Token for matching words composed of a pair\n of characters in a given set.\n \"\"\"\n def __init__( self, chars ):\n super(PairOf,self).__init__()\n self.pair_chars = set(chars)\n\n def parseImpl( self, instring, loc, doActions=True ):\n if (loc < len(instring)-1 and \n instring[loc] in self.pair_chars and\n instring[loc+1] == instring[loc]):\n return loc+2, instring[loc:loc+2]\n else:\n raise ParseException(instring, loc, \"Not at a pair of characters\")\n\nSo that:\npunc = r\"~!@#$%^&*_-+=|\\?/\"\nparser = OneOrMore(Word(alphas) | PairOf(punc))\nprint parser.parseString(\"Does ** this match @@@@ %% the parser?\")\n\nGives:\n['Does', '**', 'this', 'match', '@@', '@@', '%%', 'the', 'parser']\n\n(Note the omission of the trailing single '?')\n"
] |
[
3,
2,
2
] |
[] |
[] |
[
"parsing",
"pyparsing",
"python",
"text_parsing"
] |
stackoverflow_0002212860_parsing_pyparsing_python_text_parsing.txt
|
Q:
SQL LIKE in Django/Python
I'm trying to run a query like this:
SELECT *
FROM
MyTable
WHERE
FirstName LIKE '%[user inputted value here]%'
OR
LastName LIKE '%[that same user inputted value]%'
AND
UserID = some number
When I run the query using cursor.execute(), the inputted values are going to be escaped and quoted, which is causing an incorrect query to run. Is there a way to prevent the user inputted values from being quoted?
I'd prefer a solution not using Django's ORM, since the actual query is much more complicated than my example.
A:
Use foo__contains=realvaluehere in your queries.
A:
Hmm, looks like I overestimated the escapy-ness of the API. This works exactly how I want it to
# add wildcards to query, these are **not** escaped
q = "%" + q + "%"
cursor = connection.cursor()
cursor.execute("SELECT *
FROM MyTable
WHERE
LastName LIKE %s
AND
FirstName LIKE %s
AND
UserID = %s", [q, q, user_id])
results = cursor.fetchall()
|
SQL LIKE in Django/Python
|
I'm trying to run a query like this:
SELECT *
FROM
MyTable
WHERE
FirstName LIKE '%[user inputted value here]%'
OR
LastName LIKE '%[that same user inputted value]%'
AND
UserID = some number
When I run the query using cursor.execute(), the inputted values are going to be escaped and quoted, which is causing an incorrect query to run. Is there a way to prevent the user inputted values from being quoted?
I'd prefer a solution not using Django's ORM, since the actual query is much more complicated than my example.
|
[
"Use foo__contains=realvaluehere in your queries.\n",
"Hmm, looks like I overestimated the escapy-ness of the API. This works exactly how I want it to\n# add wildcards to query, these are **not** escaped\nq = \"%\" + q + \"%\"\ncursor = connection.cursor()\ncursor.execute(\"SELECT * \n FROM MyTable \n WHERE \n LastName LIKE %s \n AND \n FirstName LIKE %s \n AND \n UserID = %s\", [q, q, user_id])\nresults = cursor.fetchall()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"python",
"sql"
] |
stackoverflow_0002211695_django_python_sql.txt
|
Q:
How can _meta.local_fields not match the table schema in the database?
I'm completely confused about why _meta.local_fields returns more fields than the database table contains. The User model inherits from contrib.auth.models.User.
$ mysql -u user -p database
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1240032
Server version: 5.0.77 Source distribution
mysql> describe auth_user;
+--------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
| email_isvalid | tinyint(1) | NO | | NULL | |
| email_key | varchar(16) | YES | | NULL | |
| reputation | int(10) unsigned | NO | | NULL | |
| gravatar | varchar(32) | NO | | NULL | |
| gold | smallint(6) | NO | | NULL | |
| silver | smallint(6) | NO | | NULL | |
| bronze | smallint(6) | NO | | NULL | |
| questions_per_page | smallint(6) | NO | | NULL | |
| last_seen | datetime | NO | | NULL | |
| real_name | varchar(100) | NO | | NULL | |
| website | varchar(200) | NO | | NULL | |
| location | varchar(100) | NO | | NULL | |
| date_of_birth | date | YES | | NULL | |
| about | longtext | NO | | NULL | |
+--------------------+------------------+------+-----+---------+----------------+
25 rows in set (0.00 sec)
From the Django error page, this is the SQL statement that generates the error: Exception Value: (1110, "Column 'about' specified twice")
'INSERT INTO `auth_user` (`username`, `first_name`, `last_name`, `email`, `password`, `is_staff`, `is_active`, `is_superuser`, `last_login`, `date_joined`, `email_isvalid`, `email_key`, `reputation`, `gravatar`, `gold`, `silver`, `bronze`, `questions_per_page`, `last_seen`, `real_name`, `website`, `location`, `date_of_birth`, `about`, `email_isvalid`, `email_key`, `reputation`, `gravatar`, `gold`, `silver`, `bronze`, `questions_per_page`, `last_seen`, `real_name`, `website`, `location`, `date_of_birth`, `about`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
This SQL statement seems to be generated by iterating over User._meta.local_fields.
I don't understand why _meta.local_fields doesn't match the actual User table schema.
$ python2.5 manage.py shell
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from forum.models import User
>>> len(User._meta.local_fields)
39
>>> import pprint
>>> pprint.pprint(User._meta.local_fields)
[<django.db.models.fields.AutoField object at 0x852c80c>,
<django.db.models.fields.CharField object at 0x8528c4c>,
<django.db.models.fields.CharField object at 0x8528cac>,
<django.db.models.fields.CharField object at 0x8528d0c>,
<django.db.models.fields.EmailField object at 0x8528d6c>,
<django.db.models.fields.CharField object at 0x8528e2c>,
<django.db.models.fields.BooleanField object at 0x8528ecc>,
<django.db.models.fields.BooleanField object at 0x8528f6c>,
<django.db.models.fields.BooleanField object at 0x852c02c>,
<django.db.models.fields.DateTimeField object at 0x852c0ac>,
<django.db.models.fields.DateTimeField object at 0x852c0ec>,
# here is where customizations to User begin.
<django.db.models.fields.BooleanField object at 0x861744c>,
<django.db.models.fields.CharField object at 0x861732c>,
<django.db.models.fields.PositiveIntegerField object at 0x861746c>,
<django.db.models.fields.CharField object at 0x861748c>,
<django.db.models.fields.SmallIntegerField object at 0x861784c>,
<django.db.models.fields.SmallIntegerField object at 0x86178ec>,
<django.db.models.fields.SmallIntegerField object at 0x861792c>,
<django.db.models.fields.SmallIntegerField object at 0x861796c>,
<django.db.models.fields.DateTimeField object at 0x861798c>,
<django.db.models.fields.CharField object at 0x86179cc>,
<django.db.models.fields.URLField object at 0x8617a0c>,
<django.db.models.fields.CharField object at 0x8617a4c>,
<django.db.models.fields.DateField object at 0x8617a8c>,
<django.db.models.fields.TextField object at 0x8617acc>,
# this seems to be a duplicate of the fields added to User
<django.db.models.fields.BooleanField object at 0x862ab2c>,
<django.db.models.fields.CharField object at 0x862a4ac>,
<django.db.models.fields.PositiveIntegerField object at 0x862ab6c>,
<django.db.models.fields.CharField object at 0x862f6cc>,
<django.db.models.fields.SmallIntegerField object at 0x861782c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa2c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa4c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa8c>,
<django.db.models.fields.DateTimeField object at 0x862faac>,
<django.db.models.fields.CharField object at 0x862faec>,
<django.db.models.fields.URLField object at 0x862fb2c>,
<django.db.models.fields.CharField object at 0x862fb6c>,
<django.db.models.fields.DateField object at 0x862fbac>,
<django.db.models.fields.TextField object at 0x862fbec>]
The additional fields to the model are added thusly:
User.add_to_class('email_isvalid', models.BooleanField(default=False))
User.add_to_class('email_key', models.CharField(max_length=16, null=True))
User.add_to_class('reputation', models.PositiveIntegerField(default=1))
User.add_to_class('gravatar', models.CharField(max_length=32))
User.add_to_class('email_feeds', generic.GenericRelation(EmailFeed))
User.add_to_class('favorite_questions', models.ManyToManyField(Question, through=FavoriteQuestion, related_name='favorited_by'))
User.add_to_class('badges', models.ManyToManyField(Badge, through=Award, related_name='awarded_to'))
User.add_to_class('gold', models.SmallIntegerField(default=0))
User.add_to_class('silver', models.SmallIntegerField(default=0))
User.add_to_class('bronze', models.SmallIntegerField(default=0))
User.add_to_class('questions_per_page', models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10))
User.add_to_class('last_seen', models.DateTimeField(default=datetime.datetime.now))
User.add_to_class('real_name', models.CharField(max_length=100, blank=True))
User.add_to_class('website', models.URLField(max_length=200, blank=True))
User.add_to_class('location', models.CharField(max_length=100, blank=True))
User.add_to_class('date_of_birth', models.DateField(null=True, blank=True))
User.add_to_class('about', models.TextField(blank=True))
I think it's possible that the .add_to_class method may be part of this problem.
A:
It would have been helpful if you showed the Django model that is related to this problem. From the field names in your SQL this model appears to inherit from contrib.auth.models.User, is that true? If so, did you happen to duplicate a field name defined in the User model?
Update: To put it more bluntly, I was asking that you edit your question and include the specific model you declared in your models.py file. It's almost a certainty that you have declared two fields with the same name. The last field declared in auth.models.User is date_joined so both definitions of about should show up in your models declaration.
Actually, on closer inspection of your SQL again, you not only have two columns named about, you have about 14 duplicated field names in there. Something ain't right.
To paraphrase Jerry McGuire: Show me the model! :-)
Second Update (Working with a 1 beer handicap (and it's good stuff!))
I have never used add_to_class in this way. Why did you go this route and not use one of the more standard Django model inheritance techniques? Or, since this is User you are dealing with, why not use UserProfile. It can be a little bit clunky but it works just fine.
Third Update
Ah, Domini Nabisco, my son -- I didn't realize you had inherited this from someone else. A word of caution: because this changed a fundamental class in Django (in a decidedly non-standard way) you may need to look at every single reference to user in both the .py files and the templates. Depending on the size of the inherited project this can be a huge PITA, particularly when it's missing tests. Is there any chance you can hunt down, I mean locate the person responsible and get some more insight? It may be the shorter route to getting things working. Good luck!
|
How can _meta.local_fields not match the table schema in the database?
|
I'm completely confused about why _meta.local_fields returns more fields than the database table contains. The User model inherits from contrib.auth.models.User.
$ mysql -u user -p database
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1240032
Server version: 5.0.77 Source distribution
mysql> describe auth_user;
+--------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
| email_isvalid | tinyint(1) | NO | | NULL | |
| email_key | varchar(16) | YES | | NULL | |
| reputation | int(10) unsigned | NO | | NULL | |
| gravatar | varchar(32) | NO | | NULL | |
| gold | smallint(6) | NO | | NULL | |
| silver | smallint(6) | NO | | NULL | |
| bronze | smallint(6) | NO | | NULL | |
| questions_per_page | smallint(6) | NO | | NULL | |
| last_seen | datetime | NO | | NULL | |
| real_name | varchar(100) | NO | | NULL | |
| website | varchar(200) | NO | | NULL | |
| location | varchar(100) | NO | | NULL | |
| date_of_birth | date | YES | | NULL | |
| about | longtext | NO | | NULL | |
+--------------------+------------------+------+-----+---------+----------------+
25 rows in set (0.00 sec)
From the Django error page, this is the SQL statement that generates the error: Exception Value: (1110, "Column 'about' specified twice")
'INSERT INTO `auth_user` (`username`, `first_name`, `last_name`, `email`, `password`, `is_staff`, `is_active`, `is_superuser`, `last_login`, `date_joined`, `email_isvalid`, `email_key`, `reputation`, `gravatar`, `gold`, `silver`, `bronze`, `questions_per_page`, `last_seen`, `real_name`, `website`, `location`, `date_of_birth`, `about`, `email_isvalid`, `email_key`, `reputation`, `gravatar`, `gold`, `silver`, `bronze`, `questions_per_page`, `last_seen`, `real_name`, `website`, `location`, `date_of_birth`, `about`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
This SQL statement seems to be generated by iterating over User._meta.local_fields.
I don't understand why _meta.local_fields doesn't match the actual User table schema.
$ python2.5 manage.py shell
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from forum.models import User
>>> len(User._meta.local_fields)
39
>>> import pprint
>>> pprint.pprint(User._meta.local_fields)
[<django.db.models.fields.AutoField object at 0x852c80c>,
<django.db.models.fields.CharField object at 0x8528c4c>,
<django.db.models.fields.CharField object at 0x8528cac>,
<django.db.models.fields.CharField object at 0x8528d0c>,
<django.db.models.fields.EmailField object at 0x8528d6c>,
<django.db.models.fields.CharField object at 0x8528e2c>,
<django.db.models.fields.BooleanField object at 0x8528ecc>,
<django.db.models.fields.BooleanField object at 0x8528f6c>,
<django.db.models.fields.BooleanField object at 0x852c02c>,
<django.db.models.fields.DateTimeField object at 0x852c0ac>,
<django.db.models.fields.DateTimeField object at 0x852c0ec>,
# here is where customizations to User begin.
<django.db.models.fields.BooleanField object at 0x861744c>,
<django.db.models.fields.CharField object at 0x861732c>,
<django.db.models.fields.PositiveIntegerField object at 0x861746c>,
<django.db.models.fields.CharField object at 0x861748c>,
<django.db.models.fields.SmallIntegerField object at 0x861784c>,
<django.db.models.fields.SmallIntegerField object at 0x86178ec>,
<django.db.models.fields.SmallIntegerField object at 0x861792c>,
<django.db.models.fields.SmallIntegerField object at 0x861796c>,
<django.db.models.fields.DateTimeField object at 0x861798c>,
<django.db.models.fields.CharField object at 0x86179cc>,
<django.db.models.fields.URLField object at 0x8617a0c>,
<django.db.models.fields.CharField object at 0x8617a4c>,
<django.db.models.fields.DateField object at 0x8617a8c>,
<django.db.models.fields.TextField object at 0x8617acc>,
# this seems to be a duplicate of the fields added to User
<django.db.models.fields.BooleanField object at 0x862ab2c>,
<django.db.models.fields.CharField object at 0x862a4ac>,
<django.db.models.fields.PositiveIntegerField object at 0x862ab6c>,
<django.db.models.fields.CharField object at 0x862f6cc>,
<django.db.models.fields.SmallIntegerField object at 0x861782c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa2c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa4c>,
<django.db.models.fields.SmallIntegerField object at 0x862fa8c>,
<django.db.models.fields.DateTimeField object at 0x862faac>,
<django.db.models.fields.CharField object at 0x862faec>,
<django.db.models.fields.URLField object at 0x862fb2c>,
<django.db.models.fields.CharField object at 0x862fb6c>,
<django.db.models.fields.DateField object at 0x862fbac>,
<django.db.models.fields.TextField object at 0x862fbec>]
The additional fields to the model are added thusly:
User.add_to_class('email_isvalid', models.BooleanField(default=False))
User.add_to_class('email_key', models.CharField(max_length=16, null=True))
User.add_to_class('reputation', models.PositiveIntegerField(default=1))
User.add_to_class('gravatar', models.CharField(max_length=32))
User.add_to_class('email_feeds', generic.GenericRelation(EmailFeed))
User.add_to_class('favorite_questions', models.ManyToManyField(Question, through=FavoriteQuestion, related_name='favorited_by'))
User.add_to_class('badges', models.ManyToManyField(Badge, through=Award, related_name='awarded_to'))
User.add_to_class('gold', models.SmallIntegerField(default=0))
User.add_to_class('silver', models.SmallIntegerField(default=0))
User.add_to_class('bronze', models.SmallIntegerField(default=0))
User.add_to_class('questions_per_page', models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10))
User.add_to_class('last_seen', models.DateTimeField(default=datetime.datetime.now))
User.add_to_class('real_name', models.CharField(max_length=100, blank=True))
User.add_to_class('website', models.URLField(max_length=200, blank=True))
User.add_to_class('location', models.CharField(max_length=100, blank=True))
User.add_to_class('date_of_birth', models.DateField(null=True, blank=True))
User.add_to_class('about', models.TextField(blank=True))
I think it's possible that the .add_to_class method may be part of this problem.
|
[
"It would have been helpful if you showed the Django model that is related to this problem. From the field names in your SQL this model appears to inherit from contrib.auth.models.User, is that true? If so, did you happen to duplicate a field name defined in the User model?\nUpdate: To put it more bluntly, I was asking that you edit your question and include the specific model you declared in your models.py file. It's almost a certainty that you have declared two fields with the same name. The last field declared in auth.models.User is date_joined so both definitions of about should show up in your models declaration.\nActually, on closer inspection of your SQL again, you not only have two columns named about, you have about 14 duplicated field names in there. Something ain't right.\nTo paraphrase Jerry McGuire: Show me the model! :-)\nSecond Update (Working with a 1 beer handicap (and it's good stuff!))\nI have never used add_to_class in this way. Why did you go this route and not use one of the more standard Django model inheritance techniques? Or, since this is User you are dealing with, why not use UserProfile. It can be a little bit clunky but it works just fine.\nThird Update\nAh, Domini Nabisco, my son -- I didn't realize you had inherited this from someone else. A word of caution: because this changed a fundamental class in Django (in a decidedly non-standard way) you may need to look at every single reference to user in both the .py files and the templates. Depending on the size of the inherited project this can be a huge PITA, particularly when it's missing tests. Is there any chance you can hunt down, I mean locate the person responsible and get some more insight? It may be the shorter route to getting things working. Good luck!\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002213716_django_django_models_python.txt
|
Q:
Is everything greater than None?
Is there a Python built-in datatype, besides None, for which:
>>> not foo > None
True
where foo is a value of that type? How about Python 3?
A:
None is always less than any datatype in Python 2 (see object.c).
In Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a TypeError. From the 3.0 "what's new" updates:
Python 3.0 has simplified the rules for ordering comparisons:
The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like: 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.
This upset some people since it was often handy to do things like sort a list that had some None values in it, and have the None values appear clustered together at the beginning or end. There was a thread on the mailing list about this a while back, but the ultimate point is that Python 3 tries to avoid making arbitrary decisions about ordering (which is what happened a lot in Python 2).
A:
From the Python 2.7.5 source (object.c):
static int
default_3way_compare(PyObject *v, PyObject *w)
{
...
/* None is smaller than anything */
if (v == Py_None)
return -1;
if (w == Py_None)
return 1;
...
}
EDIT: Added version number.
|
Is everything greater than None?
|
Is there a Python built-in datatype, besides None, for which:
>>> not foo > None
True
where foo is a value of that type? How about Python 3?
|
[
"None is always less than any datatype in Python 2 (see object.c).\nIn Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a TypeError. From the 3.0 \"what's new\" updates:\n\nPython 3.0 has simplified the rules for ordering comparisons:\nThe ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like: 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.\n\nThis upset some people since it was often handy to do things like sort a list that had some None values in it, and have the None values appear clustered together at the beginning or end. There was a thread on the mailing list about this a while back, but the ultimate point is that Python 3 tries to avoid making arbitrary decisions about ordering (which is what happened a lot in Python 2).\n",
"From the Python 2.7.5 source (object.c):\nstatic int\ndefault_3way_compare(PyObject *v, PyObject *w)\n{\n ...\n /* None is smaller than anything */\n if (v == Py_None)\n return -1;\n if (w == Py_None)\n return 1;\n ...\n}\n\nEDIT: Added version number.\n"
] |
[
96,
30
] |
[] |
[] |
[
"python",
"python_datamodel"
] |
stackoverflow_0002214194_python_python_datamodel.txt
|
Q:
What's the pythonic way of declaring variables?
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed.
Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name?
How would you avoid such a situation?
A:
It's a silly artifact of Python's inspiration by "teaching languages", and it serves to make the language more accessible by removing the stumbling block of "declaration" entirely. For whatever reason (probably represented as "simplicity"), Python never gained an optional stricture like VB's "Option Explicit" to introduce mandatory declarations. Yes, it can be a source of bugs, but as the other answers here demonstrate, good coders can develop habits that allow them to compensate for pretty much any shortcoming in the language -- and as shortcomings go, this is a pretty minor one.
A:
If you want a class with "locked-down" instance attributes, it's not hard to make one, e.g.:
class LockedDown(object):
__locked = False
def __setattr__(self, name, value):
if self.__locked:
if name[:2] != '__' and name not in self.__dict__:
raise ValueError("Can't set attribute %r" % name)
object.__setattr__(self, name, value)
def _dolock(self):
self.__locked = True
class Example(LockedDown):
def __init__(self):
self.mistakes = 0
self._dolock()
def onemore(self):
self.mistakes += 1
print self.mistakes
def reset(self):
self.mitsakes = 0
x = Example()
for i in range(3): x.onemore()
x.reset()
As you'll see, the calls to x.onemore work just fine, but reset raises an exception because of the mis-spelling of the attribute as mitsakes. The rules of engagement here are that __init__ must set all attributes to initial values, then call self._dolock() to forbid any further addition of attributes. I'm exempting "super-private" attributes (ones starting with __), which stylistically should be used very rarely, for totally specific roles, and with extremely limited scope (making it trivial to spot typos in the super-careful inspection that's needed anyway to confirm the need for super-privacy), but that's a stylistic choice, easy to reverse; similarly for the choice to make the locked-down state "irreversible" (by "normal" means -- i.e. requiring very explicit workaround to bypass).
This doesn't apply to other kinds of names, such as function-local ones; again, no big deal because each function should be very small, and is a totally self-contained scope, trivially easy to inspect (if you write 100-lines functions, you have other, serious problems;-).
Is this worth the bother? No, because semi-decent unit tests should obviously catch all such typos with the greatest of ease, as a natural side effect of thoroughly exercising the class's functionality. In other words, it's not as if you need to have more unit tests just to catch the typos: the unit tests you need anyway to catch trivial semantic errors (off-by-one, +1 where -1 is meant, etc., etc.) will already catch all typos, too.
Robert Martin and Bruce Eckel both articulated this point 7 years ago in separate and independent articles -- Eckel's blog is temporarily down right now, but Martin's right here, and when Eckel's site revives the article should be here. The thesis is controversial (Jeff Attwood and his commenters debate it here, for example), but it's interesting to note that Martin and Eckel are both well-known experts of static languages such as C++ and Java (albeit with love affairs, respectively, with Ruby and Python), and they're far from the only ones to have discovered the importance of unit-tests... and how a good unit-tests suite, as a side effect, makes a static language's rigidity redundant.
By the way, one way to check your test suites is "error injection": systematically go over your codebase introducing one mis-spelling -- run the tests to make sure they do fail, if they don't add one that does fail, correct the spelling mistake, repeat. Can be fairly well automated (not the "add a test" part, but the finding of potential errors that aren't covered by the suite), as can some other forms of error injections (change every integer constant, one by one, to one more, and to one less; change each < to <= etc; swap each if and while condition to its reverse; ...), while other forms of error-injection yet require a lot more human savvy. Unfortunately I don't know of publicly available suites of error injection frameworks (for any language) -- might make a cool open source project;-).
A:
In python it helps to think of declaring variables as binding values to names.
Try not to misspell them, or you will have new ones (assuming you are talking about assignment statements - referencing them will cause an exception).
If you are talking about instance variables, you won't be able to use them afterwards.
For example, if you had a class myclass and in its __init__ method wrote self.myvar = 0, then trying to reference self.myvare will cause an error, rather than give you a default value.
A:
Python never forces you to create a variable only when you use it. You can always bind None to a name and then use the name elsewhere later.
A:
To avoid a situation with misspelling variable names, I use a text-editor with an autocompletion function and binded
python -c "import py_compile; py_compile.compile('{filename}')"
to a function to be called when I save a file.
A:
Test.
Example, with file variable.py:
#! /usr/bin/python
somevar = 5
Then, make file variable.txt (to hold the tests):
>>> import variables
>>> variables.somevar == 4
True
Then do:
python -m doctest variable.txt
And get:
**********************************************************************
File "variables.txt", line 2, in variables.test
Failed example:
variables.somevar == 4
Expected:
True
Got:
False
**********************************************************************
1 items had failures:
1 of 2 in variables.test
***Test Failed*** 1 failures.
This shows a variable declared incorrectly.
Try:
>>> import variables
>>> variables.someothervar == 5
True
Note that the variable is not named the same.
**********************************************************************
File "variables.test", line 2, in variables.test
Failed example:
variables.someothervar == 5
Exception raised:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/doctest.py", line 1241, in __run
compileflags, 1) in test.globs
File "<doctest variables.test[1]>", line 1, in <module>
variables.someothervar == 5
AttributeError: 'module' object has no attribute 'someothervar'
**********************************************************************
1 items had failures:
1 of 2 in variables.test
***Test Failed*** 1 failures.
This shows a misspelled variable.
>>> import variables
>>> variables.somevar == 5
True
And this returns with no error.
I've done enough VBScript development to know that typos are a problem in variable name, and enough VBScript development to know that Option Explicit is a crutch at best. (<- 12 years of ASP VBScript experience taught me that the hard way.)
A:
If you do any serious development you'll use a (integrated) development environment. Pylint will be part of it and tell you all your misspellings. No need to make such a feature part of the langauge.
|
What's the pythonic way of declaring variables?
|
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed.
Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name?
How would you avoid such a situation?
|
[
"It's a silly artifact of Python's inspiration by \"teaching languages\", and it serves to make the language more accessible by removing the stumbling block of \"declaration\" entirely. For whatever reason (probably represented as \"simplicity\"), Python never gained an optional stricture like VB's \"Option Explicit\" to introduce mandatory declarations. Yes, it can be a source of bugs, but as the other answers here demonstrate, good coders can develop habits that allow them to compensate for pretty much any shortcoming in the language -- and as shortcomings go, this is a pretty minor one.\n",
"If you want a class with \"locked-down\" instance attributes, it's not hard to make one, e.g.:\nclass LockedDown(object):\n __locked = False\n def __setattr__(self, name, value):\n if self.__locked:\n if name[:2] != '__' and name not in self.__dict__:\n raise ValueError(\"Can't set attribute %r\" % name)\n object.__setattr__(self, name, value)\n def _dolock(self):\n self.__locked = True\n\nclass Example(LockedDown):\n def __init__(self):\n self.mistakes = 0\n self._dolock()\n def onemore(self):\n self.mistakes += 1\n print self.mistakes\n def reset(self):\n self.mitsakes = 0\n\nx = Example()\nfor i in range(3): x.onemore()\nx.reset()\n\nAs you'll see, the calls to x.onemore work just fine, but reset raises an exception because of the mis-spelling of the attribute as mitsakes. The rules of engagement here are that __init__ must set all attributes to initial values, then call self._dolock() to forbid any further addition of attributes. I'm exempting \"super-private\" attributes (ones starting with __), which stylistically should be used very rarely, for totally specific roles, and with extremely limited scope (making it trivial to spot typos in the super-careful inspection that's needed anyway to confirm the need for super-privacy), but that's a stylistic choice, easy to reverse; similarly for the choice to make the locked-down state \"irreversible\" (by \"normal\" means -- i.e. requiring very explicit workaround to bypass).\nThis doesn't apply to other kinds of names, such as function-local ones; again, no big deal because each function should be very small, and is a totally self-contained scope, trivially easy to inspect (if you write 100-lines functions, you have other, serious problems;-).\nIs this worth the bother? No, because semi-decent unit tests should obviously catch all such typos with the greatest of ease, as a natural side effect of thoroughly exercising the class's functionality. In other words, it's not as if you need to have more unit tests just to catch the typos: the unit tests you need anyway to catch trivial semantic errors (off-by-one, +1 where -1 is meant, etc., etc.) will already catch all typos, too.\nRobert Martin and Bruce Eckel both articulated this point 7 years ago in separate and independent articles -- Eckel's blog is temporarily down right now, but Martin's right here, and when Eckel's site revives the article should be here. The thesis is controversial (Jeff Attwood and his commenters debate it here, for example), but it's interesting to note that Martin and Eckel are both well-known experts of static languages such as C++ and Java (albeit with love affairs, respectively, with Ruby and Python), and they're far from the only ones to have discovered the importance of unit-tests... and how a good unit-tests suite, as a side effect, makes a static language's rigidity redundant.\nBy the way, one way to check your test suites is \"error injection\": systematically go over your codebase introducing one mis-spelling -- run the tests to make sure they do fail, if they don't add one that does fail, correct the spelling mistake, repeat. Can be fairly well automated (not the \"add a test\" part, but the finding of potential errors that aren't covered by the suite), as can some other forms of error injections (change every integer constant, one by one, to one more, and to one less; change each < to <= etc; swap each if and while condition to its reverse; ...), while other forms of error-injection yet require a lot more human savvy. Unfortunately I don't know of publicly available suites of error injection frameworks (for any language) -- might make a cool open source project;-).\n",
"In python it helps to think of declaring variables as binding values to names.\nTry not to misspell them, or you will have new ones (assuming you are talking about assignment statements - referencing them will cause an exception).\nIf you are talking about instance variables, you won't be able to use them afterwards.\nFor example, if you had a class myclass and in its __init__ method wrote self.myvar = 0, then trying to reference self.myvare will cause an error, rather than give you a default value.\n",
"Python never forces you to create a variable only when you use it. You can always bind None to a name and then use the name elsewhere later.\n",
"To avoid a situation with misspelling variable names, I use a text-editor with an autocompletion function and binded \n python -c \"import py_compile; py_compile.compile('{filename}')\"\n\nto a function to be called when I save a file.\n",
"Test.\nExample, with file variable.py:\n#! /usr/bin/python\n\nsomevar = 5\n\nThen, make file variable.txt (to hold the tests):\n>>> import variables\n>>> variables.somevar == 4\nTrue\n\nThen do:\npython -m doctest variable.txt\n\nAnd get:\n**********************************************************************\nFile \"variables.txt\", line 2, in variables.test\nFailed example:\n variables.somevar == 4\nExpected:\n True\nGot:\n False\n**********************************************************************\n1 items had failures:\n 1 of 2 in variables.test\n***Test Failed*** 1 failures.\n\nThis shows a variable declared incorrectly.\nTry:\n>>> import variables\n>>> variables.someothervar == 5\nTrue\n\nNote that the variable is not named the same.\n**********************************************************************\nFile \"variables.test\", line 2, in variables.test\nFailed example:\n variables.someothervar == 5\nException raised:\n Traceback (most recent call last):\n File \"/usr/local/lib/python2.6/doctest.py\", line 1241, in __run\n compileflags, 1) in test.globs\n File \"<doctest variables.test[1]>\", line 1, in <module>\n variables.someothervar == 5\n AttributeError: 'module' object has no attribute 'someothervar'\n**********************************************************************\n1 items had failures:\n 1 of 2 in variables.test\n***Test Failed*** 1 failures.\n\nThis shows a misspelled variable.\n>>> import variables\n>>> variables.somevar == 5\nTrue\n\nAnd this returns with no error.\nI've done enough VBScript development to know that typos are a problem in variable name, and enough VBScript development to know that Option Explicit is a crutch at best. (<- 12 years of ASP VBScript experience taught me that the hard way.)\n",
"If you do any serious development you'll use a (integrated) development environment. Pylint will be part of it and tell you all your misspellings. No need to make such a feature part of the langauge.\n"
] |
[
15,
12,
9,
5,
4,
3,
2
] |
[
"Variable declaration does not prevent bugs. Any more than lack of variable declaration causes bugs.\nVariable declarations prevent one specific type of bug, but it creates other types bugs.\nPrevent. Writing code where there's an attempt to set (or change) a variable with the wrong type of data.\nCauses. Stupid workarounds to coerce a number of unrelated types together so that assignments will \"just work\". Example: The C language union. Also, variable declarations force us to use casts. Which also forces us to suppress warnings on casts at compile time because we \"know\" it will \"just work\". And it doesn't.\nLack of variable declarations does not cause bugs. The most common \"threat scenario\" is some kind of \"mis-assignment\" to a variable.\n\nWas the variable being \"reused\"? This is dumb but legal and works.\n\nWas some part of the program incorrectly assigning the wrong type?\nThat leads to a subtle question of \"what does wrong mean?\" In a duck-typed language, wrong means \"Doesn't offer the right methods or attributes.\" Which is still nebulous. Specifically, it means \"the type will be asked to provide a method or attribute it doesn't have.\" Which will raise an exception and the program will stop.\n\n\nRaising an uncaught exception in production use is annoying and shows a lack of quality. It's stupid, but it's also a detected, known failure mode with a traceback to the exact root cause.\n\"can't it cause bugs because you misspelled a variable's name\"\nYes. It can.\nBut consider this Java code.\npublic static void maine( String[] argv ) {\n int main;\n int mian;\n}\n\nA misspelling here is equally fatal. Statically typed Java has done nothing to prevent a misspelled variable name from causing a bug.\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0002213531_python.txt
|
Q:
(django initial setup) Django installation is redirecting all traffic to django page, fix?
I'm a complete newbie to Django. I've been trying to get it working on my Ubuntu server.
everytime someone my server, it redirects to the "Congratulations on your first Django-powered page." It completely ignores the index.html file in the www directory. Why is that? Is there a away to make it so that it only goes to the django page when I goto a subdomain /testproject instead?
here is what I got
python version: 2.5.2
Django version 1.2 b1
I'm using mod_python. here is my apache http.conf file
MaxRequestsPerChild 1
<location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE testproj1.settings
PythonPath "['/root/django/django_projects'] + sys.path"
PythonDebug On
</location>
<location "/admin_media">
SetHandler None
</location>
<location "/media">
SetHandler None
</location>
<LocationMatch "\.(jpg|gif|png)$">
SetHandler None
</LocationMatch>
SetHandler None
Thanks!
A:
"It completely ignores the index.html
file in the www directory. Why is
that?"
Because you installed django and django takes over from that point. You should probably change the <Location> path to "testproject" instead of "/" as obviously the latter means root/homepage. Though I'm not sure this will quite workout properly because I'm not sure it will take over the entire testproject directory like it would to the root, I could be wrong.
If you have access to, you can instead setup a subdomain as it's probably not feasible to set it up in /testproject/.
|
(django initial setup) Django installation is redirecting all traffic to django page, fix?
|
I'm a complete newbie to Django. I've been trying to get it working on my Ubuntu server.
everytime someone my server, it redirects to the "Congratulations on your first Django-powered page." It completely ignores the index.html file in the www directory. Why is that? Is there a away to make it so that it only goes to the django page when I goto a subdomain /testproject instead?
here is what I got
python version: 2.5.2
Django version 1.2 b1
I'm using mod_python. here is my apache http.conf file
MaxRequestsPerChild 1
<location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE testproj1.settings
PythonPath "['/root/django/django_projects'] + sys.path"
PythonDebug On
</location>
<location "/admin_media">
SetHandler None
</location>
<location "/media">
SetHandler None
</location>
<LocationMatch "\.(jpg|gif|png)$">
SetHandler None
</LocationMatch>
SetHandler None
Thanks!
|
[
"\n\"It completely ignores the index.html\n file in the www directory. Why is\n that?\"\n\nBecause you installed django and django takes over from that point. You should probably change the <Location> path to \"testproject\" instead of \"/\" as obviously the latter means root/homepage. Though I'm not sure this will quite workout properly because I'm not sure it will take over the entire testproject directory like it would to the root, I could be wrong.\nIf you have access to, you can instead setup a subdomain as it's probably not feasible to set it up in /testproject/.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"apache_config",
"django",
"mod_python",
"python"
] |
stackoverflow_0002214645_apache_apache_config_django_mod_python_python.txt
|
Q:
Django: Can the value of ForeignKey be None?
I have a model called SimplePage in which I have this line:
category = models.ForeignKey('Category', related_name='items',
blank=True, null=True)
I assumed this will allow me to have SimplePage instances that do not have a Category.
But for some reason, when I try to create a SimplePage in the Admin with no Category, I get:
IntegrityError at /admin/sitehelpers/simplepage/add/
sitehelpers_simplepage.category_id may not be NULL
What is this?
A:
Could it possibly be that you added the null=True attribute after doing the syncdb for that model? Django won't change database tables, only create them. Check in your database if NULL is allowed for that column and change it manually.
Edit: starting with Django 1.7, this answer and the comments are not really valid anymore, since Django gained a fully featured migration framework.
|
Django: Can the value of ForeignKey be None?
|
I have a model called SimplePage in which I have this line:
category = models.ForeignKey('Category', related_name='items',
blank=True, null=True)
I assumed this will allow me to have SimplePage instances that do not have a Category.
But for some reason, when I try to create a SimplePage in the Admin with no Category, I get:
IntegrityError at /admin/sitehelpers/simplepage/add/
sitehelpers_simplepage.category_id may not be NULL
What is this?
|
[
"Could it possibly be that you added the null=True attribute after doing the syncdb for that model? Django won't change database tables, only create them. Check in your database if NULL is allowed for that column and change it manually.\nEdit: starting with Django 1.7, this answer and the comments are not really valid anymore, since Django gained a fully featured migration framework.\n"
] |
[
9
] |
[] |
[] |
[
"database",
"django",
"foreign_keys",
"python"
] |
stackoverflow_0002214909_database_django_foreign_keys_python.txt
|
Q:
Secure Python intepreter?
Is there a secure Python intepreter?
Imagine a Python VM you can run on your machine, that restricts the operations.
No files can be opened, no system calls, etc.
It just transforms stdin to stdout, maybe with text processing + math etc.
Does such a secure Python VM exist?
A:
I know of no such "secure interpreter" that is openly distributed (obviously Google has one that it uses in App Engine, though with somewhat different restrictions from those you desire, e.g., certain files can be opened, in a read-only way). There are some claims for it, though, e.g. here, though I can't verify them. Pypy's Python in a Sandbox is probably the top one worth trying, given the high quality and reputation of pypy's development team (they're VERY unlikely to make unsubstantiated claims).
A:
You could run Jython on the JVM with a SecurityManager that allows you to specify permitted / disallowed operations.
A:
You don't need a modified Python to restrict execution in a certain sense. Just look at codepad.org, a pastebin where you can paste code (in Python and other languages) and have it run and the output shown. The code runs in a very restricted environment, but that's just the OS configuration. (Example paste)
A:
You could run IronPython inside a .NET appdomain that has restricted privileges.
This would definitely work in Windows, and possibly/probably in Mono (I couldn't really say).
You would need to write a little program that embeds the IronPython interpreter and passes the script to it.
The first example in the chapter on embedding in the book Iron Python in Action shows to write such a launcher.
I don't recall if it covers appdomains, but that info should be on the Web somewhere.
A:
I am an undergrad and in my first year, we were taught python. We had these things called "CodeLabs" that had to be submitted periodically. It works by asking a question and asking the student to input their answer into a text box and running that code on some test cases and checking their return values
One day, the codelabs website (turingscraft.com) became inaccessible because someone decided to run an endless while loop and calling os.fork() inside it.
This was obviously a problem for the administrators of turingscraft.com. However, they later found a way to restrict access to such commands for students.
If I were you, I would look up information about their site. Maybe they posted some information about this and how to fix it
A:
You could always go to the source code and make your own flavor of Python. If enough people need it, it will be no time before it's up and running.
|
Secure Python intepreter?
|
Is there a secure Python intepreter?
Imagine a Python VM you can run on your machine, that restricts the operations.
No files can be opened, no system calls, etc.
It just transforms stdin to stdout, maybe with text processing + math etc.
Does such a secure Python VM exist?
|
[
"I know of no such \"secure interpreter\" that is openly distributed (obviously Google has one that it uses in App Engine, though with somewhat different restrictions from those you desire, e.g., certain files can be opened, in a read-only way). There are some claims for it, though, e.g. here, though I can't verify them. Pypy's Python in a Sandbox is probably the top one worth trying, given the high quality and reputation of pypy's development team (they're VERY unlikely to make unsubstantiated claims).\n",
"You could run Jython on the JVM with a SecurityManager that allows you to specify permitted / disallowed operations.\n",
"You don't need a modified Python to restrict execution in a certain sense. Just look at codepad.org, a pastebin where you can paste code (in Python and other languages) and have it run and the output shown. The code runs in a very restricted environment, but that's just the OS configuration. (Example paste)\n",
"You could run IronPython inside a .NET appdomain that has restricted privileges.\nThis would definitely work in Windows, and possibly/probably in Mono (I couldn't really say).\nYou would need to write a little program that embeds the IronPython interpreter and passes the script to it.\nThe first example in the chapter on embedding in the book Iron Python in Action shows to write such a launcher.\nI don't recall if it covers appdomains, but that info should be on the Web somewhere.\n",
"I am an undergrad and in my first year, we were taught python. We had these things called \"CodeLabs\" that had to be submitted periodically. It works by asking a question and asking the student to input their answer into a text box and running that code on some test cases and checking their return values\nOne day, the codelabs website (turingscraft.com) became inaccessible because someone decided to run an endless while loop and calling os.fork() inside it. \nThis was obviously a problem for the administrators of turingscraft.com. However, they later found a way to restrict access to such commands for students. \nIf I were you, I would look up information about their site. Maybe they posted some information about this and how to fix it\n",
"You could always go to the source code and make your own flavor of Python. If enough people need it, it will be no time before it's up and running.\n"
] |
[
7,
2,
2,
1,
1,
0
] |
[
"I've been toying with this lately. My requirements include Python 3.x which immediately takes solutions like Jython and IronPython off the table. I'd be hesitant to take that route anyway, as I've never trusted user-mode language VMs.\nThat being the case, for my purposes the best solution so far is to take it out of the hands of the interpreter completely and run in a strongly locked-down container (OpenVZ or similar). However, this is taking a hammer to the problem (albeit not the sledgehammer of full virtualization), and may not be viable if you have to run a truly huge number of isolated interpreters.\nOne upside, though, is that because it doesn't rely on the security of any particular interpreter, you can use any arbitrary language you want in the environment -- you don't have to tie yourself to Python or the set of languages/implementations available for JVM or .NET/Mono.\n",
"Isn't security more a job for the operating system ?\nI mean, create a user with restricted access to files and such. Then let the vm be ran only with these rights.\nOr maybe I'm speaking nonsense. I'm no sysadmin or security expert, but I tend to do things with the tools that are made for it.\n"
] |
[
-1,
-1
] |
[
"interpreter",
"python",
"security",
"virtual_machine"
] |
stackoverflow_0001695014_interpreter_python_security_virtual_machine.txt
|
Q:
How to get rid of pygame surfaces?
In the following code, there is not just one circle on the screen at any given point in time.
I want to fix this to make it so that it looks like there is only one circle, instead of leaving a smudge trail where ever the mouse cursor has been.
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,400),0,32)
radius = 25
circle = pygame.Surface([radius*2]*2,SRCALPHA,32)
circle = circle.convert_alpha()
pygame.draw.circle(circle,(25,46,100),[radius]*2,radius)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(circle,(pygame.mouse.get_pos()[0],100))
pygame.display.update()
pygame.time.delay(10)
A:
You need to specifically erase the circle before you blit it again. Depending on how complicated your scene is, you may have to try different methods. Generally what I do is have a "background" surface that a blit to the screen every frame and then blit the sprites/other surfaces in their new positions (blits in Pygame are very fast, so even in fairly large screens I haven't had speed issues doing this). For your code above, it's simple enough just to use surface.fill(COLOR) where COLOR is your background color; eg, (255,255,255) for white:
# ...
screen = pygame.display.set_mode((640,400),0,32)
backgroundColor = (255,255,255)
# ...
while True:
# ...
screen.fill(backgroundColor)
screen.blit(circle,(pygame.mouse.get_pos()[0],100))
pygame.display.update()
pygame.time.delay(10)
Edit in answer to your comment: It is possible to do this in a more object-oriented way.
You will need to have a background Surface associated with your screen (I usually have a Display or Map class (depending on the type of game) that does this). Then, make your object a subclass of pygame.sprite. This requires that you have self.image and self.rect attributes (the image being your surface and the rect being a Pygame.rect with the location). Add all of your sprites to a pygame.group object. Now, every frame, you call the draw method on the group and, after you update the display (ie, with pygame.display.update()), you call the clear method on the group. This method requires that you provide both the destination surface (ie, screen above) and a background image.
For example, your main loop may look more like this:
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
circle.rect.center = (pygame.mouse.get_pos()[0],100)
circleGroup.draw(screen)
pygame.display.update()
circleGroup.clear(screen, backgroundSurface)
pygame.time.delay(10)
See the documentation on the Sprite and Group classes for more information.
|
How to get rid of pygame surfaces?
|
In the following code, there is not just one circle on the screen at any given point in time.
I want to fix this to make it so that it looks like there is only one circle, instead of leaving a smudge trail where ever the mouse cursor has been.
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,400),0,32)
radius = 25
circle = pygame.Surface([radius*2]*2,SRCALPHA,32)
circle = circle.convert_alpha()
pygame.draw.circle(circle,(25,46,100),[radius]*2,radius)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(circle,(pygame.mouse.get_pos()[0],100))
pygame.display.update()
pygame.time.delay(10)
|
[
"You need to specifically erase the circle before you blit it again. Depending on how complicated your scene is, you may have to try different methods. Generally what I do is have a \"background\" surface that a blit to the screen every frame and then blit the sprites/other surfaces in their new positions (blits in Pygame are very fast, so even in fairly large screens I haven't had speed issues doing this). For your code above, it's simple enough just to use surface.fill(COLOR) where COLOR is your background color; eg, (255,255,255) for white:\n# ...\nscreen = pygame.display.set_mode((640,400),0,32)\nbackgroundColor = (255,255,255)\n# ...\nwhile True:\n # ...\n screen.fill(backgroundColor)\n screen.blit(circle,(pygame.mouse.get_pos()[0],100))\n pygame.display.update()\n pygame.time.delay(10)\n\nEdit in answer to your comment: It is possible to do this in a more object-oriented way.\nYou will need to have a background Surface associated with your screen (I usually have a Display or Map class (depending on the type of game) that does this). Then, make your object a subclass of pygame.sprite. This requires that you have self.image and self.rect attributes (the image being your surface and the rect being a Pygame.rect with the location). Add all of your sprites to a pygame.group object. Now, every frame, you call the draw method on the group and, after you update the display (ie, with pygame.display.update()), you call the clear method on the group. This method requires that you provide both the destination surface (ie, screen above) and a background image.\nFor example, your main loop may look more like this:\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n circle.rect.center = (pygame.mouse.get_pos()[0],100)\n circleGroup.draw(screen)\n\n pygame.display.update()\n circleGroup.clear(screen, backgroundSurface)\n pygame.time.delay(10)\n\nSee the documentation on the Sprite and Group classes for more information.\n"
] |
[
6
] |
[] |
[] |
[
"geometry_surface",
"pygame",
"python"
] |
stackoverflow_0002215227_geometry_surface_pygame_python.txt
|
Q:
Parsing XML with BeautifulSoup and handling missing element
I am using BeautifulSoup to parse XML:
xml = """<person>
<first_name>Matt</first_name>
</person>"""
soup = BeautifulStoneSoup(xml)
first_name = soup.find('first_name').string
last_name = soup.find('last_name').string
But I have a problem when there is no last_name, because it chokes. Sometimes the feed has it, and sometimes it doesn't. How do I prevent it from choking?
I don't want to use try/except statements. I also do not want to use if/else statements. (Since it'll double the lines of the already-very-long code if I have those statements).
Is there any way to just return "None" if there is no "last_name"?
A:
last_name = soup.find('last_name') and soup.find('last_name').string
Very silly, but it does meet your equally silly stated restriction (no if). A bit less silly:
last_name_node = soup.find('last_name')
last_name = last_name_node and last_name_node.string
and:
last_name = getattr(soup.find('last_name'), 'string', None)
These two don't have the same overhead as the first. I think a simple if is more readable than any of these, though.
|
Parsing XML with BeautifulSoup and handling missing element
|
I am using BeautifulSoup to parse XML:
xml = """<person>
<first_name>Matt</first_name>
</person>"""
soup = BeautifulStoneSoup(xml)
first_name = soup.find('first_name').string
last_name = soup.find('last_name').string
But I have a problem when there is no last_name, because it chokes. Sometimes the feed has it, and sometimes it doesn't. How do I prevent it from choking?
I don't want to use try/except statements. I also do not want to use if/else statements. (Since it'll double the lines of the already-very-long code if I have those statements).
Is there any way to just return "None" if there is no "last_name"?
|
[
"last_name = soup.find('last_name') and soup.find('last_name').string\n\nVery silly, but it does meet your equally silly stated restriction (no if). A bit less silly:\nlast_name_node = soup.find('last_name')\nlast_name = last_name_node and last_name_node.string\n\nand:\nlast_name = getattr(soup.find('last_name'), 'string', None)\n\nThese two don't have the same overhead as the first. I think a simple if is more readable than any of these, though.\n"
] |
[
4
] |
[] |
[] |
[
"beautifulsoup",
"exception_handling",
"python",
"xml"
] |
stackoverflow_0002215429_beautifulsoup_exception_handling_python_xml.txt
|
Q:
Django - Determine field type of a variable passed to a template tag
I would like to write a Django template tag to which I can pass a variable.
I would like the template tag to behave differently depending on what type of model field the variable was derived from (CharField, BooleanField, IntegerField, etc.) as well as other information used in the field's definition (max_length, etc.)
I can pass the variable to the template tag easily, following this documentation:
Passing template variables to the tag
Is there a way to determine the class name and model parameters of the variable's originating model field?
In other words: can I make a tag like this:
{% template_tag model.field %}
and in the tag rendering function access information coming from the model?
field = models.CharField(max_length=40)
A:
You can use python's type function to determine the class type.
if type(field) == models.CharField:
#CharField specific code
elif type(field) == models.IntegerField:
#IntegerField specific code
|
Django - Determine field type of a variable passed to a template tag
|
I would like to write a Django template tag to which I can pass a variable.
I would like the template tag to behave differently depending on what type of model field the variable was derived from (CharField, BooleanField, IntegerField, etc.) as well as other information used in the field's definition (max_length, etc.)
I can pass the variable to the template tag easily, following this documentation:
Passing template variables to the tag
Is there a way to determine the class name and model parameters of the variable's originating model field?
In other words: can I make a tag like this:
{% template_tag model.field %}
and in the tag rendering function access information coming from the model?
field = models.CharField(max_length=40)
|
[
"You can use python's type function to determine the class type.\nif type(field) == models.CharField:\n #CharField specific code\nelif type(field) == models.IntegerField:\n #IntegerField specific code\n\n"
] |
[
5
] |
[] |
[] |
[
"django",
"field",
"python",
"templatetags",
"variables"
] |
stackoverflow_0002215484_django_field_python_templatetags_variables.txt
|
Q:
efficiently knowing if intersection of two list is empty or not, in python
Suppose I have two lists, L and M. Now I want to know if they share an element.
Which would be the fastest way of asking (in python) if they share an element?
I don't care which elements they share, or how many, just if they share or not.
For example, in this case
L = [1,2,3,4,5,6]
M = [8,9,10]
I should get False, and here:
L = [1,2,3,4,5,6]
M = [5,6,7]
I should get True.
I hope the question's clear.
Thanks!
Manuel
A:
Or more concisely
if set(L) & set(M):
# there is an intersection
else:
# no intersection
If you really need True or False
bool(set(L) & set(M))
After running some timings, this seems to be a good option to try too
m_set=set(M)
any(x in m_set for x in L)
If the items in M or L are not hashable you have to use a less efficient approach like this
any(x in M for x in L)
Here are some timings for 100 item lists. Using sets is considerably faster when there is no intersection, and a bit slower when there is a considerable intersection.
M=range(100)
L=range(100,200)
timeit set(L) & set(M)
10000 loops, best of 3: 32.3 µs per loop
timeit any(x in M for x in L)
1000 loops, best of 3: 374 µs per loop
timeit m_set=frozenset(M);any(x in m_set for x in L)
10000 loops, best of 3: 31 µs per loop
L=range(50,150)
timeit set(L) & set(M)
10000 loops, best of 3: 18 µs per loop
timeit any(x in M for x in L)
100000 loops, best of 3: 4.88 µs per loop
timeit m_set=frozenset(M);any(x in m_set for x in L)
100000 loops, best of 3: 9.39 µs per loop
# Now for some random lists
import random
L=[random.randrange(200000) for x in xrange(1000)]
M=[random.randrange(200000) for x in xrange(1000)]
timeit set(L) & set(M)
1000 loops, best of 3: 420 µs per loop
timeit any(x in M for x in L)
10 loops, best of 3: 21.2 ms per loop
timeit m_set=set(M);any(x in m_set for x in L)
1000 loops, best of 3: 168 µs per loop
timeit m_set=frozenset(M);any(x in m_set for x in L)
1000 loops, best of 3: 371 µs per loop
A:
To avoid the work of constructing the intersection, and produce an answer as soon as we know that they intersect:
m_set = frozenset(M)
return any(x in m_set for x in L)
Update: gnibbler tried this out and found it to run faster with set() in place of frozenset(). Whaddayaknow.
A:
First of all, if you do not need them ordered, then switch to the set type.
If you still need the list type, then do it this way: 0 == False
len(set.intersection(set(L), set(M)))
|
efficiently knowing if intersection of two list is empty or not, in python
|
Suppose I have two lists, L and M. Now I want to know if they share an element.
Which would be the fastest way of asking (in python) if they share an element?
I don't care which elements they share, or how many, just if they share or not.
For example, in this case
L = [1,2,3,4,5,6]
M = [8,9,10]
I should get False, and here:
L = [1,2,3,4,5,6]
M = [5,6,7]
I should get True.
I hope the question's clear.
Thanks!
Manuel
|
[
"Or more concisely\nif set(L) & set(M):\n # there is an intersection\nelse:\n # no intersection\n\nIf you really need True or False\nbool(set(L) & set(M))\n\nAfter running some timings, this seems to be a good option to try too\nm_set=set(M)\nany(x in m_set for x in L)\n\nIf the items in M or L are not hashable you have to use a less efficient approach like this\nany(x in M for x in L)\n\nHere are some timings for 100 item lists. Using sets is considerably faster when there is no intersection, and a bit slower when there is a considerable intersection.\nM=range(100)\nL=range(100,200)\n\ntimeit set(L) & set(M)\n10000 loops, best of 3: 32.3 µs per loop\n\ntimeit any(x in M for x in L)\n1000 loops, best of 3: 374 µs per loop\n\ntimeit m_set=frozenset(M);any(x in m_set for x in L)\n10000 loops, best of 3: 31 µs per loop\n\nL=range(50,150)\n\ntimeit set(L) & set(M)\n10000 loops, best of 3: 18 µs per loop\n\ntimeit any(x in M for x in L)\n100000 loops, best of 3: 4.88 µs per loop\n\ntimeit m_set=frozenset(M);any(x in m_set for x in L)\n100000 loops, best of 3: 9.39 µs per loop\n\n\n# Now for some random lists\nimport random\nL=[random.randrange(200000) for x in xrange(1000)]\nM=[random.randrange(200000) for x in xrange(1000)]\n\ntimeit set(L) & set(M)\n1000 loops, best of 3: 420 µs per loop\n\ntimeit any(x in M for x in L)\n10 loops, best of 3: 21.2 ms per loop\n\ntimeit m_set=set(M);any(x in m_set for x in L)\n1000 loops, best of 3: 168 µs per loop\n\ntimeit m_set=frozenset(M);any(x in m_set for x in L)\n1000 loops, best of 3: 371 µs per loop\n\n",
"To avoid the work of constructing the intersection, and produce an answer as soon as we know that they intersect:\nm_set = frozenset(M)\nreturn any(x in m_set for x in L)\n\nUpdate: gnibbler tried this out and found it to run faster with set() in place of frozenset(). Whaddayaknow.\n",
"First of all, if you do not need them ordered, then switch to the set type.\nIf you still need the list type, then do it this way: 0 == False\nlen(set.intersection(set(L), set(M)))\n\n"
] |
[
57,
5,
3
] |
[
"That's the most generic and efficient in a balanced way I could come up with (comments should make the code easy to understand):\nimport itertools, operator\n\ndef _compare_product(list1, list2):\n \"Return if any item in list1 equals any item in list2 exhaustively\"\n return any(\n itertools.starmap(\n operator.eq,\n itertools.product(list1, list2)))\n\ndef do_they_intersect(list1, list2):\n \"Return if any item is common between list1 and list2\"\n\n # do not try to optimize for small list sizes\n if len(list1) * len(list2) <= 100: # pick a small number\n return _compare_product(list1, list2)\n\n # first try to make a set from one of the lists\n try: a_set= set(list1)\n except TypeError:\n try: a_set= set(list2)\n except TypeError:\n a_set= None\n else:\n a_list= list1\n else:\n a_list= list2\n\n # here either a_set is None, or we have a_set and a_list\n\n if a_set:\n return any(itertools.imap(a_set.__contains__, a_list))\n\n # try to sort the lists\n try:\n a_list1= sorted(list1)\n a_list2= sorted(list2)\n except TypeError: # sorry, not sortable\n return _compare_product(list1, list2)\n\n # they could be sorted, so let's take the N+M road,\n # not the N*M\n\n iter1= iter(a_list1)\n iter2= iter(a_list2)\n try:\n item1= next(iter1)\n item2= next(iter2)\n except StopIteration: # one of the lists is empty\n return False # ie no common items\n\n while 1:\n if item1 == item2:\n return True\n while item1 < item2:\n try: item1= next(iter1)\n except StopIteration: return False\n while item2 < item1:\n try: item2= next(iter2)\n except StopIteration: return False\n\nHTH.\n"
] |
[
-1
] |
[
"intersection",
"list",
"performance",
"python"
] |
stackoverflow_0002197482_intersection_list_performance_python.txt
|
Q:
Difference Between Modulus Implementation in Python Vs Java
I've noticed differing implementations of the modulus operator in Python and Java.
For example, in Python:
>>> print -300 % 800
>>> 500
Whereas in Java:
System.out.println(-300 % 800);
-300
This caught me off guard, since I thought something as basic as modulus was universally interpreted the same way. I'm a fan of Python's interpretation (which I presume is borrowed from C), although I see the logic behind Java's implementation.
Which do you typically prefer? Is there any specific reason for the differing interpretations? I have no intention of starting a language war, simply curious.
A:
I prefer C's interpretation (also used in Python), where % is indeed a modulus operator. Good discussion in the wikipedia page and the links from it (including one bit about why taking instead the sign of the dividend can lead to one silly bug unless one's careful;-).
A:
Now try this:
>>> print 300 % -800
-500
The reason for the difference is that language designers can't seem to decide whether the remainder after division should have the sign of the dividend or the divisor. Some languages don't even specify one or the other, so it's up to the implementer.
There's a list of languages, the operator, and which sign to expect on the Modulo operation Wikipedia page. It's a good place to start, but I usually just run a few simple tests to make sure I know exactly how % is going to behave before I use it in any language I've not tested it in before.
A:
In the C standard, negative modulo is undefined, and many C compilers will give you what Java is giving you. In python though, you will always get a positive number, which is often more useful, because it means you can do modulo addition, and subtraction. If negative modulo were to give you a negative, it would not work properly.
I have no idea what advantages getting a negative number from a modulo has.
A:
I prefer x mod n to give numbers between 0 and n-1 or between floor(n/2)-n and floor(n/2); this makes it easiest to do the math in one's head.
As long as everything is equivalent, I don't really care when it comes to languages--though one does have to be aware of the convention.
Incidentally, Java can't quite make up its mind--% on negative integers returns a negative value, the mod method of java.math.BigInteger returns values between 0 and n-1 (inclusive), and the divideAndRemainder method again returns negative values for negative integers.
|
Difference Between Modulus Implementation in Python Vs Java
|
I've noticed differing implementations of the modulus operator in Python and Java.
For example, in Python:
>>> print -300 % 800
>>> 500
Whereas in Java:
System.out.println(-300 % 800);
-300
This caught me off guard, since I thought something as basic as modulus was universally interpreted the same way. I'm a fan of Python's interpretation (which I presume is borrowed from C), although I see the logic behind Java's implementation.
Which do you typically prefer? Is there any specific reason for the differing interpretations? I have no intention of starting a language war, simply curious.
|
[
"I prefer C's interpretation (also used in Python), where % is indeed a modulus operator. Good discussion in the wikipedia page and the links from it (including one bit about why taking instead the sign of the dividend can lead to one silly bug unless one's careful;-).\n",
"Now try this:\n>>> print 300 % -800\n-500\n\nThe reason for the difference is that language designers can't seem to decide whether the remainder after division should have the sign of the dividend or the divisor. Some languages don't even specify one or the other, so it's up to the implementer.\nThere's a list of languages, the operator, and which sign to expect on the Modulo operation Wikipedia page. It's a good place to start, but I usually just run a few simple tests to make sure I know exactly how % is going to behave before I use it in any language I've not tested it in before.\n",
"In the C standard, negative modulo is undefined, and many C compilers will give you what Java is giving you. In python though, you will always get a positive number, which is often more useful, because it means you can do modulo addition, and subtraction. If negative modulo were to give you a negative, it would not work properly.\nI have no idea what advantages getting a negative number from a modulo has.\n",
"I prefer x mod n to give numbers between 0 and n-1 or between floor(n/2)-n and floor(n/2); this makes it easiest to do the math in one's head.\nAs long as everything is equivalent, I don't really care when it comes to languages--though one does have to be aware of the convention.\nIncidentally, Java can't quite make up its mind--% on negative integers returns a negative value, the mod method of java.math.BigInteger returns values between 0 and n-1 (inclusive), and the divideAndRemainder method again returns negative values for negative integers.\n"
] |
[
6,
4,
1,
0
] |
[] |
[] |
[
"java",
"modulo",
"python"
] |
stackoverflow_0002215318_java_modulo_python.txt
|
Q:
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph
Given this 3D bar graph sample code, how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis_date() function without success. I also tried using plot_date(), which doesn't appear to work for 3D bar graphs. Here is a modified version of the sample code to illustrate what I am trying to do:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
dates = [dates.date2num(datetime.datetime(2009,3,12)),
dates.date2num(datetime.datetime(2009,6,9)),
dates.date2num(datetime.datetime(2010,1,1)),
#etc...
]
fig = plt.figure()
ax = Axes3D(fig)
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.array(dates)
ys = np.random.rand(20)
ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8)
ax.set_xlabel('Date & Time')
ax.set_ylabel('Series')
ax.set_zlabel('Amount')
plt.show()
A:
There might be some confusion here, the Axes3D has the properties w_xaxis, w_yaxis and w_zaxis for the axises instead of the usual x-axis, y-axis, etc.
Tested in python 3.8.11, matplotlib 3.4.3
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
import datetime, random
import matplotlib.ticker as ticker
def random_date():
date = datetime.date(2008, 12, 1)
while 1:
date += datetime.timedelta(days=30)
yield (date)
def format_date(x, pos=None):
return dates.num2date(x).strftime('%Y-%m-%d') #use FuncFormatter to format dates
r_d = random_date()
some_dates = [dates.date2num(next(r_d)) for i in range(0,20)]
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.array(some_dates)
ys = np.random.rand(20)
ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8,width=8)
ax.w_xaxis.set_major_locator(ticker.FixedLocator(some_dates)) # I want all the dates on my xaxis
ax.w_xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
for tl in ax.w_xaxis.get_ticklabels(): # re-create what autofmt_xdate but with w_xaxis
tl.set_ha('right')
tl.set_rotation(30)
ax.set_ylabel('Series')
ax.set_zlabel('Amount')
plt.show()
Produces:
|
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph
|
Given this 3D bar graph sample code, how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis_date() function without success. I also tried using plot_date(), which doesn't appear to work for 3D bar graphs. Here is a modified version of the sample code to illustrate what I am trying to do:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
dates = [dates.date2num(datetime.datetime(2009,3,12)),
dates.date2num(datetime.datetime(2009,6,9)),
dates.date2num(datetime.datetime(2010,1,1)),
#etc...
]
fig = plt.figure()
ax = Axes3D(fig)
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.array(dates)
ys = np.random.rand(20)
ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8)
ax.set_xlabel('Date & Time')
ax.set_ylabel('Series')
ax.set_zlabel('Amount')
plt.show()
|
[
"There might be some confusion here, the Axes3D has the properties w_xaxis, w_yaxis and w_zaxis for the axises instead of the usual x-axis, y-axis, etc.\nTested in python 3.8.11, matplotlib 3.4.3\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.dates as dates\nimport datetime, random\nimport matplotlib.ticker as ticker\n\ndef random_date():\n date = datetime.date(2008, 12, 1)\n while 1:\n date += datetime.timedelta(days=30)\n yield (date)\n\ndef format_date(x, pos=None):\n return dates.num2date(x).strftime('%Y-%m-%d') #use FuncFormatter to format dates\n\nr_d = random_date()\nsome_dates = [dates.date2num(next(r_d)) for i in range(0,20)]\n\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(projection='3d')\n\nfor c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):\n xs = np.array(some_dates)\n ys = np.random.rand(20)\n ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8,width=8)\n\nax.w_xaxis.set_major_locator(ticker.FixedLocator(some_dates)) # I want all the dates on my xaxis\nax.w_xaxis.set_major_formatter(ticker.FuncFormatter(format_date))\nfor tl in ax.w_xaxis.get_ticklabels(): # re-create what autofmt_xdate but with w_xaxis\n tl.set_ha('right')\n tl.set_rotation(30) \n\nax.set_ylabel('Series')\nax.set_zlabel('Amount')\n\nplt.show()\n\nProduces:\n\n"
] |
[
16
] |
[] |
[] |
[
"data_analysis",
"graph",
"matplotlib",
"numpy",
"python"
] |
stackoverflow_0002195983_data_analysis_graph_matplotlib_numpy_python.txt
|
Q:
Conditional output in Sphinx Documentation
I'm writing some documentation with Sphinx and I'd like to print out a certain block of text only for HTML documentation, not for LaTeX documentation. Something tells me I should be able to do this with sphinx.ext.ifconfig but I can't figure out how. Does anyone know how to do this?
A:
No extension is required. Just use the only directive.
(old link, from original 2010 post)
https://web.archive.org/web/20100129001557/http://sphinx.pocoo.org/markup/misc.html#including-content-based-on-tags
(latest link)
https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#including-content-based-on-tags
It works like this:
.. only:: latex
The stuff in here only appears in the latex output.
.. only:: html
The stuff in this block only appears in the HTML output. It's
often useful to use this directive with it:
.. raw:: html
It's good for embedding stuff, like video.
|
Conditional output in Sphinx Documentation
|
I'm writing some documentation with Sphinx and I'd like to print out a certain block of text only for HTML documentation, not for LaTeX documentation. Something tells me I should be able to do this with sphinx.ext.ifconfig but I can't figure out how. Does anyone know how to do this?
|
[
"No extension is required. Just use the only directive. \n(old link, from original 2010 post)\nhttps://web.archive.org/web/20100129001557/http://sphinx.pocoo.org/markup/misc.html#including-content-based-on-tags\n(latest link)\nhttps://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#including-content-based-on-tags\nIt works like this:\n\n.. only:: latex\n\n The stuff in here only appears in the latex output.\n\n.. only:: html\n\n The stuff in this block only appears in the HTML output. It's\n often useful to use this directive with it:\n\n .. raw:: html\n\n It's good for embedding stuff, like video.\n\n"
] |
[
28
] |
[] |
[] |
[
"python",
"python_sphinx"
] |
stackoverflow_0002215518_python_python_sphinx.txt
|
Q:
In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)?
This is Python question. I have a variable A
>>> A
<Swig Object of type 'uint16_t *' at 0x8c66fa0>
>>> help(A)
class PySwigObject(object)
Swig object carries a C/C++ instance pointer
The instance referred by A is a contiguous array uint16[3] and the problem is to gain access to that array from Python.
In Python, how can I create a variable B of length 3, that gives me read/write access to the same memory pointed by the pointer wrapped in A?
I think the problem has two parts:
How to get the pointer out of A. (I think 0x8c66fa0 points to a Swig object, not the wrapped object).
How to initialise some kind of Python array using a memory pointer and a known data type. (Numpy has a frombuffer method, but what seems to be needed is a frommemory method.) Perhaps some casting will be needed.
This should be easy I think, but I've been reading and hacking for more than a day!
To solve the second part, I think an example could begin this way:
>>> import numpy
>>> C = numpy.ascontiguousarray([5,6,7],"uint16")
>>> C
array([5, 6, 7], dtype=uint16)
>>> C.data
<read-write buffer for 0x8cd9340, size 6, offset 0 at 0x8902f00>
Then try to build B (of whatever vector type) using "0x8902f00" and "uint16" and test if changing B[2] causes changes in C[2].
Many thanks for your suggestions or a clear example.
Regards,
Owen
A:
After more reading and trying stuff out, the answers are as follows:
1. The wrapped pointer in PySwigObject A is available as A.__long__() .
2. A raw pointer can be cast into an indexable type using ctypes as follows
import ctypes
pA = ctypes.cast( A.__long__(), ctypes.POINTER( ctypes.c_uint16 ) )
Then the elements can be addressed as pA[0], pA[1] etc
pA points to the same memory as the original object, therefore be careful not to use pA after the original object is deleted.
Here is an example for just the second part of the problem (on using a raw pointer of known type in Python),
C = numpy.ascontiguousarray([5,6,7],"uint16") # make an array
C
rawPointer = C.ctypes.data
pC = ctypes.cast( rawPointer, ctypes.POINTER( ctypes.c_uint16 ))
pC[0:3]
pC[1]=100
pC[0:3]
C
Running the example in Python will show that both C[1] and pC[1] have been changed to 100.
Solved. :)
|
In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)?
|
This is Python question. I have a variable A
>>> A
<Swig Object of type 'uint16_t *' at 0x8c66fa0>
>>> help(A)
class PySwigObject(object)
Swig object carries a C/C++ instance pointer
The instance referred by A is a contiguous array uint16[3] and the problem is to gain access to that array from Python.
In Python, how can I create a variable B of length 3, that gives me read/write access to the same memory pointed by the pointer wrapped in A?
I think the problem has two parts:
How to get the pointer out of A. (I think 0x8c66fa0 points to a Swig object, not the wrapped object).
How to initialise some kind of Python array using a memory pointer and a known data type. (Numpy has a frombuffer method, but what seems to be needed is a frommemory method.) Perhaps some casting will be needed.
This should be easy I think, but I've been reading and hacking for more than a day!
To solve the second part, I think an example could begin this way:
>>> import numpy
>>> C = numpy.ascontiguousarray([5,6,7],"uint16")
>>> C
array([5, 6, 7], dtype=uint16)
>>> C.data
<read-write buffer for 0x8cd9340, size 6, offset 0 at 0x8902f00>
Then try to build B (of whatever vector type) using "0x8902f00" and "uint16" and test if changing B[2] causes changes in C[2].
Many thanks for your suggestions or a clear example.
Regards,
Owen
|
[
"After more reading and trying stuff out, the answers are as follows:\n\n1. The wrapped pointer in PySwigObject A is available as A.__long__() .\n\n2. A raw pointer can be cast into an indexable type using ctypes as follows\n\nimport ctypes\npA = ctypes.cast( A.__long__(), ctypes.POINTER( ctypes.c_uint16 ) )\n\nThen the elements can be addressed as pA[0], pA[1] etc\npA points to the same memory as the original object, therefore be careful not to use pA after the original object is deleted.\nHere is an example for just the second part of the problem (on using a raw pointer of known type in Python),\nC = numpy.ascontiguousarray([5,6,7],\"uint16\") # make an array\nC\nrawPointer = C.ctypes.data\npC = ctypes.cast( rawPointer, ctypes.POINTER( ctypes.c_uint16 ))\npC[0:3]\npC[1]=100\npC[0:3]\nC\n\nRunning the example in Python will show that both C[1] and pC[1] have been changed to 100.\nSolved. :)\n"
] |
[
8
] |
[] |
[] |
[
"ctypes",
"python",
"swig"
] |
stackoverflow_0002209395_ctypes_python_swig.txt
|
Q:
Are there any free alternatives to the Ranorex library (Python, Windows)?
I am interested in the Python one. I wish to automate some GUI under Windows. What is the best open source library for that with no strings attached? Thanks.
A:
Try pyWinAuto.
A:
There's WATSUP, but I've not tried it yet myself.
I've also heard of pyWinAuto, although the link I have is to pyWinAuto on SourceForge.
|
Are there any free alternatives to the Ranorex library (Python, Windows)?
|
I am interested in the Python one. I wish to automate some GUI under Windows. What is the best open source library for that with no strings attached? Thanks.
|
[
"Try pyWinAuto.\n",
"There's WATSUP, but I've not tried it yet myself.\nI've also heard of pyWinAuto, although the link I have is to pyWinAuto on SourceForge.\n"
] |
[
2,
1
] |
[] |
[] |
[
"automation",
"python",
"user_interface",
"windows"
] |
stackoverflow_0002215154_automation_python_user_interface_windows.txt
|
Q:
What is this traceback error in Python?
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/ea/ea-repos/hell/life/views.py" in linkedin_auth
137. token = oauth_linkedin.get_unauthorised_request_token()
File "/home/ea/ea-repos/hell/life/oauth_linkedin.py" in get_unauthorised_request_token
54. resp = fetch_response(oauth_request, connection)
File "/home/ea/ea-repos/hell/life/oauth_linkedin.py" in fetch_response
44. connection.request(oauth_request.http_method,url)
File "/usr/lib/python2.6/httplib.py" in request
874. self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py" in _send_request
891. self.putrequest(method, url, **skips)
File "/usr/lib/python2.6/httplib.py" in putrequest
778. raise CannotSendRequest()
Exception Type: CannotSendRequest at /linkedin/auth
Exception Value:
More specifically, it is occuring in this function:
def fetch_response(oauth_request, connection, linkedin_getinfo = False, other_url = ''):
url = oauth_request.to_url()
if linkedin_getinfo:
headers = oauth_request.to_header()
connection.request(oauth_request.http_method,other_url, headers = headers)
else:
connection.request(oauth_request.http_method,url)
response = connection.getresponse()
s = response.read()
return s
A:
Look at this answer to see if it helps you:
httplib CannotSendRequest error in WSGI
|
What is this traceback error in Python?
|
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/ea/ea-repos/hell/life/views.py" in linkedin_auth
137. token = oauth_linkedin.get_unauthorised_request_token()
File "/home/ea/ea-repos/hell/life/oauth_linkedin.py" in get_unauthorised_request_token
54. resp = fetch_response(oauth_request, connection)
File "/home/ea/ea-repos/hell/life/oauth_linkedin.py" in fetch_response
44. connection.request(oauth_request.http_method,url)
File "/usr/lib/python2.6/httplib.py" in request
874. self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py" in _send_request
891. self.putrequest(method, url, **skips)
File "/usr/lib/python2.6/httplib.py" in putrequest
778. raise CannotSendRequest()
Exception Type: CannotSendRequest at /linkedin/auth
Exception Value:
More specifically, it is occuring in this function:
def fetch_response(oauth_request, connection, linkedin_getinfo = False, other_url = ''):
url = oauth_request.to_url()
if linkedin_getinfo:
headers = oauth_request.to_header()
connection.request(oauth_request.http_method,other_url, headers = headers)
else:
connection.request(oauth_request.http_method,url)
response = connection.getresponse()
s = response.read()
return s
|
[
"Look at this answer to see if it helps you:\nhttplib CannotSendRequest error in WSGI\n"
] |
[
1
] |
[] |
[] |
[
"django",
"oauth",
"python",
"url"
] |
stackoverflow_0002216259_django_oauth_python_url.txt
|
Q:
PostgreSQL problem in Django
I have a Django application and I'm using postgres. I try to execute the bollowing line in one of my tests:
print BillingUser.objects.all()
And I get the following error:
"current transaction is aborted, commands ignored until end of transaction block."
My postresql log:
ERROR: duplicate key value violates unique constraint "billing_rental_wallet_id_key"
STATEMENT: INSERT INTO "billing_rental" ("wallet_id", "item_id", "end_time", "time", "value", "index", "info") VALUES (61, 230, E'2010-02-11 11:01:01.092336', E'2010-02-01 11:01:01.092336', 10.0, 1, NULL)
ERROR: current transaction is aborted, commands ignored until end of transaction block
STATEMENT: INSERT INTO "billing_timeable" ("creation_date", "update_date") VALUES (E'2010-02-01 11:01:01.093504', E'2010-02-01 11:01:01.093531')
ERROR: current transaction is aborted, commands ignored until end of transaction block
STATEMENT: SELECT "billing_timeable"."id", "billing_timeable"."creation_date", "billing_timeable"."update_date", "billing_billinguser"."timeable_ptr_id", "billing_billinguser"."username", "billing_billinguser"."pin", "billing_billinguser"."sbox_id", "billing_billinguser"."parental_code", "billing_billinguser"."active" FROM "billing_billinguser" INNER JOIN "billing_timeable" ON ("billing_billinguser"."timeable_ptr_id" = "billing_timeable"."id") LIMIT 21
How can I fix that?
Thanks, Arshavski Alexander.
A:
Ok... looking at the PostgreSQL log, it does look that you are doing a wrong insert that will abort the transaction... now, looking at your code I think the problems lies here:
at lines 78-81
currency = Currency.objects.all()[2]
if not Wallet.objects.filter(user=user):
wallet = Wallet(user=user, currency=currency)
wallet.save()
You will create a wallet for the current user, but then on line 87-88 you wrote:
user.wallet.amount = 12.0
user.wallet.save()
However, as you save the wallet after retrieving the user, it does not know that you had already created a wallet for him, and having a OneToOne relationship, this will cause the error you're having... I think what you should do is to add a line after 81:
currency = Currency.objects.all()[2]
if not Wallet.objects.filter(user=user):
wallet = Wallet(user=user, currency=currency)
wallet.save()
user.wallet = wallet
That should solve the issue....
A:
From the log it looks like you are trying to insert an item with a duplicate ID which throws an error and the rest of your code can't access the DB anymore. Fix that query, and it should work.
A:
You insert data in some of your test functions. After invalid insert DB connections is in fail state. You need to rollback transaction or turn it off completely. See django docs on transactions and testing them.
|
PostgreSQL problem in Django
|
I have a Django application and I'm using postgres. I try to execute the bollowing line in one of my tests:
print BillingUser.objects.all()
And I get the following error:
"current transaction is aborted, commands ignored until end of transaction block."
My postresql log:
ERROR: duplicate key value violates unique constraint "billing_rental_wallet_id_key"
STATEMENT: INSERT INTO "billing_rental" ("wallet_id", "item_id", "end_time", "time", "value", "index", "info") VALUES (61, 230, E'2010-02-11 11:01:01.092336', E'2010-02-01 11:01:01.092336', 10.0, 1, NULL)
ERROR: current transaction is aborted, commands ignored until end of transaction block
STATEMENT: INSERT INTO "billing_timeable" ("creation_date", "update_date") VALUES (E'2010-02-01 11:01:01.093504', E'2010-02-01 11:01:01.093531')
ERROR: current transaction is aborted, commands ignored until end of transaction block
STATEMENT: SELECT "billing_timeable"."id", "billing_timeable"."creation_date", "billing_timeable"."update_date", "billing_billinguser"."timeable_ptr_id", "billing_billinguser"."username", "billing_billinguser"."pin", "billing_billinguser"."sbox_id", "billing_billinguser"."parental_code", "billing_billinguser"."active" FROM "billing_billinguser" INNER JOIN "billing_timeable" ON ("billing_billinguser"."timeable_ptr_id" = "billing_timeable"."id") LIMIT 21
How can I fix that?
Thanks, Arshavski Alexander.
|
[
"Ok... looking at the PostgreSQL log, it does look that you are doing a wrong insert that will abort the transaction... now, looking at your code I think the problems lies here:\nat lines 78-81\n currency = Currency.objects.all()[2]\n if not Wallet.objects.filter(user=user):\n wallet = Wallet(user=user, currency=currency)\n wallet.save()\n\nYou will create a wallet for the current user, but then on line 87-88 you wrote:\n user.wallet.amount = 12.0\n user.wallet.save()\n\nHowever, as you save the wallet after retrieving the user, it does not know that you had already created a wallet for him, and having a OneToOne relationship, this will cause the error you're having... I think what you should do is to add a line after 81:\n currency = Currency.objects.all()[2]\n if not Wallet.objects.filter(user=user):\n wallet = Wallet(user=user, currency=currency)\n wallet.save()\n user.wallet = wallet\n\nThat should solve the issue....\n",
"From the log it looks like you are trying to insert an item with a duplicate ID which throws an error and the rest of your code can't access the DB anymore. Fix that query, and it should work.\n",
"You insert data in some of your test functions. After invalid insert DB connections is in fail state. You need to rollback transaction or turn it off completely. See django docs on transactions and testing them.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"postgresql",
"python",
"sql"
] |
stackoverflow_0002175615_django_postgresql_python_sql.txt
|
Q:
wxpython GUI having static Japanese text and chinese static text
We want to support localization of the static text (labels, button labels, etc) to Japanese and Chinese in wxpython. We want only static text within the GUI elements to be changed, hard coding of Japanese or Chinese characters in the label(static text fields) would do the work for us.
Any help on how to pursue this would be helpful.
Thank you
A:
see: wx.GetTranslation
http://wiki.wxpython.org/Internationalization
What I do, is use _ = wx.GetTranslation at the top of my scripts, and enclose any strings in _("My String")
I use this batch script: http://code.google.com/p/gui2exe/source/browse/trunk/scripts/gen_lang to run the mki18n.py script found on the wiki. It basically runs the "gettext" command over your source code, and picks out your strings to translate that match the _("") format.
You then add a message catalogue to wxPython:
self.locale = wx.Locale(wx.LANGUAGE_JAPANESE, wx.LOCALE_LOAD_DEFAULT)
langdir = os.path.join('path', 'to', 'locale', 'folder')
self.locale.AddCatalogLookupPathPrefix(langdir)
self.locale.AddCatalog("program-name")
Of course, you'll have to allow the user to choose their preferred language, and map the wx.LANGUAGE_* from that. e.g.
languages = ( (_("English"), wx.LANGUAGE_ENGLISH),
(_("English (United Kingdom)"), wx.LANGUAGE_ENGLISH_UK),
(_("Japanese"), wx.LANGUAGE_JAPANESE),
(_("Portuguese"), wx.LANGUAGE_PORTUGUESE),
(_("Dutch"), wx.LANGUAGE_DUTCH),
(_("German"), wx.LANGUAGE_GERMAN),
(_("Russian"), wx.LANGUAGE_RUSSIAN) )
self.locale = wx.Locale(languages[user.preference.language], wx.LOCALE_LOAD_DEFAULT)
|
wxpython GUI having static Japanese text and chinese static text
|
We want to support localization of the static text (labels, button labels, etc) to Japanese and Chinese in wxpython. We want only static text within the GUI elements to be changed, hard coding of Japanese or Chinese characters in the label(static text fields) would do the work for us.
Any help on how to pursue this would be helpful.
Thank you
|
[
"see: wx.GetTranslation\nhttp://wiki.wxpython.org/Internationalization\nWhat I do, is use _ = wx.GetTranslation at the top of my scripts, and enclose any strings in _(\"My String\")\nI use this batch script: http://code.google.com/p/gui2exe/source/browse/trunk/scripts/gen_lang to run the mki18n.py script found on the wiki. It basically runs the \"gettext\" command over your source code, and picks out your strings to translate that match the _(\"\") format.\nYou then add a message catalogue to wxPython:\nself.locale = wx.Locale(wx.LANGUAGE_JAPANESE, wx.LOCALE_LOAD_DEFAULT)\nlangdir = os.path.join('path', 'to', 'locale', 'folder')\nself.locale.AddCatalogLookupPathPrefix(langdir)\nself.locale.AddCatalog(\"program-name\")\n\nOf course, you'll have to allow the user to choose their preferred language, and map the wx.LANGUAGE_* from that. e.g.\nlanguages = ( (_(\"English\"), wx.LANGUAGE_ENGLISH),\n (_(\"English (United Kingdom)\"), wx.LANGUAGE_ENGLISH_UK),\n (_(\"Japanese\"), wx.LANGUAGE_JAPANESE),\n (_(\"Portuguese\"), wx.LANGUAGE_PORTUGUESE),\n (_(\"Dutch\"), wx.LANGUAGE_DUTCH),\n (_(\"German\"), wx.LANGUAGE_GERMAN),\n (_(\"Russian\"), wx.LANGUAGE_RUSSIAN) )\n\n\nself.locale = wx.Locale(languages[user.preference.language], wx.LOCALE_LOAD_DEFAULT)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"unicode",
"wxpython"
] |
stackoverflow_0002214694_python_unicode_wxpython.txt
|
Q:
Adding values in a tuple that is in a list in python
I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18.
A:
>>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(map(sum,l))
18
>>> l[0]=(1,2,3,)
>>> l
[(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(map(sum,l))
23
A:
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> s = sum(i[0] for i in l)
>>> print s
18
A:
Just some fun with itertools, not very readable. Works only if you consider 1st element in tuple.
>>> import itertools
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(*itertools.izip(*l))
18
|
Adding values in a tuple that is in a list in python
|
I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18.
|
[
">>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n\n>>> sum(map(sum,l))\n18\n\n>>> l[0]=(1,2,3,)\n>>> l\n[(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n>>> sum(map(sum,l))\n23\n\n",
">>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n>>> s = sum(i[0] for i in l)\n>>> print s\n18\n\n",
"Just some fun with itertools, not very readable. Works only if you consider 1st element in tuple. \n>>> import itertools\n>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n>>> sum(*itertools.izip(*l))\n18\n\n"
] |
[
7,
4,
0
] |
[] |
[] |
[
"list",
"python",
"tuples"
] |
stackoverflow_0002216450_list_python_tuples.txt
|
Q:
How to make a relation between tables using SQLAlchemy?
Using SQLAlchemy, given tables such as these:
locations_table = Table('locations', metadata,
Column('id', Integer, primary_key=True),
Column('name', Text),
)
players_table = Table('players', metadata,
Column('id', Integer, primary_key=True),
Column('email', Text),
Column('password', Text),
Column('location_id', ForeignKey('locations.id'))
)
and classes such as these:
class Location(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location: %s, %s>' % (self.name)
mapper(Location, locations_table)
class Player(object):
def __init__(self, email, password, location_id):
self.email = email
self.password = password
self.location_id = location_id
def __repr__(self):
return '<Player: %s>' % self.email
mapper(Player, players_table)
and code like this:
location = session.query(Location).first()
player = session.query(Player).first()
(simplified).
How would I go about modifying that to support actions such as these:
# assign location to player using a Location object, as opposed to an ID
player.location = location
# access the Location object associated with the player directly
print player.location.name
and if SQLAlchemy permits:
# print all players having a certain location
print location.players
?
A:
Use sqlalchemy's relation feature:
http://www.sqlalchemy.org/docs/ormtutorial.html#building-a-relation
A:
This should work for you:
mapper(Player, players_table, properties={'location'=relation(Location, uselist=False, backref=backref('players'))})
That way you can access the location directly as you won't get a list. Other than that, you can do location.players which will give you an InstrumentedList back, so you can iter over the players
|
How to make a relation between tables using SQLAlchemy?
|
Using SQLAlchemy, given tables such as these:
locations_table = Table('locations', metadata,
Column('id', Integer, primary_key=True),
Column('name', Text),
)
players_table = Table('players', metadata,
Column('id', Integer, primary_key=True),
Column('email', Text),
Column('password', Text),
Column('location_id', ForeignKey('locations.id'))
)
and classes such as these:
class Location(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location: %s, %s>' % (self.name)
mapper(Location, locations_table)
class Player(object):
def __init__(self, email, password, location_id):
self.email = email
self.password = password
self.location_id = location_id
def __repr__(self):
return '<Player: %s>' % self.email
mapper(Player, players_table)
and code like this:
location = session.query(Location).first()
player = session.query(Player).first()
(simplified).
How would I go about modifying that to support actions such as these:
# assign location to player using a Location object, as opposed to an ID
player.location = location
# access the Location object associated with the player directly
print player.location.name
and if SQLAlchemy permits:
# print all players having a certain location
print location.players
?
|
[
"Use sqlalchemy's relation feature:\nhttp://www.sqlalchemy.org/docs/ormtutorial.html#building-a-relation\n",
"This should work for you:\nmapper(Player, players_table, properties={'location'=relation(Location, uselist=False, backref=backref('players'))})\nThat way you can access the location directly as you won't get a list. Other than that, you can do location.players which will give you an InstrumentedList back, so you can iter over the players\n"
] |
[
3,
1
] |
[] |
[] |
[
"orm",
"python",
"relation",
"sqlalchemy"
] |
stackoverflow_0002216887_orm_python_relation_sqlalchemy.txt
|
Q:
gstreamer playbin - setting uri on windows
I am trying to play some audio files with the CLI example on this site:
http://pygstdocs.berlios.de/pygst-tutorial/playbin.html
http://pygstdocs.berlios.de/pygst-tutorial/playbin.html
I am on windows and it is giving error while reading the file. I specified
the following path:
$ python cliplayer.py C:\\voice.mp3
0:00:00.125000000 3788 009DA010 ERROR basesrc
gstbasesrc.c:2834:gst_base_src_activate_pull:<source> Failed to start in
pull mode
Error: Could not open resource for reading.
..\..\..\Source\gst-plugins-base\ext\gio\gstgiosrc.c(324):
gst_gio_src_get_stream ():
/GstPlayBin2:player/GstURIDecodeBin:uridecodebin0/GstGioSrc:source:
Could not open location file:///C:/file:/C:/voice.mp3 for reading: Error
opening file: Invalid argument
How should I specify the file path on windows??
Also, is there anything special I need to do in this line of code?
self.player.set_property("uri", "file://" + filepath)
Thank you!
A:
As you may have suspected, this code is rather badly written:
for filepath in sys.argv[1:]:
# ...
self.player.set_property("uri", "file://" + filepath)
Use something like this:
'file:' + urllib.pathname2url(filepath)
and (in the command line) specify the file path in normal Windows notation, e.g. C:\a\b.mp3.
A:
Did you notice the actual path you've got is file:///C:/file:/C:/voice.mp3?
The correct path should be: file:///C:/path/to/voice.mp3.
|
gstreamer playbin - setting uri on windows
|
I am trying to play some audio files with the CLI example on this site:
http://pygstdocs.berlios.de/pygst-tutorial/playbin.html
http://pygstdocs.berlios.de/pygst-tutorial/playbin.html
I am on windows and it is giving error while reading the file. I specified
the following path:
$ python cliplayer.py C:\\voice.mp3
0:00:00.125000000 3788 009DA010 ERROR basesrc
gstbasesrc.c:2834:gst_base_src_activate_pull:<source> Failed to start in
pull mode
Error: Could not open resource for reading.
..\..\..\Source\gst-plugins-base\ext\gio\gstgiosrc.c(324):
gst_gio_src_get_stream ():
/GstPlayBin2:player/GstURIDecodeBin:uridecodebin0/GstGioSrc:source:
Could not open location file:///C:/file:/C:/voice.mp3 for reading: Error
opening file: Invalid argument
How should I specify the file path on windows??
Also, is there anything special I need to do in this line of code?
self.player.set_property("uri", "file://" + filepath)
Thank you!
|
[
"As you may have suspected, this code is rather badly written:\nfor filepath in sys.argv[1:]:\n # ...\n self.player.set_property(\"uri\", \"file://\" + filepath)\n\nUse something like this:\n'file:' + urllib.pathname2url(filepath)\n\nand (in the command line) specify the file path in normal Windows notation, e.g. C:\\a\\b.mp3.\n",
"Did you notice the actual path you've got is file:///C:/file:/C:/voice.mp3?\nThe correct path should be: file:///C:/path/to/voice.mp3.\n"
] |
[
9,
4
] |
[] |
[] |
[
"gstreamer",
"python"
] |
stackoverflow_0002216064_gstreamer_python.txt
|
Q:
Django URL configuration
Assume I have 3 Models: City, Area, Entry.
Each city has several Areas and each area can have several entries BUT for "now", there can be will be only one active Entry and it will be shown. So in logic:
Note that each city, area, entry will be using slug variable of related model class
Format will be in such:
www.mysite.com/<slug of city>/<slug of area>/<slug of entry>
www.mysite.com/mycity/myarea/ -> will be displaying an Entry that is bound to that Area AND active (this can be detected by using Area's active_entry function).
But users can view some old Entries such as:
www.mysite.com/mycity/myarea/some-old-entry-that-is-no-longer-active
I have written get_absolute_url functions by reading the "Practical Django Projects 2nd Edition" book but now I am stucked.
I have such models:
from django.db import models
class Entry(models.Model):
area = models.ForeignKey('Area',verbose_name="The area that this entry belongs to")
slug = slug = models.SlugField(unique=True) # this will be auto populated via admin panel, from title
title = baslik = models.CharField()
content = models.TextField()
start_time = models.DateTimeField()#start time for this entry.
end_time = models.DateTimeField()#end time for this entry.
@models.permalink
def get_absolute_url(self):
return ("entry.detail",(),{"city":self.area.city.slug,"area":self.area.slug,"entry":self.slug})
class Area(models.Model):
city = models.ForeignKey(verbose_name="city that this area belongs to")
name = models.CharField(max_length=30)
slug = models.SlugField(unique=True)# this will be auto populated via admin panel, from name
@models.permalink
def get_absolute_url(self):
return ("bolge.detay",(),{"city":self.city.slug,"area":self.slug})
def active_entry(self):
from datetime import datetime, date, time
now = datetime.now()
try:
return Entry.objects.get(area__exact=self,start_time__lte=now,end_time__gte=now)
except Entry.DoesNotExist:
return False
class City(models.Model):
name =models.CharField(max_length=30)
slug = models.SlugField(unique=True) # this will be auto populated via admin panel, from name
@models.permalink
def get_absolute_url(self):
return ("city.detail",(),{"city":self.slug})
Please help this poor soul to configure his url configuration.
Thanks
A:
It should probably look like something like that:
urlpatterns = patterns('',
(r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/$', 'yourapp.views.areaview'),
(r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/(?P<entry>[a-z-]+)/$', 'yourapp.views.entryview'),
)
|
Django URL configuration
|
Assume I have 3 Models: City, Area, Entry.
Each city has several Areas and each area can have several entries BUT for "now", there can be will be only one active Entry and it will be shown. So in logic:
Note that each city, area, entry will be using slug variable of related model class
Format will be in such:
www.mysite.com/<slug of city>/<slug of area>/<slug of entry>
www.mysite.com/mycity/myarea/ -> will be displaying an Entry that is bound to that Area AND active (this can be detected by using Area's active_entry function).
But users can view some old Entries such as:
www.mysite.com/mycity/myarea/some-old-entry-that-is-no-longer-active
I have written get_absolute_url functions by reading the "Practical Django Projects 2nd Edition" book but now I am stucked.
I have such models:
from django.db import models
class Entry(models.Model):
area = models.ForeignKey('Area',verbose_name="The area that this entry belongs to")
slug = slug = models.SlugField(unique=True) # this will be auto populated via admin panel, from title
title = baslik = models.CharField()
content = models.TextField()
start_time = models.DateTimeField()#start time for this entry.
end_time = models.DateTimeField()#end time for this entry.
@models.permalink
def get_absolute_url(self):
return ("entry.detail",(),{"city":self.area.city.slug,"area":self.area.slug,"entry":self.slug})
class Area(models.Model):
city = models.ForeignKey(verbose_name="city that this area belongs to")
name = models.CharField(max_length=30)
slug = models.SlugField(unique=True)# this will be auto populated via admin panel, from name
@models.permalink
def get_absolute_url(self):
return ("bolge.detay",(),{"city":self.city.slug,"area":self.slug})
def active_entry(self):
from datetime import datetime, date, time
now = datetime.now()
try:
return Entry.objects.get(area__exact=self,start_time__lte=now,end_time__gte=now)
except Entry.DoesNotExist:
return False
class City(models.Model):
name =models.CharField(max_length=30)
slug = models.SlugField(unique=True) # this will be auto populated via admin panel, from name
@models.permalink
def get_absolute_url(self):
return ("city.detail",(),{"city":self.slug})
Please help this poor soul to configure his url configuration.
Thanks
|
[
"It should probably look like something like that:\nurlpatterns = patterns('',\n (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/$', 'yourapp.views.areaview'),\n (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/(?P<entry>[a-z-]+)/$', 'yourapp.views.entryview'),\n)\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_urls",
"python"
] |
stackoverflow_0002217149_django_django_urls_python.txt
|
Q:
Python regex for reading CSV-like rows
I want to parse incoming CSV-like rows of data. Values are separated with commas (and there could be leading and trailing whitespaces around commas), and can be quoted either with ' or with ". For example - this is a valid row:
data1, data2 ,"data3'''", 'data4""',,,data5,
but this one is malformed:
data1, data2, da"ta3", 'data4',
-- quotation marks can only be prepended or trailed by spaces.
Such malformed rows should be recognized - best would be to somehow mark malformed value within row, but if regex doesn't match the whole row then it's also acceptable.
I'm trying to write regex able to parse this, using either match() of findall(), but every single regex I'm coming with has some problems with edge cases.
So, maybe someone with experience in parsing something similar could help me on this?
(Or maybe this is too complex for regex and I should just write a function)
EDIT1:
csv module is not much of use here:
>>> list(csv.reader(StringIO('''2, "dat,a1", 'dat,a2',''')))
[['2', ' "dat', 'a1"', " 'dat", "a2'", '']]
>>> list(csv.reader(StringIO('''2,"dat,a1",'dat,a2',''')))
[['2', 'dat,a1', "'dat", "a2'", '']]
-- unless this can be tuned?
EDIT2: A few language edits - I hope it's more valid English now
EDIT3: Thank you for all answers, I'm now pretty sure that regular expression is not that good idea here as (1) covering all edge cases can be tricky (2) writer output is not regular. Writing that, I've decided to check mentioned pyparsing and either use it, or write custom FSM-like parser.
A:
While the csv module is the right answer here, a regex that could do this is quite doable:
import re
r = re.compile(r'''
\s* # Any whitespace.
( # Start capturing here.
[^,"']+? # Either a series of non-comma non-quote characters.
| # OR
"(?: # A double-quote followed by a string of characters...
[^"\\]|\\. # That are either non-quotes or escaped...
)* # ...repeated any number of times.
" # Followed by a closing double-quote.
| # OR
'(?:[^'\\]|\\.)*'# Same as above, for single quotes.
) # Done capturing.
\s* # Allow arbitrary space before the comma.
(?:,|$) # Followed by a comma or the end of a string.
''', re.VERBOSE)
line = r"""data1, data2 ,"data3'''", 'data4""',,,data5,"""
print r.findall(line)
# That prints: ['data1', 'data2', '"data3\'\'\'"', '\'data4""\'', 'data5']
EDIT: To validate lines, you can reuse the regex above with small additions:
import re
r_validation = re.compile(r'''
^(?: # Capture from the start.
# Below is the same regex as above, but condensed.
# One tiny modification is that it allows empty values
# The first plus is replaced by an asterisk.
\s*([^,"']*?|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*(?:,|$)
)*$ # And don't stop until the end.
''', re.VERBOSE)
line1 = r"""data1, data2 ,"data3'''", 'data4""',,,data5,"""
line2 = r"""data1, data2, da"ta3", 'data4',"""
if r_validation.match(line1):
print 'Line 1 is valid.'
else:
print 'Line 1 is INvalid.'
if r_validation.match(line2):
print 'Line 2 is valid.'
else:
print 'Line 2 is INvalid.'
# Prints:
# Line 1 is valid.
# Line 2 is INvalid.
A:
Although it would likely be possible with some combination of pre-processing, use of csv module, post-processing, and use of regular expressions, your stated requirements do not fit well with the design of the csv module, nor possibly with regular expressions (depending on the complexity of nested quotation marks that you might have to handle).
In complex parsing cases, pyparsing is always a good package to fall back on. If this isn't a one-off situation, it will likely produce the most straightforward and maintainable result, at the cost of possibly a little extra effort up front. Consider that investment to be paid back quickly, however, as you save yourself the extra effort of debugging the regex solutions to handle corner cases...
You can likely find examples of pyparsing-based CSV parsing easily, with this question maybe enough to get you started.
A:
Python has a standard library module to read csv files:
import csv
reader = csv.reader(open('file.csv'))
for line in reader:
print line
For your example input this prints
['data1', ' data2 ', "data3'''", ' \'data4""\'', '', '', 'data5', '']
EDIT:
you need to add skipinitalspace=True to allow spaces before double quotation marks for the extra examples you provided. Not sure about the single quotes yet.
>>> list(csv.reader(StringIO('''2, "dat,a1", 'dat,a2','''), skipinitialspace=True))
[['2', 'dat,a1', "'dat", "a2'", '']]
>>> list(csv.reader(StringIO('''2,"dat,a1",'dat,a2','''), skipinitialspace=True))
[['2', 'dat,a1', "'dat", "a2'", '']]
A:
It is not possible to give you an answer, because you have not completely specified the protocol that is being used by the writer.
It evidently contains rules like:
If a field contains any commas or single quotes, quote it with double quotes.
Else if the field contains any double quotes, quote it with single quotes.
Note: the result is still valid if you swap double and single in the above 2 clauses.
Else don't quote it.
The resultant field may have spaces (or other whitespace?) prepended or appended.
The so-augmented fields are assembled into a row, separated by commas and terminated by the platform's newline (LF or CRLF).
What is not mentioned is what the writer does in these cases:
(0) field contains BOTH single quotes and double quotes
(1) field contains leading non-newline whitespace
(2) field contains trailing non-newline whitespace
(3) field contains any newlines.
Where the writer ignores any of these cases, please specify what outcomes you want.
You also mention "quotation marks can only be prepended or trailed by spaces" -- surely you mean commas are allowed also, otherwise your example 'data4""',,,data5, fails on the first comma.
How is your data encoded?
A:
This probably sounds too simple, but really from the looks of things you are looking for a string that contains either [a-zA-Z0-9]["']+[a-zA-Z0-9], I mean without in depth testing against the data really what you're looking for is a quote or double quote (or any combination) in between letters (you could also add numbers there).
Based on what you were asking, it really doesn't matter that it's a CSV, it matter's that you have data that doesn't conform. Which I believe just doing a search for a letter, then any combination of one or more " or ' and another letter.
Now are you looking to get a "quantity" or just a printout of the line that contains it so you know which ones to go back and fix?
I'm sorry I don't know python regex's but in perl this would look something like this:
# Look for one or more letter/number at least one ' or " or more and at least one
# or more letter/number
if ($line =~ m/[a-zA-Z0-9]+['"]+[a-zA-Z0-9]+/ig)
{
# Prints the line if the above regex is found
print $line;
}
Just simply convert that for when you look at a line.
I'm sorry if I misunderstood the question
I hope it helps!
A:
If your goal is to convert the data to XML (or JSON, or YAML), look at this example for a Gelatin syntax that produces the following output:
<xml>
<line>
<column>data1</column>
<column>data2 </column>
<column>data3'''</column>
<column>data4""</column>
<column/>
<column/>
<column>data5</column>
<column/>
</line>
</xml>
Note that Gelatin also has a Python API:
from Gelatin.util import compile, generate_to_file
syntax = compile('syntax.gel')
generate_to_file(syntax, 'input.csv', 'output.xml', 'xml')
|
Python regex for reading CSV-like rows
|
I want to parse incoming CSV-like rows of data. Values are separated with commas (and there could be leading and trailing whitespaces around commas), and can be quoted either with ' or with ". For example - this is a valid row:
data1, data2 ,"data3'''", 'data4""',,,data5,
but this one is malformed:
data1, data2, da"ta3", 'data4',
-- quotation marks can only be prepended or trailed by spaces.
Such malformed rows should be recognized - best would be to somehow mark malformed value within row, but if regex doesn't match the whole row then it's also acceptable.
I'm trying to write regex able to parse this, using either match() of findall(), but every single regex I'm coming with has some problems with edge cases.
So, maybe someone with experience in parsing something similar could help me on this?
(Or maybe this is too complex for regex and I should just write a function)
EDIT1:
csv module is not much of use here:
>>> list(csv.reader(StringIO('''2, "dat,a1", 'dat,a2',''')))
[['2', ' "dat', 'a1"', " 'dat", "a2'", '']]
>>> list(csv.reader(StringIO('''2,"dat,a1",'dat,a2',''')))
[['2', 'dat,a1', "'dat", "a2'", '']]
-- unless this can be tuned?
EDIT2: A few language edits - I hope it's more valid English now
EDIT3: Thank you for all answers, I'm now pretty sure that regular expression is not that good idea here as (1) covering all edge cases can be tricky (2) writer output is not regular. Writing that, I've decided to check mentioned pyparsing and either use it, or write custom FSM-like parser.
|
[
"While the csv module is the right answer here, a regex that could do this is quite doable:\nimport re\n\nr = re.compile(r'''\n \\s* # Any whitespace.\n ( # Start capturing here.\n [^,\"']+? # Either a series of non-comma non-quote characters.\n | # OR\n \"(?: # A double-quote followed by a string of characters...\n [^\"\\\\]|\\\\. # That are either non-quotes or escaped...\n )* # ...repeated any number of times.\n \" # Followed by a closing double-quote.\n | # OR\n '(?:[^'\\\\]|\\\\.)*'# Same as above, for single quotes.\n ) # Done capturing.\n \\s* # Allow arbitrary space before the comma.\n (?:,|$) # Followed by a comma or the end of a string.\n ''', re.VERBOSE)\n\nline = r\"\"\"data1, data2 ,\"data3'''\", 'data4\"\"',,,data5,\"\"\"\n\nprint r.findall(line)\n\n# That prints: ['data1', 'data2', '\"data3\\'\\'\\'\"', '\\'data4\"\"\\'', 'data5']\n\nEDIT: To validate lines, you can reuse the regex above with small additions:\nimport re\n\nr_validation = re.compile(r'''\n ^(?: # Capture from the start.\n # Below is the same regex as above, but condensed.\n # One tiny modification is that it allows empty values\n # The first plus is replaced by an asterisk.\n \\s*([^,\"']*?|\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*(?:,|$)\n )*$ # And don't stop until the end.\n ''', re.VERBOSE)\n\nline1 = r\"\"\"data1, data2 ,\"data3'''\", 'data4\"\"',,,data5,\"\"\"\nline2 = r\"\"\"data1, data2, da\"ta3\", 'data4',\"\"\"\n\nif r_validation.match(line1):\n print 'Line 1 is valid.'\nelse:\n print 'Line 1 is INvalid.'\n\nif r_validation.match(line2):\n print 'Line 2 is valid.'\nelse:\n print 'Line 2 is INvalid.'\n\n# Prints:\n# Line 1 is valid.\n# Line 2 is INvalid.\n\n",
"Although it would likely be possible with some combination of pre-processing, use of csv module, post-processing, and use of regular expressions, your stated requirements do not fit well with the design of the csv module, nor possibly with regular expressions (depending on the complexity of nested quotation marks that you might have to handle).\nIn complex parsing cases, pyparsing is always a good package to fall back on. If this isn't a one-off situation, it will likely produce the most straightforward and maintainable result, at the cost of possibly a little extra effort up front. Consider that investment to be paid back quickly, however, as you save yourself the extra effort of debugging the regex solutions to handle corner cases...\nYou can likely find examples of pyparsing-based CSV parsing easily, with this question maybe enough to get you started.\n",
"Python has a standard library module to read csv files:\nimport csv\n\nreader = csv.reader(open('file.csv'))\n\nfor line in reader:\n print line\n\nFor your example input this prints\n['data1', ' data2 ', \"data3'''\", ' \\'data4\"\"\\'', '', '', 'data5', '']\n\nEDIT:\nyou need to add skipinitalspace=True to allow spaces before double quotation marks for the extra examples you provided. Not sure about the single quotes yet.\n>>> list(csv.reader(StringIO('''2, \"dat,a1\", 'dat,a2','''), skipinitialspace=True))\n[['2', 'dat,a1', \"'dat\", \"a2'\", '']]\n\n>>> list(csv.reader(StringIO('''2,\"dat,a1\",'dat,a2','''), skipinitialspace=True))\n[['2', 'dat,a1', \"'dat\", \"a2'\", '']]\n\n",
"It is not possible to give you an answer, because you have not completely specified the protocol that is being used by the writer.\nIt evidently contains rules like:\nIf a field contains any commas or single quotes, quote it with double quotes.\nElse if the field contains any double quotes, quote it with single quotes.\nNote: the result is still valid if you swap double and single in the above 2 clauses.\nElse don't quote it.\nThe resultant field may have spaces (or other whitespace?) prepended or appended.\nThe so-augmented fields are assembled into a row, separated by commas and terminated by the platform's newline (LF or CRLF). \nWhat is not mentioned is what the writer does in these cases:\n (0) field contains BOTH single quotes and double quotes\n (1) field contains leading non-newline whitespace\n (2) field contains trailing non-newline whitespace\n (3) field contains any newlines.\nWhere the writer ignores any of these cases, please specify what outcomes you want.\nYou also mention \"quotation marks can only be prepended or trailed by spaces\" -- surely you mean commas are allowed also, otherwise your example 'data4\"\"',,,data5, fails on the first comma.\nHow is your data encoded?\n",
"This probably sounds too simple, but really from the looks of things you are looking for a string that contains either [a-zA-Z0-9][\"']+[a-zA-Z0-9], I mean without in depth testing against the data really what you're looking for is a quote or double quote (or any combination) in between letters (you could also add numbers there).\nBased on what you were asking, it really doesn't matter that it's a CSV, it matter's that you have data that doesn't conform. Which I believe just doing a search for a letter, then any combination of one or more \" or ' and another letter. \nNow are you looking to get a \"quantity\" or just a printout of the line that contains it so you know which ones to go back and fix?\nI'm sorry I don't know python regex's but in perl this would look something like this:\n# Look for one or more letter/number at least one ' or \" or more and at least one \n# or more letter/number\nif ($line =~ m/[a-zA-Z0-9]+['\"]+[a-zA-Z0-9]+/ig)\n{\n # Prints the line if the above regex is found\n print $line;\n\n}\n\nJust simply convert that for when you look at a line.\nI'm sorry if I misunderstood the question\nI hope it helps!\n",
"If your goal is to convert the data to XML (or JSON, or YAML), look at this example for a Gelatin syntax that produces the following output:\n<xml>\n <line>\n <column>data1</column>\n <column>data2 </column>\n <column>data3'''</column>\n <column>data4\"\"</column>\n <column/>\n <column/>\n <column>data5</column>\n <column/>\n </line>\n</xml>\n\nNote that Gelatin also has a Python API:\nfrom Gelatin.util import compile, generate_to_file\nsyntax = compile('syntax.gel')\ngenerate_to_file(syntax, 'input.csv', 'output.xml', 'xml')\n\n"
] |
[
12,
7,
4,
2,
1,
0
] |
[] |
[] |
[
"csv",
"python",
"regex"
] |
stackoverflow_0002212933_csv_python_regex.txt
|
Q:
Mock Y of (from X import Y) in doctest (python)
I'm trying to create a doctest with mock of function that resides in a separate module
and that is imported as bellow
from foomodule import foo
def bar():
"""
>>> from minimock import mock
>>> mock('foo', nsdicts=(bar.func_globals,), returns=5)
>>> bar()
Called foo()
10
"""
return foo() * 2
import doctest
doctest.testmod()
foomodule.py:
def foo():
raise ValueError, "Don't call me during testing!"
This fails.
If I change import to import foomodule
and use foomodule.foo everywhere
Then it works.
But is there any solution for mocking function imported the way above?
A:
You've just met one of the many reasons that make it best to never import object from "within" modules -- only modules themselves (possibly from within packages). We've made this rule part of our style guidelines at Google (published here) and I heartily recommend it to every Python programmer.
That being said, what you need to do is to take the foomodule.foo that you've just replaced with a mock and stick it in the current module. I don't recall enough of doctest's internal to confirm whether
>>> import foomodule
>>> foo = foomodule.foo
will suffice for that -- give it a try, and if it doesn't work, do instead
>>> import foomodule
>>> import sys
>>> sys.modules[__name__].foo = foomodule.foo
yeah, it's a mess, but the cause of that mess is that innocent-looking from foomodule import foo -- eschew that, and your life will be simpler and more productive;-).
A:
Finally, found out that this was rather an issue of trunk version of MiniMock.
Old stable one performs as expected.
|
Mock Y of (from X import Y) in doctest (python)
|
I'm trying to create a doctest with mock of function that resides in a separate module
and that is imported as bellow
from foomodule import foo
def bar():
"""
>>> from minimock import mock
>>> mock('foo', nsdicts=(bar.func_globals,), returns=5)
>>> bar()
Called foo()
10
"""
return foo() * 2
import doctest
doctest.testmod()
foomodule.py:
def foo():
raise ValueError, "Don't call me during testing!"
This fails.
If I change import to import foomodule
and use foomodule.foo everywhere
Then it works.
But is there any solution for mocking function imported the way above?
|
[
"You've just met one of the many reasons that make it best to never import object from \"within\" modules -- only modules themselves (possibly from within packages). We've made this rule part of our style guidelines at Google (published here) and I heartily recommend it to every Python programmer.\nThat being said, what you need to do is to take the foomodule.foo that you've just replaced with a mock and stick it in the current module. I don't recall enough of doctest's internal to confirm whether\n >>> import foomodule\n >>> foo = foomodule.foo\n\nwill suffice for that -- give it a try, and if it doesn't work, do instead\n >>> import foomodule\n >>> import sys\n >>> sys.modules[__name__].foo = foomodule.foo\n\nyeah, it's a mess, but the cause of that mess is that innocent-looking from foomodule import foo -- eschew that, and your life will be simpler and more productive;-).\n",
"Finally, found out that this was rather an issue of trunk version of MiniMock.\nOld stable one performs as expected.\n"
] |
[
4,
2
] |
[] |
[] |
[
"doctest",
"mocking",
"python",
"testing"
] |
stackoverflow_0002216828_doctest_mocking_python_testing.txt
|
Q:
Possible to use GCJ to produce library callable from Python?
Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes?
I'm interested in toxilibs for now, but if anybody knows a toy example that would be great !
A:
If you want Java-Python hooks, you'd be far better off using Jython and then calling across the boundary that way.
However, yes, it's possible to call an external library from Java; but you don't need GCJ to do that. Rather, you can just bring up a JVM instance inside your Python runtime and then invoke your method(s) for that.
JNI invocation spec
Basically, you want to create your VM at startup, then invoke your method(s) whenever you want:
// Do this once per session, e.g. an __init__
JNI_CreateJavaVM(&jvm, &env, &vm_args);
// When needed invoke Example.foo(int)
jclass cls =
env->FindClass("Example"); jmethodID
mid = env->GetStaticMethodID(cls,
"foo", "(I)V");
env->CallStaticVoidMethod(cls, mid,100);
You could write some simple C-wrapper code to invoke this for you from ctypes. However, the JavaVM is a structure of a structure with a number of void* pointers, so might ne non-trivial to do it directly.
|
Possible to use GCJ to produce library callable from Python?
|
Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes?
I'm interested in toxilibs for now, but if anybody knows a toy example that would be great !
|
[
"If you want Java-Python hooks, you'd be far better off using Jython and then calling across the boundary that way. \nHowever, yes, it's possible to call an external library from Java; but you don't need GCJ to do that. Rather, you can just bring up a JVM instance inside your Python runtime and then invoke your method(s) for that. \nJNI invocation spec\nBasically, you want to create your VM at startup, then invoke your method(s) whenever you want:\n// Do this once per session, e.g. an __init__ \n\nJNI_CreateJavaVM(&jvm, &env, &vm_args); \n\n// When needed invoke Example.foo(int)\njclass cls =\nenv->FindClass(\"Example\"); jmethodID\nmid = env->GetStaticMethodID(cls,\n\"foo\", \"(I)V\"); \nenv->CallStaticVoidMethod(cls, mid,100);\n\nYou could write some simple C-wrapper code to invoke this for you from ctypes. However, the JavaVM is a structure of a structure with a number of void* pointers, so might ne non-trivial to do it directly.\n"
] |
[
1
] |
[] |
[] |
[
"ctypes",
"gcj",
"java",
"python"
] |
stackoverflow_0002203728_ctypes_gcj_java_python.txt
|
Q:
How to convert ip address to DWORD?
Hey, how can I convert ip address to DWORD using python ?
I searched a while but didn't found anything useful.
Thanks for the helpers!
A:
Don't roll your own solution. Use the socket library.
import socket
socket.inet_pton(socket.AF_INET, "127.0.0.1")
It will throw exceptions when it can't properly parse the address, and writing your own parsers for things is just a recipe for problems down the line.
Doing it this way also makes it easier to transition your code to IPv6. And writing your own address parser for IPv6 would be a really bad idea because IPv6 addresses are complex and have some weird corner cases.
Edit: Apparently, this doesn't work on Windows. I'm not sure how you're supposed to parse IPv6 addresses on Windows, but there is still a library call that can parse IPv4 addresses. It's socket.inet_aton, and you should use it if socket.inet_pton doesn't exist instead of rolling your own solution.
A:
Assuming you have a correct IPv4, you could do this, for example:
import struct
ip = "192.168.2.101"
components = map(int, ip.split("."))
asLittleEndianDword = struct.pack("<I", (components[0] << 24) |
(components[1] << 16) |
(components[2] << 8) |
components[3])
A:
Python doesn't have a DWORD type. If you need it as a 4-byte string use:
struct.pack('bbbb', *(int(x) for x in '127.0.0.1'.split('.')))
|
How to convert ip address to DWORD?
|
Hey, how can I convert ip address to DWORD using python ?
I searched a while but didn't found anything useful.
Thanks for the helpers!
|
[
"Don't roll your own solution. Use the socket library.\nimport socket\nsocket.inet_pton(socket.AF_INET, \"127.0.0.1\")\n\nIt will throw exceptions when it can't properly parse the address, and writing your own parsers for things is just a recipe for problems down the line.\nDoing it this way also makes it easier to transition your code to IPv6. And writing your own address parser for IPv6 would be a really bad idea because IPv6 addresses are complex and have some weird corner cases.\nEdit: Apparently, this doesn't work on Windows. I'm not sure how you're supposed to parse IPv6 addresses on Windows, but there is still a library call that can parse IPv4 addresses. It's socket.inet_aton, and you should use it if socket.inet_pton doesn't exist instead of rolling your own solution.\n",
"Assuming you have a correct IPv4, you could do this, for example:\nimport struct\n\nip = \"192.168.2.101\"\ncomponents = map(int, ip.split(\".\"))\nasLittleEndianDword = struct.pack(\"<I\", (components[0] << 24) |\n (components[1] << 16) |\n (components[2] << 8) |\n components[3])\n\n",
"Python doesn't have a DWORD type. If you need it as a 4-byte string use:\nstruct.pack('bbbb', *(int(x) for x in '127.0.0.1'.split('.')))\n\n"
] |
[
4,
0,
-1
] |
[] |
[] |
[
"dword",
"ip_address",
"python"
] |
stackoverflow_0002217612_dword_ip_address_python.txt
|
Q:
Python 2.6 multiprocessing.Queue compatible with threads?
I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's __init__ method). It seems to generally work but occasionally and unpredictably fails with the following error:
File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small time.sleep(0.01) seems to alleviate the problem.
Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?
Thanks!
-brian
A:
I didn't experiment with multi-processing in 2.6 yet, but I played a lot with pyprocessing (as it was called in 2.5).
I can see that you are looking for a number of processes with each spawning a set of threads respectively.
Since you are using the multiprocessing module, I will suggest use multi process and not multi thread approach, you will hit less problems like deadlocks, etc.
Create a queue object. http://pyprocessing.berlios.de/doc/queue-objects.html
For creating a multi process environment use a pool: http://pyprocessing.berlios.de/doc/pool-objects.html which will manage the worker processes for you. You can then apply asynchronous/synchronous to the workers and can also add a callback for each worker if required. But remember call back is a common code block and it should return immediately (as mentioned in documentation)
Some additional info:
If required create a manager http://pyprocessing.berlios.de/doc/manager-objects.html to manage the the access to the queue object. You will have to make the queue object shared for this. But the advantage is that, once shared and managed you can access this shared queue all over the network by creating proxy objects. This will enable you to call methods of a centralized shared queue object as (apparently) native methods on any network node.
here is a code example from the documentation
It is possible to run a manager server on one machine and have clients use it from other machines (assuming that the firewalls involved allow it).
Running the following commands creates a server for a shared queue which remote clients can use:
>>> from processing.managers import BaseManager, CreatorMethod
>>> import Queue
>>> queue = Queue.Queue()
>>> class QueueManager(BaseManager):
... get_proxy = CreatorMethod(callable=lambda:queue, typeid='get_proxy')
...
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey='none')
>>> m.serve_forever()
One client can access the server as follows:
>>> from processing.managers import BaseManager, CreatorMethod
>>> class QueueManager(BaseManager):
... get_proxy = CreatorMethod(typeid='get_proxy')
...
>>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='none')
>>> queue = m.get_proxy()
>>> queue.put('hello')
If you insist on safe threaded stuff, PEP371 (multiprocessing) references this http://code.google.com/p/python-safethread/
A:
You should pass Queue objects as target's arguments.
Example from multiprocessing's documentation:
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
Queues are thread and process safe.
A:
You may be running into this bug:
http://bugs.python.org/issue4660
|
Python 2.6 multiprocessing.Queue compatible with threads?
|
I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's __init__ method). It seems to generally work but occasionally and unpredictably fails with the following error:
File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small time.sleep(0.01) seems to alleviate the problem.
Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?
Thanks!
-brian
|
[
"I didn't experiment with multi-processing in 2.6 yet, but I played a lot with pyprocessing (as it was called in 2.5).\nI can see that you are looking for a number of processes with each spawning a set of threads respectively.\nSince you are using the multiprocessing module, I will suggest use multi process and not multi thread approach, you will hit less problems like deadlocks, etc.\nCreate a queue object. http://pyprocessing.berlios.de/doc/queue-objects.html\nFor creating a multi process environment use a pool: http://pyprocessing.berlios.de/doc/pool-objects.html which will manage the worker processes for you. You can then apply asynchronous/synchronous to the workers and can also add a callback for each worker if required. But remember call back is a common code block and it should return immediately (as mentioned in documentation)\nSome additional info:\nIf required create a manager http://pyprocessing.berlios.de/doc/manager-objects.html to manage the the access to the queue object. You will have to make the queue object shared for this. But the advantage is that, once shared and managed you can access this shared queue all over the network by creating proxy objects. This will enable you to call methods of a centralized shared queue object as (apparently) native methods on any network node.\nhere is a code example from the documentation\nIt is possible to run a manager server on one machine and have clients use it from other machines (assuming that the firewalls involved allow it).\nRunning the following commands creates a server for a shared queue which remote clients can use:\n>>> from processing.managers import BaseManager, CreatorMethod\n>>> import Queue\n>>> queue = Queue.Queue()\n>>> class QueueManager(BaseManager):\n... get_proxy = CreatorMethod(callable=lambda:queue, typeid='get_proxy')\n...\n>>> m = QueueManager(address=('foo.bar.org', 50000), authkey='none')\n>>> m.serve_forever()\n\nOne client can access the server as follows:\n>>> from processing.managers import BaseManager, CreatorMethod\n>>> class QueueManager(BaseManager):\n... get_proxy = CreatorMethod(typeid='get_proxy')\n...\n>>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='none')\n>>> queue = m.get_proxy()\n>>> queue.put('hello')\n\nIf you insist on safe threaded stuff, PEP371 (multiprocessing) references this http://code.google.com/p/python-safethread/\n",
"You should pass Queue objects as target's arguments.\nExample from multiprocessing's documentation:\nfrom multiprocessing import Process, Queue\n\ndef f(q):\n q.put([42, None, 'hello'])\n\n if __name__ == '__main__':\n q = Queue()\n p = Process(target=f, args=(q,))\n p.start()\n print q.get() # prints \"[42, None, 'hello']\"\n p.join()\n\n\nQueues are thread and process safe.\n\n",
"You may be running into this bug:\nhttp://bugs.python.org/issue4660\n"
] |
[
4,
2,
1
] |
[
"Thanks for the quick response. I am passing the multiprocessing.Queue instances as arguments to each Process as you illustrate. The failure seems to occur in the threads. I am creating them by subclassing threading.Thread and passing the queue to the 'init' method of each thread instance. This seems to be the accepted way to pass in Queues to thread subclasses. My only thought it that multiprocessing Queues may not be compatible with threads (although they are supposedly thread-safe).\n"
] |
[
-1
] |
[
"multiprocessing",
"python",
"python_2.6"
] |
stackoverflow_0000342556_multiprocessing_python_python_2.6.txt
|
Q:
Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy)
I have a conjunctive probability mass function array, with shape, for example (1,2,3,4,5,6) and I want to calculate the probability table, conditional to a value for some of the dimensions (export the cpts), for decision-making purposes.
The code I came up with at the moment is the following (the input is the dictionary "vdict" of the form {'variable_1': value_1, 'variable_2': value_2 ... } )
for i in vdict:
dim = self.invardict.index(i) # The index of the dimension that our Variable resides in
val = self.valdict[i][vdict[i]] # The value we want it to be
d = d.swapaxes(0, dim)
**d = array([d[val]])**
d = d.swapaxes(0, dim)
...
So, what I currently do is:
I translate the variables to the corresponding dimension in the cpt.
I swap the zero-th axis with the axis I found before.
I replace whole 0-axis with just the desired value.
I put the dimension back to its original axis.
Now, the problem is, in order to do step 2, I have (a.) to calculate a subarray
and (b.) to put it in a list and translate it again to array so I'll have my new array.
Thing is, stuff in bold means that I create new objects, instead of using just the references to the old ones and this, if d is very large (which happens to me) and methods that use d are called many times (which, again, happens to me) the whole result is very slow.
So, has anyone come up with an idea that will subtitude this little piece of code and will run faster? Maybe something that will allow me to calculate the conditionals in place.
Note: I have to maintain original axis order (or at least be sure on how to update the variable to dimensions dictionaries when an axis is removed). I'd like not to resort in custom dtypes.
A:
Ok, found the answer myself after playing a little with numpy's in-place array manipulations.
Changed the last 3 lines in the loop to:
d = conditionalize(d, dim, val)
where conditionalize is defined as:
def conditionalize(arr, dim, val):
arr = arr.swapaxes(dim, 0)
shape = arr.shape[1:] # shape of the sub-array when we omit the desired dimension.
count = array(shape).prod() # count of elements omitted the desired dimension.
arr = arr.reshape(array(arr.shape).prod()) # flatten the array in-place.
arr = arr[val*count:(val+1)*count] # take the needed elements
arr = arr.reshape((1,)+shape) # the desired sub-array shape.
arr = arr. swapaxes(0, dim) # fix dimensions
return arr
That made my program's execution time reduce from 15 minutes to 6 seconds. Huge gain.
I hope this helps someone who comes across the same problem.
|
Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy)
|
I have a conjunctive probability mass function array, with shape, for example (1,2,3,4,5,6) and I want to calculate the probability table, conditional to a value for some of the dimensions (export the cpts), for decision-making purposes.
The code I came up with at the moment is the following (the input is the dictionary "vdict" of the form {'variable_1': value_1, 'variable_2': value_2 ... } )
for i in vdict:
dim = self.invardict.index(i) # The index of the dimension that our Variable resides in
val = self.valdict[i][vdict[i]] # The value we want it to be
d = d.swapaxes(0, dim)
**d = array([d[val]])**
d = d.swapaxes(0, dim)
...
So, what I currently do is:
I translate the variables to the corresponding dimension in the cpt.
I swap the zero-th axis with the axis I found before.
I replace whole 0-axis with just the desired value.
I put the dimension back to its original axis.
Now, the problem is, in order to do step 2, I have (a.) to calculate a subarray
and (b.) to put it in a list and translate it again to array so I'll have my new array.
Thing is, stuff in bold means that I create new objects, instead of using just the references to the old ones and this, if d is very large (which happens to me) and methods that use d are called many times (which, again, happens to me) the whole result is very slow.
So, has anyone come up with an idea that will subtitude this little piece of code and will run faster? Maybe something that will allow me to calculate the conditionals in place.
Note: I have to maintain original axis order (or at least be sure on how to update the variable to dimensions dictionaries when an axis is removed). I'd like not to resort in custom dtypes.
|
[
"Ok, found the answer myself after playing a little with numpy's in-place array manipulations.\nChanged the last 3 lines in the loop to:\n d = conditionalize(d, dim, val)\n\nwhere conditionalize is defined as:\n def conditionalize(arr, dim, val):\n arr = arr.swapaxes(dim, 0)\n shape = arr.shape[1:] # shape of the sub-array when we omit the desired dimension.\n count = array(shape).prod() # count of elements omitted the desired dimension.\n arr = arr.reshape(array(arr.shape).prod()) # flatten the array in-place.\n arr = arr[val*count:(val+1)*count] # take the needed elements\n arr = arr.reshape((1,)+shape) # the desired sub-array shape.\n arr = arr. swapaxes(0, dim) # fix dimensions\n\n return arr\n\nThat made my program's execution time reduce from 15 minutes to 6 seconds. Huge gain.\nI hope this helps someone who comes across the same problem.\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"numpy",
"probability",
"python",
"recarray"
] |
stackoverflow_0002199940_arrays_numpy_probability_python_recarray.txt
|
Q:
Sort by field in ForeignKey model
I have created a Django model called Person, which has got a 'user' ForeignKey to django.contrib.auth.models.User
How can I set the ordering on class Person to self.user.first_name, self.user.last_name?
A:
class Meta:
ordering = ['user__first_name', 'user__last_name']
Should do the trick iirc
|
Sort by field in ForeignKey model
|
I have created a Django model called Person, which has got a 'user' ForeignKey to django.contrib.auth.models.User
How can I set the ordering on class Person to self.user.first_name, self.user.last_name?
|
[
"class Meta:\n ordering = ['user__first_name', 'user__last_name']\n\nShould do the trick iirc\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002218121_django_python.txt
|
Q:
Override Python's 'in' operator?
If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g.
class MyClass(object):
...
m = MyClass()
if 54 in m:
...
A:
MyClass.__contains__(self, item)
A:
A more complete answer is:
class MyClass(object):
def __init__(self):
self.numbers = [1,2,3,4,54]
def __contains__(self, key):
return key in self.numbers
Here you would get True when asking if 54 was in m:
>>> m = MyClass()
>>> 54 in m
True
See documentation on overloading __contains__.
|
Override Python's 'in' operator?
|
If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g.
class MyClass(object):
...
m = MyClass()
if 54 in m:
...
|
[
"MyClass.__contains__(self, item)\n",
"A more complete answer is:\nclass MyClass(object):\n\n def __init__(self):\n self.numbers = [1,2,3,4,54]\n\n def __contains__(self, key):\n return key in self.numbers\n\nHere you would get True when asking if 54 was in m:\n>>> m = MyClass()\n>>> 54 in m\nTrue \n\nSee documentation on overloading __contains__.\n"
] |
[
325,
263
] |
[] |
[] |
[
"in_operator",
"operator_overloading",
"operators",
"python"
] |
stackoverflow_0002217001_in_operator_operator_overloading_operators_python.txt
|
Q:
convention to represent the exit status and actual result in XMLRPC
in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process. when it comes to xmlrpc, no INOUT/OUT parameter, is there any best practice/conventions to represent the exit status and actual result?
the context is i am trying to write an agent/daemon (python SimpleXMLRPCServer) running on the Server, and want to design the "protocol" to interact with it.
any advice is appreciated.
EDIT:
per S.Lott's comment, make the problem more clear.
it is more about os convention rather
than C convention. I agree with that.
the job of the agent is more or less run some cmd on the server, inherently with an exit code/result idiom
.
A:
One simple way to implement this in Python is with a tuple. Have your function return a tuple of: (status, result) where the status can be numeric or a string, and the result can be any Python data structure you fancy.
Here's an example, adapted from the module documentation. Server code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
def myfunction(x, y):
status = 1
result = [5, 6, [4, 5]]
return (status, result)
server.register_function(myfunction)
# Run the server's main loop
server.serve_forever()
Client code:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.myfunction(2, 4)
The server function returns a tuple
A:
"in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process"
Consider an exit status to be a hack. It's not a C-ism, it's a Linux-ism. C functions return exactly one value. C doesn't have exceptions, so there are several ways to indicate failure, all pretty bad.
Exception handling is what's needed. Python and Java have this, and they don't need exit status.
OS's however, still depend on exit status because shell scripting is still very primitive and some languages (like C) can't produce exceptions.
Consider in/out variables also to be a hack. This is a terrible hack because the function has multiple side-effects in addition to returning a value.
Both of these "features" aren't really the best design patterns to follow.
Ideally, a function is "idempotent" -- no matter how many times you call it, you get the same results. In/Out variables break idempotency in obscure, hard-to-debug ways.
You don't really need either of these features, that's why you don't see many best practices for implementing them.
The best practice is to return a value or raise an exception. If you need to return multiple values you return a tuple. If things didn't work, you don't return an exit status, you raise an exception.
Update. Since the remote process is basically RSH to run a remote command, you should do what remctl does.
You need to mimic: http://linux.die.net/man/1/remctl precisely. You have to write a Python client and server. The server returns a message with a status code (and any other summary, like run-time). The client exits with that same status code.
|
convention to represent the exit status and actual result in XMLRPC
|
in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process. when it comes to xmlrpc, no INOUT/OUT parameter, is there any best practice/conventions to represent the exit status and actual result?
the context is i am trying to write an agent/daemon (python SimpleXMLRPCServer) running on the Server, and want to design the "protocol" to interact with it.
any advice is appreciated.
EDIT:
per S.Lott's comment, make the problem more clear.
it is more about os convention rather
than C convention. I agree with that.
the job of the agent is more or less run some cmd on the server, inherently with an exit code/result idiom
.
|
[
"One simple way to implement this in Python is with a tuple. Have your function return a tuple of: (status, result) where the status can be numeric or a string, and the result can be any Python data structure you fancy.\nHere's an example, adapted from the module documentation. Server code:\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nfrom SimpleXMLRPCServer import SimpleXMLRPCRequestHandler\n\n# Restrict to a particular path.\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2',)\n\n# Create server\nserver = SimpleXMLRPCServer((\"localhost\", 8000),\n requestHandler=RequestHandler)\n\ndef myfunction(x, y):\n status = 1\n result = [5, 6, [4, 5]]\n return (status, result)\nserver.register_function(myfunction)\n\n# Run the server's main loop\nserver.serve_forever()\n\nClient code:\nimport xmlrpclib\n\ns = xmlrpclib.ServerProxy('http://localhost:8000')\nprint s.myfunction(2, 4)\n\nThe server function returns a tuple \n",
"\"in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process\"\n\nConsider an exit status to be a hack. It's not a C-ism, it's a Linux-ism. C functions return exactly one value. C doesn't have exceptions, so there are several ways to indicate failure, all pretty bad. \nException handling is what's needed. Python and Java have this, and they don't need exit status. \nOS's however, still depend on exit status because shell scripting is still very primitive and some languages (like C) can't produce exceptions.\nConsider in/out variables also to be a hack. This is a terrible hack because the function has multiple side-effects in addition to returning a value.\n\nBoth of these \"features\" aren't really the best design patterns to follow.\nIdeally, a function is \"idempotent\" -- no matter how many times you call it, you get the same results. In/Out variables break idempotency in obscure, hard-to-debug ways.\nYou don't really need either of these features, that's why you don't see many best practices for implementing them.\nThe best practice is to return a value or raise an exception. If you need to return multiple values you return a tuple. If things didn't work, you don't return an exit status, you raise an exception.\n\nUpdate. Since the remote process is basically RSH to run a remote command, you should do what remctl does. \nYou need to mimic: http://linux.die.net/man/1/remctl precisely. You have to write a Python client and server. The server returns a message with a status code (and any other summary, like run-time). The client exits with that same status code.\n"
] |
[
1,
1
] |
[] |
[] |
[
"exit_code",
"function",
"python",
"xml_rpc"
] |
stackoverflow_0002217072_exit_code_function_python_xml_rpc.txt
|
Q:
python equivalent of '#define func() ' or how to comment out a function call in python
my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.)
for example:
import logging
logging.root.setLevel(logging.DEBUG)
logging.debug('hello')
j = 0
for i in range(10):
j += i
logging.debug('i %d j %d' % (i,j))
print(j)
logging.debug('bye')
i want to #define these resource consuming functions out of the code. something like the c equivalent
#define logging.debug(val)
yes, i know the logging module logging level mechanism can be used to mask out loggings below set log level. but, im asking for a general way to have the python interpreter skip functions (that take time to run even if they dont do much)
one idea is to redefine the functions i want to comment out into empty functions:
def lazy(*args): pass
logging.debug = lazy
the above idea still calls a function, and may create a myriad of other problems
A:
Python does not have a preprocessor, although you could run your python source through an external preprocessor to get the same effect - e.g. sed "/logging.debug/d" will strip out all the debug logging commands. This is not very elegant though - you will end up needing some sort of build system to run all your modules through the preprocessor and perhaps create a new directory tree of the processed .py files before running the main script.
Alternatively if you put all your debug statements in an if __debug__: block they will get optimised out when python is run with the -O (optimise) flag.
As an aside, I checked the code with the dis module to ensure that it did get optimised away. I discovered that both
if __debug__: doStuff()
and
if 0: doStuff()
are optimised, but
if False: doStuff()
is not. This is because False is a regular Python object, and you can in fact do this:
>>> False = True
>>> if False: print "Illogical, captain"
Illogical, captain
Which seems to me a flaw in the language - hopefully it is fixed in Python 3.
Edit:
This is fixed in Python 3: Assigning to True or False now gives a SyntaxError.
Since True and False are constants in Python 3, it means that if False: doStuff() is now optimised:
>>> def f():
... if False: print( "illogical")
...
>>> dis.dis(f)
2 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
A:
Although I think the question is perfectly clear and valid (notwithstanding the many responses that suggest otherwise), the short answer is "there's no support in Python for this".
The only potential solution other than the preprocessor suggestion would be to use some bytecode hacking. I won't even begin to imagine how this should work in terms of the high-level API, but at a low level you could imagine examining code objects for particular sequences of instructions and re-writing them to eliminate them.
For example, look at the following two functions:
>>> def func():
... if debug: # analogous to if __debug__:
... foo
>>> dis.dis(func)
2 0 LOAD_GLOBAL 0 (debug)
3 JUMP_IF_FALSE 8 (to 14)
6 POP_TOP
3 7 LOAD_GLOBAL 1 (foo)
10 POP_TOP
11 JUMP_FORWARD 1 (to 15)
>> 14 POP_TOP
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
Here you could scan for the LOAD_GLOBAL of debug, and eliminate it and everything up to the JUMP_IF_FALSE target.
This one is the more traditional C-style debug() function that gets nicely obliterated by a preprocessor:
>>> def func2():
... debug('bar', baz)
>>> dis.dis(func2)
2 0 LOAD_GLOBAL 0 (debug)
3 LOAD_CONST 1 ('bar')
6 LOAD_GLOBAL 1 (baz)
9 CALL_FUNCTION 2
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
Here you would look for LOAD_GLOBAL of debug and wipe everything up to the corresponding CALL_FUNCTION.
Of course, both of those descriptions of what you would do are far simpler than what you'd really need for all but the most simplistic patterns of use, but I think it would be feasible. Would make a cute project, if nobody's already done it.
A:
Well, you can always implement your own simple preprocessor that does the trick. Or, even better, you can use an already existing one. Say http://code.google.com/p/preprocess/
A:
Use a module scoped variable?
from config_module import debug_flag
and use this "variable" to gate access to the logging function(s). You would build yourself a logging module that uses the debug_flag to gate the logging functionality.
A:
I think that completely aboiding the calling on a function is not posible, as Python works in a different way that C. The #define takes place in the pre-compiler, before the code is compiled. In Python, there's no such thing.
If you want to completely remove the calling to debug in a work environment, I think the only way if to actually change the code before execution. With a script previous to execution you could comment/uncomment the debug lines.
Something like this:
File logging.py
#Main module
def log():
print 'logging'
def main():
log()
print 'Hello'
log()
File call_log.py
import re
#To log or not to log, that's the question
log = True
#Change the loging
with open('logging.py') as f:
new_data = []
for line in f:
if not log and re.match(r'\s*log.*', line):
#Comment
line = '#' + line
if log and re.match(r'#\s*log.*', line):
#Uncomment
line = line[1:]
new_data.append(line)
#Save file with adequate log level
with open('logging.py', 'w') as f:
f.write(''.join(new_data))
#Call the module
import logging
logging.main()
Of course, it has its problems, specially if there are a lot of modules and are complex, but could be usable if you need to absolutely avoid the calling to a function.
A:
Before you do this, have you profiled to verify that the logging is actually taking a substantial amount of time? You may find that you spend more time trying to remove the calls than you save.
Next, have you tried something like Psyco? If you've got things set up so logging is disabled, then Psyco may be able to optimise away most of the overhead of calling the logging function, noticing that it will always return without action.
If you still find logging taking an appreciable amount of time, you might then want to look at overriding the logging function inside critical loops, possibly by binding a local variable to either the logging function or a dummy function as appropriate (or by checking for None before calling it).
A:
define a function that does nothing, ie
def nuzzing(*args, **kwargs): pass
Then just overload all the functions you want to get rid of with your function, ala
logging.debug = nuzzing
A:
I like the 'if __debug_' solution except that putting it in front of every call is a bit distracting and ugly. I had this same problem and overcame it by writing a script which automatically parses your source files and replaces logging statements with pass statements (and commented out copies of the logging statements). It can also undo this conversion.
I use it when I deploy new code to a production environment when there are lots of logging statements which I don't need in a production setting and they are affecting performance.
You can find the script here: http://dound.com/2010/02/python-logging-performance/
|
python equivalent of '#define func() ' or how to comment out a function call in python
|
my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.)
for example:
import logging
logging.root.setLevel(logging.DEBUG)
logging.debug('hello')
j = 0
for i in range(10):
j += i
logging.debug('i %d j %d' % (i,j))
print(j)
logging.debug('bye')
i want to #define these resource consuming functions out of the code. something like the c equivalent
#define logging.debug(val)
yes, i know the logging module logging level mechanism can be used to mask out loggings below set log level. but, im asking for a general way to have the python interpreter skip functions (that take time to run even if they dont do much)
one idea is to redefine the functions i want to comment out into empty functions:
def lazy(*args): pass
logging.debug = lazy
the above idea still calls a function, and may create a myriad of other problems
|
[
"Python does not have a preprocessor, although you could run your python source through an external preprocessor to get the same effect - e.g. sed \"/logging.debug/d\" will strip out all the debug logging commands. This is not very elegant though - you will end up needing some sort of build system to run all your modules through the preprocessor and perhaps create a new directory tree of the processed .py files before running the main script.\nAlternatively if you put all your debug statements in an if __debug__: block they will get optimised out when python is run with the -O (optimise) flag.\nAs an aside, I checked the code with the dis module to ensure that it did get optimised away. I discovered that both\nif __debug__: doStuff()\n\nand\nif 0: doStuff()\n\nare optimised, but \nif False: doStuff()\n\nis not. This is because False is a regular Python object, and you can in fact do this:\n>>> False = True\n>>> if False: print \"Illogical, captain\"\nIllogical, captain\n\nWhich seems to me a flaw in the language - hopefully it is fixed in Python 3.\nEdit:\nThis is fixed in Python 3: Assigning to True or False now gives a SyntaxError.\nSince True and False are constants in Python 3, it means that if False: doStuff() is now optimised:\n>>> def f():\n... if False: print( \"illogical\")\n... \n>>> dis.dis(f)\n 2 0 LOAD_CONST 0 (None) \n 3 RETURN_VALUE \n\n",
"Although I think the question is perfectly clear and valid (notwithstanding the many responses that suggest otherwise), the short answer is \"there's no support in Python for this\".\nThe only potential solution other than the preprocessor suggestion would be to use some bytecode hacking. I won't even begin to imagine how this should work in terms of the high-level API, but at a low level you could imagine examining code objects for particular sequences of instructions and re-writing them to eliminate them. \nFor example, look at the following two functions:\n>>> def func():\n... if debug: # analogous to if __debug__:\n... foo\n>>> dis.dis(func)\n 2 0 LOAD_GLOBAL 0 (debug)\n 3 JUMP_IF_FALSE 8 (to 14)\n 6 POP_TOP\n\n 3 7 LOAD_GLOBAL 1 (foo)\n 10 POP_TOP\n 11 JUMP_FORWARD 1 (to 15)\n >> 14 POP_TOP\n >> 15 LOAD_CONST 0 (None)\n 18 RETURN_VALUE\n\nHere you could scan for the LOAD_GLOBAL of debug, and eliminate it and everything up to the JUMP_IF_FALSE target.\nThis one is the more traditional C-style debug() function that gets nicely obliterated by a preprocessor:\n>>> def func2():\n... debug('bar', baz)\n>>> dis.dis(func2)\n 2 0 LOAD_GLOBAL 0 (debug)\n 3 LOAD_CONST 1 ('bar')\n 6 LOAD_GLOBAL 1 (baz)\n 9 CALL_FUNCTION 2\n 12 POP_TOP\n 13 LOAD_CONST 0 (None)\n 16 RETURN_VALUE\n\nHere you would look for LOAD_GLOBAL of debug and wipe everything up to the corresponding CALL_FUNCTION.\nOf course, both of those descriptions of what you would do are far simpler than what you'd really need for all but the most simplistic patterns of use, but I think it would be feasible. Would make a cute project, if nobody's already done it.\n",
"Well, you can always implement your own simple preprocessor that does the trick. Or, even better, you can use an already existing one. Say http://code.google.com/p/preprocess/\n",
"Use a module scoped variable?\nfrom config_module import debug_flag\nand use this \"variable\" to gate access to the logging function(s). You would build yourself a logging module that uses the debug_flag to gate the logging functionality.\n",
"I think that completely aboiding the calling on a function is not posible, as Python works in a different way that C. The #define takes place in the pre-compiler, before the code is compiled. In Python, there's no such thing.\nIf you want to completely remove the calling to debug in a work environment, I think the only way if to actually change the code before execution. With a script previous to execution you could comment/uncomment the debug lines. \nSomething like this: \nFile logging.py\n#Main module\ndef log():\n print 'logging'\n\ndef main():\n log()\n print 'Hello'\n log()\n\nFile call_log.py\nimport re\n#To log or not to log, that's the question\nlog = True\n\n#Change the loging\nwith open('logging.py') as f:\n new_data = []\n for line in f:\n if not log and re.match(r'\\s*log.*', line):\n #Comment\n line = '#' + line\n if log and re.match(r'#\\s*log.*', line):\n #Uncomment\n line = line[1:]\n new_data.append(line)\n\n#Save file with adequate log level\nwith open('logging.py', 'w') as f:\n f.write(''.join(new_data))\n\n\n#Call the module\nimport logging\nlogging.main()\n\nOf course, it has its problems, specially if there are a lot of modules and are complex, but could be usable if you need to absolutely avoid the calling to a function.\n",
"Before you do this, have you profiled to verify that the logging is actually taking a substantial amount of time? You may find that you spend more time trying to remove the calls than you save.\nNext, have you tried something like Psyco? If you've got things set up so logging is disabled, then Psyco may be able to optimise away most of the overhead of calling the logging function, noticing that it will always return without action.\nIf you still find logging taking an appreciable amount of time, you might then want to look at overriding the logging function inside critical loops, possibly by binding a local variable to either the logging function or a dummy function as appropriate (or by checking for None before calling it).\n",
"define a function that does nothing, ie\ndef nuzzing(*args, **kwargs): pass\n\nThen just overload all the functions you want to get rid of with your function, ala\nlogging.debug = nuzzing\n\n",
"I like the 'if __debug_' solution except that putting it in front of every call is a bit distracting and ugly. I had this same problem and overcame it by writing a script which automatically parses your source files and replaces logging statements with pass statements (and commented out copies of the logging statements). It can also undo this conversion.\nI use it when I deploy new code to a production environment when there are lots of logging statements which I don't need in a production setting and they are affecting performance.\nYou can find the script here: http://dound.com/2010/02/python-logging-performance/\n"
] |
[
17,
2,
1,
0,
0,
0,
0,
0
] |
[
"You can't skip function calls. You could redefine these as empty though, e.g. by creating another logging object that provides the same interface, but with empty functions.\nBut by far the cleanest approach is to ignore the low priority log messages (as you suggested):\nlogging.root.setLevel(logging.CRITICAL)\n\n"
] |
[
-1
] |
[
"comments",
"preprocessor",
"python"
] |
stackoverflow_0002006190_comments_preprocessor_python.txt
|
Q:
Profiling of Python threads
I am trying to figure out how to measure the performance of several python threads in my application. I currently have several tasks that are executing on different threads based on user input and I would like to measure the execution time, maybe even memory consumption of each of the threads. I have tried to use cProfile (on each instantiation of the thread, then I would write the data to a file and then aggregate all results) with limited success. Also, I have an added problem of having some blocking IO which is skewing my results. Is there anyway to effectively profile my application?
A:
There are a few different ways to tackle this problem. cProfile is great and comes with Python, however many people see multi-threaded profiling as an issue. One way of getting around this is by running separate instances of cProfile for each thread and then combining the results using Stats.add.
Should that not be as useful as you'd hoped, another alternative could be to use Yappi, which I've had success using for a few special multi-threaded cases. It's got great documentation so you shouldn't have too much trouble setting it up.
For memory specific profiling, check out Heapy. But be warned, it may create some of the largest log files you've ever seen if your code is bad!
|
Profiling of Python threads
|
I am trying to figure out how to measure the performance of several python threads in my application. I currently have several tasks that are executing on different threads based on user input and I would like to measure the execution time, maybe even memory consumption of each of the threads. I have tried to use cProfile (on each instantiation of the thread, then I would write the data to a file and then aggregate all results) with limited success. Also, I have an added problem of having some blocking IO which is skewing my results. Is there anyway to effectively profile my application?
|
[
"There are a few different ways to tackle this problem. cProfile is great and comes with Python, however many people see multi-threaded profiling as an issue. One way of getting around this is by running separate instances of cProfile for each thread and then combining the results using Stats.add.\nShould that not be as useful as you'd hoped, another alternative could be to use Yappi, which I've had success using for a few special multi-threaded cases. It's got great documentation so you shouldn't have too much trouble setting it up.\nFor memory specific profiling, check out Heapy. But be warned, it may create some of the largest log files you've ever seen if your code is bad!\n"
] |
[
4
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002218330_multithreading_python.txt
|
Q:
Unable to access ID property from a datastore entity
Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) :
class Question(db.Model):
text = db.StringProperty()
answers = db.StringListProperty()
user = db.UserProperty()
datetime = db.DateTimeProperty()
I can access text, answers, user, datetime and key properties just fine. However, I can't access the ID property.
For example, after fetching all entities (using Question.all()) :
# OK Within a template, this will return a string :
{{ question.text }}
# OK, this will return the entity key :
{{ question.key }}
# KO this will return nothing :
{{ question.id }}
Any ideas ? Thanks !
A:
According to the documentation, there is no id() instance method defined for Model subclasses.
Try {{ question.key }} instead.
Also note that the key is not created until the entity is saved to the datastore.
Edit: more info based on OP's edit:
Since we're really after the numeric ID, we could do something like this in our template:
{{ question.key.id }}
Another note: you should never expect numeric IDs to increase in value corresponding with the order of entity creation. In practice, this is usually—but not always—the case.
A:
I just found a possible (inelegant, IMO) solution. After querying and fetching entities, loop through all of them and manually add the id parameter :
query = Question.all()
questions = query.fetch(10)
# Add ID property :
for question in questions:
question.id = str(question.key().id())
I don't think it's efficient CPU wise, but it works as a quick/dirty fix.
|
Unable to access ID property from a datastore entity
|
Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) :
class Question(db.Model):
text = db.StringProperty()
answers = db.StringListProperty()
user = db.UserProperty()
datetime = db.DateTimeProperty()
I can access text, answers, user, datetime and key properties just fine. However, I can't access the ID property.
For example, after fetching all entities (using Question.all()) :
# OK Within a template, this will return a string :
{{ question.text }}
# OK, this will return the entity key :
{{ question.key }}
# KO this will return nothing :
{{ question.id }}
Any ideas ? Thanks !
|
[
"According to the documentation, there is no id() instance method defined for Model subclasses.\nTry {{ question.key }} instead.\nAlso note that the key is not created until the entity is saved to the datastore.\n\nEdit: more info based on OP's edit:\nSince we're really after the numeric ID, we could do something like this in our template:\n{{ question.key.id }}\nAnother note: you should never expect numeric IDs to increase in value corresponding with the order of entity creation. In practice, this is usually—but not always—the case.\n",
"I just found a possible (inelegant, IMO) solution. After querying and fetching entities, loop through all of them and manually add the id parameter :\nquery = Question.all()\nquestions = query.fetch(10)\n\n# Add ID property :\nfor question in questions:\n question.id = str(question.key().id())\n\nI don't think it's efficient CPU wise, but it works as a quick/dirty fix.\n"
] |
[
11,
5
] |
[] |
[] |
[
"entity",
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002218693_entity_google_app_engine_google_cloud_datastore_python.txt
|
Q:
time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff!
How does time.localtime() work exactly? I can call up the "array" (tupple, I think it is called - because it is immutable?) and reference/index components of it. For example:
>>> time.localtime()[0]
2010
But if I do:
print time.localtime()
time.struct_time(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46, tm_sec=58, tm_wday=6, tm_yday=38, tm_isdst=0)
First: How does time.localtime() know to return time.struct_time()?
Second: If I type print time.struct_time() it wants additional values to be passed to it (thus not giving me the same values it returned from time.localtime()) - how do I know what those values could possibly be? I checked the python documentation and I couldn't make 'heads nor tails' of it. Really just looking for an example here...
Third: When I index the tupple/array for time.localtime() it returns the proper associated value, "2010" for example, rather than "tm_year=2010" - how does it know to do this (generally speaking not asking for a lot here).
Forth: If I wanted to "call" tm_year from time.localtime() how can I do this? What I am doing (and don't 'feel' right about) is the following:
tm_year = str(time.localtime()[0])
tm_mon = str(time.localtime()[1])
tm_mday = str(time.localtime()[2])
tm_hour = str(time.localtime()[3])
tm_min = str(time.localtime()[4])
NOTE: I am saving them as strings for other reasons not explained in this question, just wanted to point out that I am creating my own variables (named exactly the same as they are in the tupple) and then just referencing the index value associated with the value I want
Is there a way to to just call time.localtime(tm_year) (I know that doesn't work as is, but just brainstorming...)
Thanks in advance... (and I have read "http://docs.python.org/library/time.html" but I am sure I missed some important information... any advice?)
-J
A:
time.localtime()[0] calls __gettiem__() on the time.struct_time instance. This is how it gets this list/tuple like behaviour from. Here is a really simple example
>>> class MyTime(object):
... def __init__(self, year, month, mday, hour, minute):
... self.data = year, month, mday, hour, minute
... def __getitem__(self, idx):
... return self.data[idx]
... def __str__(self):
... return "MyTime(tm_year=%s, tm_mon=%s, tm_mday=%s, tm_hour=%s, tm_min=%s)"%self.data
...
>>> x=MyTime(2010,2,7,14,46)
>>> x[0]
2010
>>> x[1]
2
>>> print x
MyTime(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46)
time.struct_time is a class. time.localtime() returns an instance of the class, which explains the difference when you try to print them
You can load up your 5 variables like this
>>> tm_year,tm_mon,tm_mday,tm_hour,tm_min=map(str,time.localtime()[:5])
A:
You can make your own "named tuples", i.e., subclasses of tuple with items accessible by either indexing or as attributes, with collections.namedtuple (in Python 2.6 or better). There's nothing "magical" about named tuples in general, nor specifically about the one whose instances are returned by various functions in the time module (which is slightly different, because it predates collections.namedtuple).
So, for example, time.localtime().tm_year will give you the year, as you want (you can pass it to str and/or assign it to anything you want, of course).
But since you can also access the result as a tuple, you have alternatives such as slicing, tuple-unpacking, and the like.
When you call time.struct_time, you're building an arbitrary instance of it -- and you need to pass it one argument, a sequence with exactly nine items. (For a normal named tuple that's similar to it, you'd pass nine arguments instead -- of course it's easy to pass nine arguments if you have a nine-sequence foo, i.e., you call bar(*foo);-).
By the way, you focus on localtime, but that's not the only function returning a struct_time, of course -- gmtime and strptime return instances of the same type!-)
A:
The print statement tries to convert all its arguments to a string representation. And the __repr__ or __str__ method of a struct_time object yields the result
time.struct_time(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46, tm_sec=58, tm_wday=6, tm_yday=38, tm_isdst=0)
See the Python docs
Don't use it. It's an internal data structure
When you use the index-operator [] it behaves like a tuple
A:
Nascent Notes,
The function time.localtime() accepts an optional argument of Epoch seconds, without the argument it takes the current time (probably from time.time()). The function then calculates what time this corresponds to in your timezone (i.e. your local time) and then returns the results in object of type time.struct_time.
I'm not sure why you want to create a struct_time object, as you're asking about the what the arguments should be, perhaps you're heading in the wrong direction.
It seems that you're interested in manipulating representations of time. I think that the datetime module may be more suitable for your purposes.
|
time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff!
|
How does time.localtime() work exactly? I can call up the "array" (tupple, I think it is called - because it is immutable?) and reference/index components of it. For example:
>>> time.localtime()[0]
2010
But if I do:
print time.localtime()
time.struct_time(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46, tm_sec=58, tm_wday=6, tm_yday=38, tm_isdst=0)
First: How does time.localtime() know to return time.struct_time()?
Second: If I type print time.struct_time() it wants additional values to be passed to it (thus not giving me the same values it returned from time.localtime()) - how do I know what those values could possibly be? I checked the python documentation and I couldn't make 'heads nor tails' of it. Really just looking for an example here...
Third: When I index the tupple/array for time.localtime() it returns the proper associated value, "2010" for example, rather than "tm_year=2010" - how does it know to do this (generally speaking not asking for a lot here).
Forth: If I wanted to "call" tm_year from time.localtime() how can I do this? What I am doing (and don't 'feel' right about) is the following:
tm_year = str(time.localtime()[0])
tm_mon = str(time.localtime()[1])
tm_mday = str(time.localtime()[2])
tm_hour = str(time.localtime()[3])
tm_min = str(time.localtime()[4])
NOTE: I am saving them as strings for other reasons not explained in this question, just wanted to point out that I am creating my own variables (named exactly the same as they are in the tupple) and then just referencing the index value associated with the value I want
Is there a way to to just call time.localtime(tm_year) (I know that doesn't work as is, but just brainstorming...)
Thanks in advance... (and I have read "http://docs.python.org/library/time.html" but I am sure I missed some important information... any advice?)
-J
|
[
"time.localtime()[0] calls __gettiem__() on the time.struct_time instance. This is how it gets this list/tuple like behaviour from. Here is a really simple example\n>>> class MyTime(object):\n... def __init__(self, year, month, mday, hour, minute):\n... self.data = year, month, mday, hour, minute\n... def __getitem__(self, idx):\n... return self.data[idx]\n... def __str__(self):\n... return \"MyTime(tm_year=%s, tm_mon=%s, tm_mday=%s, tm_hour=%s, tm_min=%s)\"%self.data\n... \n>>> x=MyTime(2010,2,7,14,46)\n>>> x[0]\n2010\n>>> x[1]\n2\n>>> print x\nMyTime(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46)\n\ntime.struct_time is a class. time.localtime() returns an instance of the class, which explains the difference when you try to print them\nYou can load up your 5 variables like this\n>>> tm_year,tm_mon,tm_mday,tm_hour,tm_min=map(str,time.localtime()[:5])\n\n",
"You can make your own \"named tuples\", i.e., subclasses of tuple with items accessible by either indexing or as attributes, with collections.namedtuple (in Python 2.6 or better). There's nothing \"magical\" about named tuples in general, nor specifically about the one whose instances are returned by various functions in the time module (which is slightly different, because it predates collections.namedtuple).\nSo, for example, time.localtime().tm_year will give you the year, as you want (you can pass it to str and/or assign it to anything you want, of course).\nBut since you can also access the result as a tuple, you have alternatives such as slicing, tuple-unpacking, and the like.\nWhen you call time.struct_time, you're building an arbitrary instance of it -- and you need to pass it one argument, a sequence with exactly nine items. (For a normal named tuple that's similar to it, you'd pass nine arguments instead -- of course it's easy to pass nine arguments if you have a nine-sequence foo, i.e., you call bar(*foo);-).\nBy the way, you focus on localtime, but that's not the only function returning a struct_time, of course -- gmtime and strptime return instances of the same type!-)\n",
"\nThe print statement tries to convert all its arguments to a string representation. And the __repr__ or __str__ method of a struct_time object yields the result\ntime.struct_time(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46, tm_sec=58, tm_wday=6, tm_yday=38, tm_isdst=0)\nSee the Python docs\nDon't use it. It's an internal data structure\nWhen you use the index-operator [] it behaves like a tuple\n\n",
"Nascent Notes,\nThe function time.localtime() accepts an optional argument of Epoch seconds, without the argument it takes the current time (probably from time.time()). The function then calculates what time this corresponds to in your timezone (i.e. your local time) and then returns the results in object of type time.struct_time. \nI'm not sure why you want to create a struct_time object, as you're asking about the what the arguments should be, perhaps you're heading in the wrong direction.\nIt seems that you're interested in manipulating representations of time. I think that the datetime module may be more suitable for your purposes.\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"arrays",
"python",
"time"
] |
stackoverflow_0002218737_arrays_python_time.txt
|
Q:
Is it advisable to go with Python 3.1 for a beginner?
Possible Duplicate:
What version of Python should I use if I’m a new to Python?
Is it advisable to go with Python 3.1 for a beginner? Or are there any severe drawbacks I would have to consider?
A:
3.1 is much simpler than 2.5 or 2.6, but currently suffers a severe dearth of third-party add-ons, environments supporting it (big apps using it for scripting, etc) and tools such as IDEs. So, much depends on what you want to learn Python for -- if just for personal edification, 3.1 is ideal; if it's to actually build or control applications, websites, etc, then 2.5 or 2.6 will serve you better at the present time (3.* will no doubt reach and surpass 2.* in the future, but, the future is not here yet;-).
A:
Library support is a big issue, for now, until library developers develop their support for Python 3.x.
For example, here are some popular libraries that you might be interested in learning, that do not yet support Python 3.x:
NumPy and SciPy
Django
wxPython
PySide (free alternative to PyQt, see below)
Here are some libraries that do support Python 3.x:
PyQt
Libraries with support in-progress:
PyGame
A:
A lot of the newer Python books target Python 3.x. You'll be learning the future!
But third party modules aren't necessarily Python 3.x ready... but if you're just learning programming that might not matter much anyway.
A:
The only possible drawback that I can think of is that a lot of existing Python code and examples are written for Python 2.x and might not work in Python 3. But the changes that you need to make are usually quite small so you will soon get used to the slight differences.
If you are learning from a tutorial, make sure it is aimed at Python 3.x and not 2.x so that the examples run correctly.
A:
Python is a good language for beginners. It is easy to get somthing up and running quickly. The language contains all the major programing techniques, such as OOP, etc, so you can learn both how to program and concepts with it.
Plenty of online tutorials:
http://docs.python.org/dev/3.0/tutorial/
https://stackoverflow.com/questions/207701/python-tutorial-for-total-beginners
On a side note, that this is an interpreted language, meaning there is no compiler/linker. So, IMO, it is easier to start writing code.
|
Is it advisable to go with Python 3.1 for a beginner?
|
Possible Duplicate:
What version of Python should I use if I’m a new to Python?
Is it advisable to go with Python 3.1 for a beginner? Or are there any severe drawbacks I would have to consider?
|
[
"3.1 is much simpler than 2.5 or 2.6, but currently suffers a severe dearth of third-party add-ons, environments supporting it (big apps using it for scripting, etc) and tools such as IDEs. So, much depends on what you want to learn Python for -- if just for personal edification, 3.1 is ideal; if it's to actually build or control applications, websites, etc, then 2.5 or 2.6 will serve you better at the present time (3.* will no doubt reach and surpass 2.* in the future, but, the future is not here yet;-).\n",
"Library support is a big issue, for now, until library developers develop their support for Python 3.x.\nFor example, here are some popular libraries that you might be interested in learning, that do not yet support Python 3.x:\n\nNumPy and SciPy\nDjango\nwxPython\nPySide (free alternative to PyQt, see below)\n\nHere are some libraries that do support Python 3.x:\n\nPyQt\n\nLibraries with support in-progress:\n\nPyGame\n\n",
"A lot of the newer Python books target Python 3.x. You'll be learning the future!\nBut third party modules aren't necessarily Python 3.x ready... but if you're just learning programming that might not matter much anyway.\n",
"The only possible drawback that I can think of is that a lot of existing Python code and examples are written for Python 2.x and might not work in Python 3. But the changes that you need to make are usually quite small so you will soon get used to the slight differences.\nIf you are learning from a tutorial, make sure it is aimed at Python 3.x and not 2.x so that the examples run correctly.\n",
"Python is a good language for beginners. It is easy to get somthing up and running quickly. The language contains all the major programing techniques, such as OOP, etc, so you can learn both how to program and concepts with it.\nPlenty of online tutorials:\n\nhttp://docs.python.org/dev/3.0/tutorial/\nhttps://stackoverflow.com/questions/207701/python-tutorial-for-total-beginners\n\nOn a side note, that this is an interpreted language, meaning there is no compiler/linker. So, IMO, it is easier to start writing code.\n"
] |
[
17,
4,
3,
3,
1
] |
[] |
[] |
[
"python",
"python_3.x",
"version"
] |
stackoverflow_0002218841_python_python_3.x_version.txt
|
Q:
What's wrong here? Iterating over a dictionary in Django template
I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value.
Here's what I have in models.py:
class Manors(models.Model):
structidx = models.IntegerField(primary_key=True, verbose_name="ID")
county = models.CharField(max_length=5, null=True, blank=True, verbose_name="County")
def get_fields(self):
d = {}
#d["database"] = "pubs"
#d["uid"] = "sa"
for field in Manors._meta.fields:
d[field.verbose_name(self)] = field.value_to_string(self)
return d
And in views.py:
manor_stats = Manors.objects.get(structidx__exact=id)
return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))
And in the template:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }} </li>
{% endfor %}
</ul>
But I just get a weird, distorted-looking list like:
u: i
d: a
It doesn't even work if I use hard-coded values in models.py (as shown commented out above).
What's wrong here? Been trying to work this out for hours:(
---------- UPDATED ---------------
Trying with
def get_fields(self):
d = {}
for field in Manors._meta.fields:
d[field.verbose_name(self)] = { "verbose": field.verbose_name(self), "value": field.value_to_string(self) }
return d
and in template:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
just produces a blank list....
A:
To iterate a dictionary wouldn't you need:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
But I'd suggest retrieving the dictionary from the function first:
Views.py:
manor_stats = Manors.objects.get(structidx__exact=id).get_fields()
return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))
And then:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
But only because I'm not that familiar with how much dereferencing the templating system can do. Seeing as you know how to deference it you're saving the effort of having the renderer work it out.
A:
Iterating over a dict yields its keys. I don't know why Django thinks you want to do an incomplete sequence expansion on the key name instead of throwing an exception, but I'll chalk it up to ANOTHER one of Django's template engine's quirks.
Anyways, yes, get key from the dict in your for loop, then use key and dict.key inside it.
A:
You're getting the weird results because I think you're iterating over a string's characters. A for loop in django templates isn't the same as in python. Try using an object and iterating via property accessors for object in my objects and then use object.prop1 object.prop2 instead.
|
What's wrong here? Iterating over a dictionary in Django template
|
I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value.
Here's what I have in models.py:
class Manors(models.Model):
structidx = models.IntegerField(primary_key=True, verbose_name="ID")
county = models.CharField(max_length=5, null=True, blank=True, verbose_name="County")
def get_fields(self):
d = {}
#d["database"] = "pubs"
#d["uid"] = "sa"
for field in Manors._meta.fields:
d[field.verbose_name(self)] = field.value_to_string(self)
return d
And in views.py:
manor_stats = Manors.objects.get(structidx__exact=id)
return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))
And in the template:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }} </li>
{% endfor %}
</ul>
But I just get a weird, distorted-looking list like:
u: i
d: a
It doesn't even work if I use hard-coded values in models.py (as shown commented out above).
What's wrong here? Been trying to work this out for hours:(
---------- UPDATED ---------------
Trying with
def get_fields(self):
d = {}
for field in Manors._meta.fields:
d[field.verbose_name(self)] = { "verbose": field.verbose_name(self), "value": field.value_to_string(self) }
return d
and in template:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
just produces a blank list....
|
[
"To iterate a dictionary wouldn't you need:\n<h4>Statistics</h4>\n<ul>\n {% for key, value in manor_stats.get_fields.items %}\n <li> {{ key }}: {{ value }}</li>\n {% endfor %}\n</ul>\n\nBut I'd suggest retrieving the dictionary from the function first:\nViews.py:\n manor_stats = Manors.objects.get(structidx__exact=id).get_fields()\n return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))\n\nAnd then:\n<h4>Statistics</h4>\n<ul>\n {% for key, value in manor_stats.items %}\n <li> {{ key }}: {{ value }}</li>\n {% endfor %}\n</ul>\n\nBut only because I'm not that familiar with how much dereferencing the templating system can do. Seeing as you know how to deference it you're saving the effort of having the renderer work it out.\n",
"Iterating over a dict yields its keys. I don't know why Django thinks you want to do an incomplete sequence expansion on the key name instead of throwing an exception, but I'll chalk it up to ANOTHER one of Django's template engine's quirks.\nAnyways, yes, get key from the dict in your for loop, then use key and dict.key inside it.\n",
"You're getting the weird results because I think you're iterating over a string's characters. A for loop in django templates isn't the same as in python. Try using an object and iterating via property accessors for object in my objects and then use object.prop1 object.prop2 instead.\n"
] |
[
29,
1,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002218388_django_django_templates_python.txt
|
Q:
Many2ManyField is not saving via Modelforms
I have a Modelform:
class POwner4NewModel(ModelForm):
class Meta:
model = ProductOwner
exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status")
This is the model's schema:
class ProductOwner(models.Model):
o_owner = models.ForeignKey(User, verbose_name="Owner")
o_owner_desc = models.TextField(verbose_name="Seller Description")
o_product_model = models.ForeignKey(ProductModel, verbose_name="Product")
o_main_image = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Main Image", blank=True)
o_thumbnail = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Thumbnail (100x100)px", blank=True)
o_gallery_images = models.ManyToManyField(ProductImages, verbose_name="Product Gallery Images", related_name="product_images", blank=True)
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
o_timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Date Created")
o_internationlisation = models.ManyToManyField(Countries, verbose_name="Available in", related_name="product_countries")
This is my code trying to save the form:
def save_m_owner(self, request):
form = POwner4NewModel(request.POST, request.FILES)
form = form.save(commit=False)
form.o_owner = request.user
form.o_owner_desc = self.product_model.p_description
form.o_product_model = self.product_model
form.o_status = "unapproved"
form.o_main_image = self.product_model.p_main_image
form.save()
I've tried adding form.save_m2m() but it says form does not have that attribute. So now, in the field using o_internationlisation, the m2m is not saved. I'm not sure what I'm doing wrong here, could use some help, thanks!
A:
form doesn't have save_m2m() because you overwrote form with a model instance when you did form = form.save(commit=False)
try using something else like instance = form.save(commit=False) etc. then you should be able to use form.save_m2m() (of course after the instance.save()).
|
Many2ManyField is not saving via Modelforms
|
I have a Modelform:
class POwner4NewModel(ModelForm):
class Meta:
model = ProductOwner
exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status")
This is the model's schema:
class ProductOwner(models.Model):
o_owner = models.ForeignKey(User, verbose_name="Owner")
o_owner_desc = models.TextField(verbose_name="Seller Description")
o_product_model = models.ForeignKey(ProductModel, verbose_name="Product")
o_main_image = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Main Image", blank=True)
o_thumbnail = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Thumbnail (100x100)px", blank=True)
o_gallery_images = models.ManyToManyField(ProductImages, verbose_name="Product Gallery Images", related_name="product_images", blank=True)
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
o_timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Date Created")
o_internationlisation = models.ManyToManyField(Countries, verbose_name="Available in", related_name="product_countries")
This is my code trying to save the form:
def save_m_owner(self, request):
form = POwner4NewModel(request.POST, request.FILES)
form = form.save(commit=False)
form.o_owner = request.user
form.o_owner_desc = self.product_model.p_description
form.o_product_model = self.product_model
form.o_status = "unapproved"
form.o_main_image = self.product_model.p_main_image
form.save()
I've tried adding form.save_m2m() but it says form does not have that attribute. So now, in the field using o_internationlisation, the m2m is not saved. I'm not sure what I'm doing wrong here, could use some help, thanks!
|
[
"form doesn't have save_m2m() because you overwrote form with a model instance when you did form = form.save(commit=False)\ntry using something else like instance = form.save(commit=False) etc. then you should be able to use form.save_m2m() (of course after the instance.save()).\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002218424_django_python.txt
|
Q:
How to evaluate a matched number later in a regex? - Lexing FORTRAN 'H' edit descriptor with Ply
I am using Ply to interpret a FORTRAN format string. I am having trouble writing a regex to match the 'H' edit descriptor which is of the form
xHccccc ...
where x specifies the number of characters to read in after the 'H'
Ply matches tokens with a single regular expression, but I am having trouble using regular expression to perform the above. I am looking for something like,
(\d+)[Hh].{\1}
where \1 is parsed as an integer and evaluated as part of the regex - however it isn't.
It seems that it is not possible to use matched numbers later in the same regex, is this the case?
Does anyone have any other solutions that might use Ply?
A:
Regex can't do things like that. You can hack it though:
(1[Hh].|2[Hh]..|3[Hh]...|etc...)
Ugly!
A:
This is what comes of thinking that regexps can replace a lexer.
Short version: regular expressions can only deal with that small subset of all possible language termed "regular" (big surprise, I know). But "regular" is not isomorphic to the human understanding of "simple", so even very simple languages can have non-regular expressions.
Writing a lexer for a simple language is not terribly hard.
That canonical Stack Overflow question for resources on the topic is Learning to write a compiler.
Ah. I seem to have misunderstood the question. Mea Culpa.
I'm not familiar with ply, and its been a while since I used flex, but think you would eat any number of following digits, then check in the associated code block if the rules had been obeyed.
A:
Pyparsing includes an adaptive expression that is very similar to this, called countedArray. countedArray(expr) parses a leading integer 'n' and then parses 'n' instances of expr, returning the whole array as a single list. The way this works is that countedArray parses a leading integer expression, followed by an uninitialized Forward expression. The leading integer expression has a parse action attached that assigns the following Forward to 'n'*expr. The pyparsing parser then continues on, and parses the following 'n' expr's. So it is sort of a self-modifying parser.
To parse your expression, this would look something like:
integer = Word(nums).setParseAction(lambda t:int(t[0]))
following = Forward()
integer.addParseAction(lambda t: following << Word(printables+" ",exact=t[0]))
H_expr = integer + 'H' + following
print H_expr.parseString("22HThis is a test string.This is not in the string")
Prints:
[22, 'H', 'This is a test string.']
If Ply has something similar, perhaps you could use this technique.
|
How to evaluate a matched number later in a regex? - Lexing FORTRAN 'H' edit descriptor with Ply
|
I am using Ply to interpret a FORTRAN format string. I am having trouble writing a regex to match the 'H' edit descriptor which is of the form
xHccccc ...
where x specifies the number of characters to read in after the 'H'
Ply matches tokens with a single regular expression, but I am having trouble using regular expression to perform the above. I am looking for something like,
(\d+)[Hh].{\1}
where \1 is parsed as an integer and evaluated as part of the regex - however it isn't.
It seems that it is not possible to use matched numbers later in the same regex, is this the case?
Does anyone have any other solutions that might use Ply?
|
[
"Regex can't do things like that. You can hack it though:\n(1[Hh].|2[Hh]..|3[Hh]...|etc...)\n\nUgly!\n",
"This is what comes of thinking that regexps can replace a lexer.\nShort version: regular expressions can only deal with that small subset of all possible language termed \"regular\" (big surprise, I know). But \"regular\" is not isomorphic to the human understanding of \"simple\", so even very simple languages can have non-regular expressions.\nWriting a lexer for a simple language is not terribly hard.\nThat canonical Stack Overflow question for resources on the topic is Learning to write a compiler.\n\nAh. I seem to have misunderstood the question. Mea Culpa. \nI'm not familiar with ply, and its been a while since I used flex, but think you would eat any number of following digits, then check in the associated code block if the rules had been obeyed.\n",
"Pyparsing includes an adaptive expression that is very similar to this, called countedArray. countedArray(expr) parses a leading integer 'n' and then parses 'n' instances of expr, returning the whole array as a single list. The way this works is that countedArray parses a leading integer expression, followed by an uninitialized Forward expression. The leading integer expression has a parse action attached that assigns the following Forward to 'n'*expr. The pyparsing parser then continues on, and parses the following 'n' expr's. So it is sort of a self-modifying parser.\nTo parse your expression, this would look something like:\ninteger = Word(nums).setParseAction(lambda t:int(t[0]))\nfollowing = Forward()\ninteger.addParseAction(lambda t: following << Word(printables+\" \",exact=t[0]))\nH_expr = integer + 'H' + following\nprint H_expr.parseString(\"22HThis is a test string.This is not in the string\")\n\nPrints:\n[22, 'H', 'This is a test string.']\n\nIf Ply has something similar, perhaps you could use this technique.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"lexical_analysis",
"ply",
"python",
"regex"
] |
stackoverflow_0002216843_lexical_analysis_ply_python_regex.txt
|
Q:
Does the Python standard library contain a module for manipulating URIs?
I'd like to pass a URI to a constructor and get back an object on which I can call obj.type, obj.host, obj.port, etc. The "Request" object of the urllib2 module is close to what I need, but not quite it.
A:
Maybe something like the urlparse module?
The urlparse module is renamed to urllib.parse in Python 3.0.
From the doc:
>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o # doctest: +NORMALIZE_WHITESPACE
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.port
80
>>> o.geturl()
'http://www.cwi.nl:80/%7Eguido/Python.html'
|
Does the Python standard library contain a module for manipulating URIs?
|
I'd like to pass a URI to a constructor and get back an object on which I can call obj.type, obj.host, obj.port, etc. The "Request" object of the urllib2 module is close to what I need, but not quite it.
|
[
"Maybe something like the urlparse module? \n\nThe urlparse module is renamed to urllib.parse in Python 3.0.\n\nFrom the doc:\n>>> from urlparse import urlparse\n>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')\n>>> o # doctest: +NORMALIZE_WHITESPACE\n ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',\n params='', query='', fragment='')\n>>> o.scheme\n'http'\n>>> o.port\n80\n>>> o.geturl()\n'http://www.cwi.nl:80/%7Eguido/Python.html'\n\n"
] |
[
6
] |
[] |
[] |
[
"python",
"string",
"url"
] |
stackoverflow_0002219827_python_string_url.txt
|
Q:
Simple example of gang scheduling of processes in Python?
I have a pool of processes that need to be executed. I would like to fully utilize the machine, so that all CPUs are executing processes. I do not want to over-subscribe the system, so what i really want is #executing_processes=#cpus at any given moment.
I also need to store the stdout,stderr and return code of each completed processes.
How can this be achieved in Python?
EDIT: by 'process' i mean a shell process.
A:
If you are talking about your own, Python-implemented processes:
The multiprocessing module gives you the ability to spawn multiple processes. In particular, it sounds like you would want to create multiprocessing.cpu_count numbers of processes, potentially in a Pool.
If you are talking about separate programs that you want to execute through the shell:
The subprocess module will let you spawn processes through its Popen class, which has parameters for stdin, stdout, sterr that accept file-like objects. Popen.returncode can be used to check the return code.
|
Simple example of gang scheduling of processes in Python?
|
I have a pool of processes that need to be executed. I would like to fully utilize the machine, so that all CPUs are executing processes. I do not want to over-subscribe the system, so what i really want is #executing_processes=#cpus at any given moment.
I also need to store the stdout,stderr and return code of each completed processes.
How can this be achieved in Python?
EDIT: by 'process' i mean a shell process.
|
[
"If you are talking about your own, Python-implemented processes:\nThe multiprocessing module gives you the ability to spawn multiple processes. In particular, it sounds like you would want to create multiprocessing.cpu_count numbers of processes, potentially in a Pool.\nIf you are talking about separate programs that you want to execute through the shell:\nThe subprocess module will let you spawn processes through its Popen class, which has parameters for stdin, stdout, sterr that accept file-like objects. Popen.returncode can be used to check the return code.\n"
] |
[
2
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0002220083_multiprocessing_python.txt
|
Q:
python tuple division
TypeError: unsupported operand type(s) for /: 'tuple' and 'tuple'
I'm getting above error , while I fetched a record using query "select max(rowid) from table"
and assigned it to variable and while performing / operation is throws above message.
How to resolve this.
A:
Sql query select max(rowid) would return Tuple data like records=(1000,)
You may need to do like numerator / records[0]
|
python tuple division
|
TypeError: unsupported operand type(s) for /: 'tuple' and 'tuple'
I'm getting above error , while I fetched a record using query "select max(rowid) from table"
and assigned it to variable and while performing / operation is throws above message.
How to resolve this.
|
[
"Sql query select max(rowid) would return Tuple data like records=(1000,)\nYou may need to do like numerator / records[0]\n"
] |
[
4
] |
[] |
[] |
[
"python",
"tuples"
] |
stackoverflow_0002220099_python_tuples.txt
|
Q:
delete xml node using lxml
admin
.
.
.
.
admin
this my xml file.
when i user clear()or del method it will clear all the child and a blank node is creating
<user/>
How can i avoid creating this blank node
it will make problem when i use findall() and try to access any of its child
can anyone provide me a piece of code to del the node fully???
A:
Removing match user node from parent Node would be suitable for this case.
|
delete xml node using lxml
|
admin
.
.
.
.
admin
this my xml file.
when i user clear()or del method it will clear all the child and a blank node is creating
<user/>
How can i avoid creating this blank node
it will make problem when i use findall() and try to access any of its child
can anyone provide me a piece of code to del the node fully???
|
[
"Removing match user node from parent Node would be suitable for this case.\n"
] |
[
4
] |
[] |
[] |
[
"lxml",
"python",
"xml"
] |
stackoverflow_0002220185_lxml_python_xml.txt
|
Q:
Catching errors when logging with SocketHandler in Python
My web application runs on multpile apache instances and I am having multiprocess logging issues because of this. I am currently using a SocketHandler for logging to a daemon using SocketServer that then writes logs to a single log file (similar to this example).
Now that I am using a SocketHandler for logging I am having trouble discovering if/when the socket server crashes. For example, if I try creating a SocketHandler for a port that has no listening socket server, no exception arises. I would like to catch this type of error and log it to a file.
My question is, when logging using SocketHandler how can I discover when the socket being used is not currently being listened to?
A:
When a socket creation operation fails (e.g. because there is no server listening), the default behaviour is to retry the next time an event is logged, with an exponential back-off algorithm. Here are some approaches you could try:
Subclass SocketHandler, override the createSocket method and handle exceptions how you will in your implementation.
Note that the sock attribute of the SocketHandler instance will be None if no socket has been created yet. If the value is None after you've logged an event, most likely the SocketHandler wouldn't have sent it.
Note that the makeSocket method of the handler is used to actually create and connect the socket. So, you could call makeSocket yourself before logging anything, and if it throws an exception, you know that your server is probably not listening. If it returns success, then you can just close the returned value.
Subclass SocketHandler, override the emit method, and in your subclass, have a reference to an alternate handler instance (e.g. FileHandler or SMTPHandler) which you want to use. In your emit code, try to create the socket using
if self.sock is None:
self.createSocket()
if self.sock is None:
# creation failed: do self.alternate_handler.handle(record)
else:
# creation succeeded: defer to superclass implementation
Of course, this may not catch any errors that occur if the server goes down in the middle of sending a message, but it should at least alert you to some problems with your servers.
A:
There is no way to do that with the current resilient implementation. "Resilient" means in this case that the SocketHandler will handle problems with the socket already by trying to reopen it as soon as there is a problem.
Just restart the server and the handlers will reconnect eventually.
|
Catching errors when logging with SocketHandler in Python
|
My web application runs on multpile apache instances and I am having multiprocess logging issues because of this. I am currently using a SocketHandler for logging to a daemon using SocketServer that then writes logs to a single log file (similar to this example).
Now that I am using a SocketHandler for logging I am having trouble discovering if/when the socket server crashes. For example, if I try creating a SocketHandler for a port that has no listening socket server, no exception arises. I would like to catch this type of error and log it to a file.
My question is, when logging using SocketHandler how can I discover when the socket being used is not currently being listened to?
|
[
"When a socket creation operation fails (e.g. because there is no server listening), the default behaviour is to retry the next time an event is logged, with an exponential back-off algorithm. Here are some approaches you could try:\n\nSubclass SocketHandler, override the createSocket method and handle exceptions how you will in your implementation.\nNote that the sock attribute of the SocketHandler instance will be None if no socket has been created yet. If the value is None after you've logged an event, most likely the SocketHandler wouldn't have sent it.\nNote that the makeSocket method of the handler is used to actually create and connect the socket. So, you could call makeSocket yourself before logging anything, and if it throws an exception, you know that your server is probably not listening. If it returns success, then you can just close the returned value.\nSubclass SocketHandler, override the emit method, and in your subclass, have a reference to an alternate handler instance (e.g. FileHandler or SMTPHandler) which you want to use. In your emit code, try to create the socket using\nif self.sock is None:\n self.createSocket()\nif self.sock is None:\n # creation failed: do self.alternate_handler.handle(record)\nelse:\n # creation succeeded: defer to superclass implementation\n\n\nOf course, this may not catch any errors that occur if the server goes down in the middle of sending a message, but it should at least alert you to some problems with your servers.\n",
"There is no way to do that with the current resilient implementation. \"Resilient\" means in this case that the SocketHandler will handle problems with the socket already by trying to reopen it as soon as there is a problem.\nJust restart the server and the handlers will reconnect eventually.\n"
] |
[
5,
1
] |
[] |
[] |
[
"exception_handling",
"mod_python",
"python",
"sockets"
] |
stackoverflow_0002220159_exception_handling_mod_python_python_sockets.txt
|
Q:
writing to data to excel
I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated.
def month_end(request):
"""
A simple view that will generate a month end report as a PDF response.
"""
current_date = datetime.now()
context = {}
context['month'] = current_date.month
context['year'] = current_date.year
context['company'] = 3
if request.method == 'POST':
context['form'] = MonthEndForm(user=request.user, data=request.POST)
if context['form'].is_valid():
#from reportlab.pdfgen import canvas
#import ho.pisa as pisa
context['month_no'] = int(context['form'].cleaned_data['month'])
context['company'] = context['form'].cleaned_data['company']
context['year'] = context['form'].cleaned_data['year']
context['month'] = datetime(context['year'], context['month_no'], 1).strftime('%B')
sql = '''SELECT "campaign_provider"."originator" as originator, "campaign_provider"."cost",
"campaign_receivedmessage"."network_id",
COUNT("campaign_provider"."originator") AS "originator_count",
"shortcode_network"."network"
FROM "campaign_receivedmessage"
LEFT OUTER JOIN "shortcode_network" ON ("shortcode_network"."id" = "campaign_receivedmessage"."network_id")
LEFT OUTER JOIN "campaign_provider" ON ("campaign_receivedmessage"."provider_id" = "campaign_provider"."id")
WHERE ("campaign_provider"."company_id" = %s
AND EXTRACT('month' FROM "campaign_receivedmessage"."date_received") = %s)
GROUP BY "campaign_provider"."originator", "campaign_provider"."cost", "campaign_receivedmessage"."network_id", "shortcode_network"."network"
ORDER BY "campaign_provider"."originator", "campaign_receivedmessage"."network_id" ASC
''' % (context['company'].id, context['month_no'])
context['rec_messages']= []
cursor = connection.cursor()
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
dict = {}
desc = cursor.description
for (name, value) in zip(desc, row) :
dict[name[0]] = value
try:
dict['share'] = RevenueShare.objects.get(company=context['company'], priceband=dict['cost'], network=dict['network_id']).customer_share
dict['revenue'] = dict['originator_count'] * dict['share']
except:
dict['share'] = 0
dict['revenue'] = 0
context['rec_messages'].append(dict)
#context['rec_messages'] = ReceivedMessage.objects.filter(provider__company__id=context['company'].id, date_received__month=context['month_no'], date_received__year=context['year']).values('provider__originator', 'provider__cost', 'network').annotate(originator_count=Count('provider__originator')).order_by('provider__originator')
context['ret_messages'] = SentMessage.objects.filter(campaign__providers__company__id=context['company'].id, date_sent__month=context['month_no'], date_sent__year=context['year']).values('campaign__title').annotate(campaign_count=Count('campaign__title')).order_by('campaign__title')
context['revenue_share'] = RevenueShare.objects.filter(company=context['company'].id)
context['total_rec'] = 0
context['total_ret'] = 0
context['total_value'] = 0
context['total_cost'] = 0
context['queries'] = connection.queries
for message in context['rec_messages']:
context['total_rec'] += message['originator_count']
context['total_value'] += message['revenue']
for message in context['ret_messages']:
message['price'] = 0.175
message['cost'] = message['campaign_count'] * message['price']
context['total_ret'] += message['campaign_count']
context['total_cost'] += message['cost']
context['total'] = context['total_value'] - context['total_cost']
context['loaded_report'] = "yes"
data.append((context['data']))
data.append(('Orginator', 'cost', 'network_id', 'originator_count', 'network'))
file_name = '%s' % ('reports')
return generate_csv(file_name, data)
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#csv_data = StringIO.StringIO()
#csv_data.seek()
#simple_report = ExcelReport()34
#simple_report.addSheet("TestSimple")
#simple_report.writeReport(csv_data)
#response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
#response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
#return response
return render_to_response('reports/month_end.html', RequestContext(request, context))
#return render_to_response('reports/rfm_models.html', RequestContext(request, context))
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#pdf_data = StringIO.StringIO()
#pisa.CreatePDF(template_data, pdf_data, link_callback=fetch_resources)
#pdf_data.seek(0)
#response = HttpResponse(pdf_data, mimetype='application/pdf')
#response['Content-Disposition'] = 'attachment; filename=%s_%s_%s.pdf' % (context['company'].name.lower().replace(' ', '_'), context['month'].lower()[:3], context['year'])
if 'form' not in context.keys():
context['form'] = MonthEndForm(user=request.user, data=context)
return render_to_response('reports/month_end.html', RequestContext(request, context))
A:
Have a look to xlwt http://pypi.python.org/pypi/xlwt
A:
You could directly write CSV from MySQL records,
import csv
csv_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
data = cursor.fetchall()
for row in data:
csv_writer.writerow(row)
Full example at
http://snipplr.com/view/11970/simple-csv-dump-script/
SELECTQ="SELECT * FROM category"
FILENAME="dump.csv"
import MySQLdb
import csv
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="sakila")
dump_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
cursor = db.cursor()
cursor.execute(SELECTQ)
result = cursor.fetchall()
for record in result:
dump_writer.writerow(record)
db.close()
|
writing to data to excel
|
I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated.
def month_end(request):
"""
A simple view that will generate a month end report as a PDF response.
"""
current_date = datetime.now()
context = {}
context['month'] = current_date.month
context['year'] = current_date.year
context['company'] = 3
if request.method == 'POST':
context['form'] = MonthEndForm(user=request.user, data=request.POST)
if context['form'].is_valid():
#from reportlab.pdfgen import canvas
#import ho.pisa as pisa
context['month_no'] = int(context['form'].cleaned_data['month'])
context['company'] = context['form'].cleaned_data['company']
context['year'] = context['form'].cleaned_data['year']
context['month'] = datetime(context['year'], context['month_no'], 1).strftime('%B')
sql = '''SELECT "campaign_provider"."originator" as originator, "campaign_provider"."cost",
"campaign_receivedmessage"."network_id",
COUNT("campaign_provider"."originator") AS "originator_count",
"shortcode_network"."network"
FROM "campaign_receivedmessage"
LEFT OUTER JOIN "shortcode_network" ON ("shortcode_network"."id" = "campaign_receivedmessage"."network_id")
LEFT OUTER JOIN "campaign_provider" ON ("campaign_receivedmessage"."provider_id" = "campaign_provider"."id")
WHERE ("campaign_provider"."company_id" = %s
AND EXTRACT('month' FROM "campaign_receivedmessage"."date_received") = %s)
GROUP BY "campaign_provider"."originator", "campaign_provider"."cost", "campaign_receivedmessage"."network_id", "shortcode_network"."network"
ORDER BY "campaign_provider"."originator", "campaign_receivedmessage"."network_id" ASC
''' % (context['company'].id, context['month_no'])
context['rec_messages']= []
cursor = connection.cursor()
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
dict = {}
desc = cursor.description
for (name, value) in zip(desc, row) :
dict[name[0]] = value
try:
dict['share'] = RevenueShare.objects.get(company=context['company'], priceband=dict['cost'], network=dict['network_id']).customer_share
dict['revenue'] = dict['originator_count'] * dict['share']
except:
dict['share'] = 0
dict['revenue'] = 0
context['rec_messages'].append(dict)
#context['rec_messages'] = ReceivedMessage.objects.filter(provider__company__id=context['company'].id, date_received__month=context['month_no'], date_received__year=context['year']).values('provider__originator', 'provider__cost', 'network').annotate(originator_count=Count('provider__originator')).order_by('provider__originator')
context['ret_messages'] = SentMessage.objects.filter(campaign__providers__company__id=context['company'].id, date_sent__month=context['month_no'], date_sent__year=context['year']).values('campaign__title').annotate(campaign_count=Count('campaign__title')).order_by('campaign__title')
context['revenue_share'] = RevenueShare.objects.filter(company=context['company'].id)
context['total_rec'] = 0
context['total_ret'] = 0
context['total_value'] = 0
context['total_cost'] = 0
context['queries'] = connection.queries
for message in context['rec_messages']:
context['total_rec'] += message['originator_count']
context['total_value'] += message['revenue']
for message in context['ret_messages']:
message['price'] = 0.175
message['cost'] = message['campaign_count'] * message['price']
context['total_ret'] += message['campaign_count']
context['total_cost'] += message['cost']
context['total'] = context['total_value'] - context['total_cost']
context['loaded_report'] = "yes"
data.append((context['data']))
data.append(('Orginator', 'cost', 'network_id', 'originator_count', 'network'))
file_name = '%s' % ('reports')
return generate_csv(file_name, data)
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#csv_data = StringIO.StringIO()
#csv_data.seek()
#simple_report = ExcelReport()34
#simple_report.addSheet("TestSimple")
#simple_report.writeReport(csv_data)
#response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
#response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
#return response
return render_to_response('reports/month_end.html', RequestContext(request, context))
#return render_to_response('reports/rfm_models.html', RequestContext(request, context))
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#pdf_data = StringIO.StringIO()
#pisa.CreatePDF(template_data, pdf_data, link_callback=fetch_resources)
#pdf_data.seek(0)
#response = HttpResponse(pdf_data, mimetype='application/pdf')
#response['Content-Disposition'] = 'attachment; filename=%s_%s_%s.pdf' % (context['company'].name.lower().replace(' ', '_'), context['month'].lower()[:3], context['year'])
if 'form' not in context.keys():
context['form'] = MonthEndForm(user=request.user, data=context)
return render_to_response('reports/month_end.html', RequestContext(request, context))
|
[
"Have a look to xlwt http://pypi.python.org/pypi/xlwt\n",
"You could directly write CSV from MySQL records,\nimport csv\ncsv_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar=\"'\")\n\ndata = cursor.fetchall()\nfor row in data:\n csv_writer.writerow(row)\n\nFull example at\nhttp://snipplr.com/view/11970/simple-csv-dump-script/\nSELECTQ=\"SELECT * FROM category\"\nFILENAME=\"dump.csv\"\n\nimport MySQLdb\nimport csv\n\ndb = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\")\ndump_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar=\"'\")\ncursor = db.cursor()\ncursor.execute(SELECTQ)\nresult = cursor.fetchall()\nfor record in result:\n dump_writer.writerow(record)\n\ndb.close()\n\n"
] |
[
4,
4
] |
[] |
[] |
[
"csv",
"django",
"python"
] |
stackoverflow_0002220351_csv_django_python.txt
|
Q:
Python properties: Two instances of variable?
Really confused about what's going on here. I have a class defined as follows:
class Profile(models.Model):
user = models.OneToOneField(User)
primary_phone = models.CharField(max_length=20)
address = models.ForeignKey(Address)
@property
def primary_email(self): return self.user.email
@primary_email.setter
def primary_email(self, val): self.user.email = val
NB: user has an attribute email.
Now from the commandline, I'm trying this:
>>> u = User.objects.get(pk=1)
>>> u.email = 'xxx'
>>> u.profile.primary_email
u'yyy'
It spits out a different value? Specifically, the old value of u.email. What's going on? How is this possible? I basically just want to create an alias for email.
Some more info:
>>> id(u) == id(u.profile.user)
False
>>> u
<User: mark>
>>> u.profile.user
<User: mark>
They seem to be different copies of user, but they... what? Both start with the same values?
Doing this seems to commit the changes:
>>> u.profile.primary_email = 'yyy'
>>> u.profile.user.save()
But u.save() won't do the trick because u != u.profile.user for whatever reason. I guess that answers my question, but it's still kind of lame.
It is possible for those two to refer to the same object in Python, right? It was just a funny design decision in Django that's causing this?
A:
I'm not a Django user, but I'd guess it's because you didn't update the model after changing u.email. Try calling u.save() (or whatever the method happens to be called) before accessing the user's email through the profile.
You can use Django's signaling feature to build a workaround. Basically, update Profile.user when User sends post_save:
# models.py
...
def update_user(**kwargs):
kwargs['instance'].profile.user = kwargs['instance']
models.signals.post_save.connect(update_user, sender=User)
You still need to call User.save for this to work, and clobbering Profile.user may have other side effects. There might be a more Django-y way; someone with more Django experience than I may yet post it. For example, it may be possible to hook the code that gets called the first time you access User.profile and set Profile.user to the parent user, instead of creating a new User.
Alternatively, whenever you get a user via Users.objects.get and reference Users.profile, replace the user object with the user property from User.profile.
A:
Python properties per se do not work in django models because django's models do some magic to set instance attributes. Maybe this is having an effect.
|
Python properties: Two instances of variable?
|
Really confused about what's going on here. I have a class defined as follows:
class Profile(models.Model):
user = models.OneToOneField(User)
primary_phone = models.CharField(max_length=20)
address = models.ForeignKey(Address)
@property
def primary_email(self): return self.user.email
@primary_email.setter
def primary_email(self, val): self.user.email = val
NB: user has an attribute email.
Now from the commandline, I'm trying this:
>>> u = User.objects.get(pk=1)
>>> u.email = 'xxx'
>>> u.profile.primary_email
u'yyy'
It spits out a different value? Specifically, the old value of u.email. What's going on? How is this possible? I basically just want to create an alias for email.
Some more info:
>>> id(u) == id(u.profile.user)
False
>>> u
<User: mark>
>>> u.profile.user
<User: mark>
They seem to be different copies of user, but they... what? Both start with the same values?
Doing this seems to commit the changes:
>>> u.profile.primary_email = 'yyy'
>>> u.profile.user.save()
But u.save() won't do the trick because u != u.profile.user for whatever reason. I guess that answers my question, but it's still kind of lame.
It is possible for those two to refer to the same object in Python, right? It was just a funny design decision in Django that's causing this?
|
[
"I'm not a Django user, but I'd guess it's because you didn't update the model after changing u.email. Try calling u.save() (or whatever the method happens to be called) before accessing the user's email through the profile.\nYou can use Django's signaling feature to build a workaround. Basically, update Profile.user when User sends post_save:\n# models.py\n...\ndef update_user(**kwargs):\n kwargs['instance'].profile.user = kwargs['instance']\n\nmodels.signals.post_save.connect(update_user, sender=User)\n\nYou still need to call User.save for this to work, and clobbering Profile.user may have other side effects. There might be a more Django-y way; someone with more Django experience than I may yet post it. For example, it may be possible to hook the code that gets called the first time you access User.profile and set Profile.user to the parent user, instead of creating a new User.\nAlternatively, whenever you get a user via Users.objects.get and reference Users.profile, replace the user object with the user property from User.profile.\n",
"Python properties per se do not work in django models because django's models do some magic to set instance attributes. Maybe this is having an effect.\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002218989_django_python.txt
|
Q:
perror equivalent function in python
I'm using try except block in python, while the try block fails , how to print meaningful error message. I'm looking for something like perror() in C
A:
>>> try:
... 0/0
... except Exception,e:
... print e.message
...
integer division or modulo by zero
or in Python 2.6 and above, e.args, because of BaseException.message has been deprecated
>>> try:
... 0/0
... except Exception,e:
... print e.args
...
('integer division or modulo by zero',)
|
perror equivalent function in python
|
I'm using try except block in python, while the try block fails , how to print meaningful error message. I'm looking for something like perror() in C
|
[
">>> try:\n... 0/0\n... except Exception,e:\n... print e.message\n...\ninteger division or modulo by zero\n\nor in Python 2.6 and above, e.args, because of BaseException.message has been deprecated\n>>> try:\n... 0/0\n... except Exception,e:\n... print e.args\n...\n('integer division or modulo by zero',)\n\n"
] |
[
6
] |
[
"try:\n pass\nexcept Exception, err:\n print err\n\n"
] |
[
-2
] |
[
"python",
"try_catch"
] |
stackoverflow_0002220038_python_try_catch.txt
|
Q:
Does Django have `__not_equal`?
Does Django have a field lookup like __not_equal? (Field lookups are __exact, __contains, etc.)
A:
Use one of __exact, __contains etc. with exclude() instead of filter().
A:
You can also use the Q object and negate it.
E.g.
Poll.objects.filter(~Q(question='Who'))
|
Does Django have `__not_equal`?
|
Does Django have a field lookup like __not_equal? (Field lookups are __exact, __contains, etc.)
|
[
"Use one of __exact, __contains etc. with exclude() instead of filter().\n",
"You can also use the Q object and negate it.\nE.g.\nPoll.objects.filter(~Q(question='Who'))\n\n"
] |
[
6,
3
] |
[] |
[] |
[
"django",
"orm",
"python"
] |
stackoverflow_0002220682_django_orm_python.txt
|
Q:
Google App Engine: How do I save uploaded text file to Blob, then read from it line by line?
I have a huge file (over 16,000 lines) that I want to save in the datastore for parsing later. Each line contains info on an entity.
How do I read line by line from the stored Blob?
I can't seem to find a good tutorial or documentation on a Blob anywhere. GAE only shows how to deal with images, but I want to read from the stored text file.
A:
Use the Text type to store it instead of a blob. Text does not have any limits on size, but its not indexable or queryable.
So if all you want is sequential line by line access to the data, it would work perfectly.
A:
If you simply need the lines from the blob, just do:
lines = blob.split("\n")
If you need to treat the blob like a file, do:
fh = StringIO.StringIO(blob)
|
Google App Engine: How do I save uploaded text file to Blob, then read from it line by line?
|
I have a huge file (over 16,000 lines) that I want to save in the datastore for parsing later. Each line contains info on an entity.
How do I read line by line from the stored Blob?
I can't seem to find a good tutorial or documentation on a Blob anywhere. GAE only shows how to deal with images, but I want to read from the stored text file.
|
[
"Use the Text type to store it instead of a blob. Text does not have any limits on size, but its not indexable or queryable. \nSo if all you want is sequential line by line access to the data, it would work perfectly.\n",
"If you simply need the lines from the blob, just do:\nlines = blob.split(\"\\n\")\n\nIf you need to treat the blob like a file, do:\nfh = StringIO.StringIO(blob)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"blob",
"google_app_engine",
"python"
] |
stackoverflow_0002216134_blob_google_app_engine_python.txt
|
Q:
Migrating off AppEngine
I have an application running on AppEngine that uses about 50 CPU hours a day. Most of it is spent waiting for the datastore.
I am contemplating moving it off of AppEngine to something like Rackspace Cloud Servers because I think that my application can be more efficient if I can offload some of the work to the database (plus I can add more features that would be difficult to implement on AppEngine).
So, how would I go about moving an AppEngine app? It is developed with the webapp framework and does not use many Google APIs other than the datastore. Ideally I would be able to keep the webapp code and swap out the db classes for something that would talk to another database (MySQL or PostgreSQL is probably preferable to something like CouchDB or MongoDB, but those could work too).
UPDATE: In response to the comments below...
I have run plenty of web applications before. I have not run production python apps before. I assume setting up the python / webserver aspect is fairly simple. My hope for going with something like Rackspace Cloud servers is that it will be 1 "server" that I can just add resources too as we grow. We are currently doing about 200k hits a day.
As for AppEngine optimizations, we are using memcache where we can (not many places). We are also using Tasks, and while that helps get around request timeouts, it adds to the resources used.
My primary question is a good python alternative for the data layer that might require the fewest code changes. Though I also know there are probably some relevant questions that I am not thinking to ask.
A:
If you can redeploy to appscale, you won't have to rewrite any of your App Engine code.
A:
You can use TyphoonAE, which is based on the SDK, and designed for small to medium scale deployments - eg, individual servers to small clusters - and should be fairly easy to set up.
Sorry to see you go.
|
Migrating off AppEngine
|
I have an application running on AppEngine that uses about 50 CPU hours a day. Most of it is spent waiting for the datastore.
I am contemplating moving it off of AppEngine to something like Rackspace Cloud Servers because I think that my application can be more efficient if I can offload some of the work to the database (plus I can add more features that would be difficult to implement on AppEngine).
So, how would I go about moving an AppEngine app? It is developed with the webapp framework and does not use many Google APIs other than the datastore. Ideally I would be able to keep the webapp code and swap out the db classes for something that would talk to another database (MySQL or PostgreSQL is probably preferable to something like CouchDB or MongoDB, but those could work too).
UPDATE: In response to the comments below...
I have run plenty of web applications before. I have not run production python apps before. I assume setting up the python / webserver aspect is fairly simple. My hope for going with something like Rackspace Cloud servers is that it will be 1 "server" that I can just add resources too as we grow. We are currently doing about 200k hits a day.
As for AppEngine optimizations, we are using memcache where we can (not many places). We are also using Tasks, and while that helps get around request timeouts, it adds to the resources used.
My primary question is a good python alternative for the data layer that might require the fewest code changes. Though I also know there are probably some relevant questions that I am not thinking to ask.
|
[
"If you can redeploy to appscale, you won't have to rewrite any of your App Engine code.\n",
"You can use TyphoonAE, which is based on the SDK, and designed for small to medium scale deployments - eg, individual servers to small clusters - and should be fairly easy to set up.\nSorry to see you go.\n"
] |
[
9,
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"web_applications"
] |
stackoverflow_0002215721_google_app_engine_python_web_applications.txt
|
Q:
App engine - Uploading a large file and parsing data from it onto the datastore
I have a file that contains ~16,000 lines of information on entities. The user is supposed to upload the file using an HTML upload form, then the system handles this by reading line by line and creating then put()'ing entities onto the datastore.
I'm limited by the 30 second request time limit. I have tried a lot of different work-arounds using Task Queue, forced HTML redirecting, etc. and nothing has worked for me.
I am using forced HTML redirecting to delete all data and this works, albeit VERY slowly. (4th answer here: Delete all data for a kind in Google App Engine)
I can't seem to apply this to my uploading problem, since my method has to be a POST method. Is there a solution somehow? Sample code would be much appreciated since I'm very new to web development in general.
A:
To solve a similar problem, I stored the dataset in a model with a single TextProperty, then spawn a taskqueue task that:
Fetches a dataset from the datastore if there are any left.
Checks if the length of the dataset is <= N, where N is some small number of entities you can put() without a timeout. I used 5. If so, write the individual entities, delete the dataset record, and spawn a new copy of the task.
If the dataset size was bigger than N, split it into N parts in the same format and write those to the datastore, delete the original entity, and spawn a new copy of the task.
A:
If you're doing this to bulk load data, why not use the bulk loader?
If you need the interface to be accessible to non-admin users, then, as suggested, you need to break the file up into decent sized chunks (by taking blocks of n lines each) put them into the datastore, and start a task to deal with each of them.
|
App engine - Uploading a large file and parsing data from it onto the datastore
|
I have a file that contains ~16,000 lines of information on entities. The user is supposed to upload the file using an HTML upload form, then the system handles this by reading line by line and creating then put()'ing entities onto the datastore.
I'm limited by the 30 second request time limit. I have tried a lot of different work-arounds using Task Queue, forced HTML redirecting, etc. and nothing has worked for me.
I am using forced HTML redirecting to delete all data and this works, albeit VERY slowly. (4th answer here: Delete all data for a kind in Google App Engine)
I can't seem to apply this to my uploading problem, since my method has to be a POST method. Is there a solution somehow? Sample code would be much appreciated since I'm very new to web development in general.
|
[
"To solve a similar problem, I stored the dataset in a model with a single TextProperty, then spawn a taskqueue task that:\n\nFetches a dataset from the datastore if there are any left.\nChecks if the length of the dataset is <= N, where N is some small number of entities you can put() without a timeout. I used 5. If so, write the individual entities, delete the dataset record, and spawn a new copy of the task.\nIf the dataset size was bigger than N, split it into N parts in the same format and write those to the datastore, delete the original entity, and spawn a new copy of the task.\n\n",
"If you're doing this to bulk load data, why not use the bulk loader?\nIf you need the interface to be accessible to non-admin users, then, as suggested, you need to break the file up into decent sized chunks (by taking blocks of n lines each) put them into the datastore, and start a task to deal with each of them.\n"
] |
[
2,
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"upload"
] |
stackoverflow_0002208546_google_app_engine_python_upload.txt
|
Q:
Python list slice syntax used for no obvious reason
I occasionally see the list slice syntax used in Python code like this:
newList = oldList[:]
Surely this is just the same as:
newList = oldList
Or am I missing something?
A:
[:] Shallow copies the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original.
A Deep Copy would make copies of all the list members as well.
The code snippet below shows a shallow copy in action.
# ================================================================
# === ShallowCopy.py =============================================
# ================================================================
#
class Foo:
def __init__(self, data):
self._data = data
aa = Foo ('aaa')
bb = Foo ('bbb')
# The initial list has two elements containing 'aaa' and 'bbb'
OldList = [aa,bb]
print OldList[0]._data
# The shallow copy makes a new list pointing to the old elements
NewList = OldList[:]
print NewList[0]._data
# Updating one of the elements through the new list sees the
# change reflected when you access that element through the
# old list.
NewList[0]._data = 'xxx'
print OldList[0]._data
# Updating the new list to point to something new is not reflected
# in the old list.
NewList[0] = Foo ('ccc')
print NewList[0]._data
print OldList[0]._data
Running it in a python shell gives the following transcript. We can see the
list being made with copies of the old objects. One of the objects can have
its state updated by reference through the old list, and the updates can be
seen when the object is accessed through the old list. Finally, changing a
reference in the new list can be seen to not reflect in the old list, as the
new list is now referring to a different object.
>>> # ================================================================
... # === ShallowCopy.py =============================================
... # ================================================================
... #
... class Foo:
... def __init__(self, data):
... self._data = data
...
>>> aa = Foo ('aaa')
>>> bb = Foo ('bbb')
>>>
>>> # The initial list has two elements containing 'aaa' and 'bbb'
... OldList = [aa,bb]
>>> print OldList[0]._data
aaa
>>>
>>> # The shallow copy makes a new list pointing to the old elements
... NewList = OldList[:]
>>> print NewList[0]._data
aaa
>>>
>>> # Updating one of the elements through the new list sees the
... # change reflected when you access that element through the
... # old list.
... NewList[0]._data = 'xxx'
>>> print OldList[0]._data
xxx
>>>
>>> # Updating the new list to point to something new is not reflected
... # in the old list.
... NewList[0] = Foo ('ccc')
>>> print NewList[0]._data
ccc
>>> print OldList[0]._data
xxx
A:
Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.
newList = oldList would create two different variables that point to the same object, therefore, changing oldList would also change newList.
However, when you do newList = oldList[:], it "slices" the list, and creates a new list. The default values for [:] are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.
A:
As it has already been answered, I'll simply add a simple demonstration:
>>> a = [1, 2, 3, 4]
>>> b = a
>>> c = a[:]
>>> b[2] = 10
>>> c[3] = 20
>>> a
[1, 2, 10, 4]
>>> b
[1, 2, 10, 4]
>>> c
[1, 2, 3, 20]
A:
Never think that 'a = b' in Python means 'copy b to a'. If there are variables on both sides, you can't really know that. Instead, think of it as 'give b the additional name a'.
If b is an immutable object (like a number, tuple or a string), then yes, the effect is that you get a copy. But that's because when you deal with immutables (which maybe should have been called read only, unchangeable or WORM) you always get a copy, by definition.
If b is a mutable, you always have to do something extra to be sure you have a true copy. Always. With lists, it's as simple as a slice: a = b[:].
Mutability is also the reason that this:
def myfunction(mylist=[]):
pass
... doesn't quite do what you think it does.
If you're from a C-background: what's left of the '=' is a pointer, always. All variables are pointers, always. If you put variables in a list: a = [b, c], you've put pointers to the values pointed to by b and c in a list pointed to by a. If you then set a[0] = d, the pointer in position 0 is now pointing to whatever d points to.
See also the copy-module: http://docs.python.org/library/copy.html
|
Python list slice syntax used for no obvious reason
|
I occasionally see the list slice syntax used in Python code like this:
newList = oldList[:]
Surely this is just the same as:
newList = oldList
Or am I missing something?
|
[
"[:] Shallow copies the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original. \nA Deep Copy would make copies of all the list members as well.\nThe code snippet below shows a shallow copy in action.\n# ================================================================\n# === ShallowCopy.py =============================================\n# ================================================================\n#\nclass Foo:\n def __init__(self, data):\n self._data = data\n\naa = Foo ('aaa')\nbb = Foo ('bbb')\n\n# The initial list has two elements containing 'aaa' and 'bbb'\nOldList = [aa,bb]\nprint OldList[0]._data\n\n# The shallow copy makes a new list pointing to the old elements\nNewList = OldList[:]\nprint NewList[0]._data\n\n# Updating one of the elements through the new list sees the\n# change reflected when you access that element through the\n# old list.\nNewList[0]._data = 'xxx'\nprint OldList[0]._data\n\n# Updating the new list to point to something new is not reflected\n# in the old list.\nNewList[0] = Foo ('ccc')\nprint NewList[0]._data\nprint OldList[0]._data\n\nRunning it in a python shell gives the following transcript. We can see the\nlist being made with copies of the old objects. One of the objects can have\nits state updated by reference through the old list, and the updates can be\nseen when the object is accessed through the old list. Finally, changing a\nreference in the new list can be seen to not reflect in the old list, as the\nnew list is now referring to a different object.\n>>> # ================================================================\n... # === ShallowCopy.py =============================================\n... # ================================================================\n... #\n... class Foo:\n... def __init__(self, data):\n... self._data = data\n...\n>>> aa = Foo ('aaa')\n>>> bb = Foo ('bbb')\n>>>\n>>> # The initial list has two elements containing 'aaa' and 'bbb'\n... OldList = [aa,bb]\n>>> print OldList[0]._data\naaa\n>>>\n>>> # The shallow copy makes a new list pointing to the old elements\n... NewList = OldList[:]\n>>> print NewList[0]._data\naaa\n>>>\n>>> # Updating one of the elements through the new list sees the\n... # change reflected when you access that element through the\n... # old list.\n... NewList[0]._data = 'xxx'\n>>> print OldList[0]._data\nxxx\n>>>\n>>> # Updating the new list to point to something new is not reflected\n... # in the old list.\n... NewList[0] = Foo ('ccc')\n>>> print NewList[0]._data\nccc\n>>> print OldList[0]._data\nxxx\n\n",
"Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.\nnewList = oldList would create two different variables that point to the same object, therefore, changing oldList would also change newList.\nHowever, when you do newList = oldList[:], it \"slices\" the list, and creates a new list. The default values for [:] are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.\n",
"As it has already been answered, I'll simply add a simple demonstration:\n>>> a = [1, 2, 3, 4]\n>>> b = a\n>>> c = a[:]\n>>> b[2] = 10\n>>> c[3] = 20\n>>> a\n[1, 2, 10, 4]\n>>> b\n[1, 2, 10, 4]\n>>> c\n[1, 2, 3, 20]\n\n",
"Never think that 'a = b' in Python means 'copy b to a'. If there are variables on both sides, you can't really know that. Instead, think of it as 'give b the additional name a'.\nIf b is an immutable object (like a number, tuple or a string), then yes, the effect is that you get a copy. But that's because when you deal with immutables (which maybe should have been called read only, unchangeable or WORM) you always get a copy, by definition. \nIf b is a mutable, you always have to do something extra to be sure you have a true copy. Always. With lists, it's as simple as a slice: a = b[:]. \nMutability is also the reason that this:\ndef myfunction(mylist=[]): \n pass\n\n... doesn't quite do what you think it does.\nIf you're from a C-background: what's left of the '=' is a pointer, always. All variables are pointers, always. If you put variables in a list: a = [b, c], you've put pointers to the values pointed to by b and c in a list pointed to by a. If you then set a[0] = d, the pointer in position 0 is now pointing to whatever d points to. \nSee also the copy-module: http://docs.python.org/library/copy.html\n"
] |
[
53,
51,
12,
4
] |
[
"Shallow Copy: (copies chunks of memory from one location to another)\na = ['one','two','three']\n\nb = a[:]\n\nb[1] = 2\n\nprint id(a), a #Output: 1077248300 ['one', 'two', 'three']\nprint id(b), b #Output: 1077248908 ['one', 2, 'three']\n\nDeep Copy: (Copies object reference)\na = ['one','two','three']\n\nb = a\n\nb[1] = 2\n\n\nprint id(a), a #Output: 1077248300 ['one', 2, 'three']\nprint id(b), b #Output: 1077248300 ['one', 2, 'three']\n\n"
] |
[
-2
] |
[
"list",
"python",
"shallow_copy"
] |
stackoverflow_0000323689_list_python_shallow_copy.txt
|
Q:
How to know all the derived classes of a parent?
Suppose you have a base class A, and this class is reimplemented by B and C.
Suppose also there's a class method A.derived() that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have class D(A): pass or class D(B): pass, now A.derived() returns [B,C,D].
How would you implement the method A.derived() ? I have the feeling that is not possible unless you use metaclasses. You can traverse the inheritance tree only from child to parent with the standard mechanism. To have the link in the other direction, you have to keep it "by hand", and this means overriding the traditional class declaration mechanics.
A:
If you define your classes as a new-style class (subclass of object) then this is possible since the subclasses are saved in __subclasses__.
class A(object):
def hello(self):
print "Hello A"
class B(A):
def hello(self):
print "Hello B"
>>> for cls in A.__subclasses__():
... print cls.__name__
...
B
I do not know exactly when this was introduced or if there are any special considerations. It does however work fine to declare a subclass in a function:
>>> def f(x):
... class C(A):
... def hello(self):
... print "Hello C"
... c = C()
... c.hello()
... print x
... for cls in A.__subclasses__():
... print cls.__name__
...
>>> f(4)
Hello C
4
B
C
However, you need to note that until the class definitions have been run the interpreter does not know about them. In the example above C is not recognized as a subclass of A until the function f is executed. But this is the same for python classes every time anyway, as I presume you are already aware of.
A:
Given the discussion on subclasses then an implementation might look like this:
class A(object):
@classmethod
def derived(cls):
return [c.__name__ for c in cls.__subclasses__()]
edit: you might also want to look at this answer to a slightly different question.
A:
Here is another implementation that will recursively print out all subclasses, with indentation.
def findsubclass(baseclass, indent=0):
if indent == 0:
print "Subclasses of %s are:" % baseclass.__name__
indent = indent + 1
for c in baseclass.__subclasses__():
print "-"*indent*4 + ">" + c.__name__
findsubclass(c, indent)
|
How to know all the derived classes of a parent?
|
Suppose you have a base class A, and this class is reimplemented by B and C.
Suppose also there's a class method A.derived() that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have class D(A): pass or class D(B): pass, now A.derived() returns [B,C,D].
How would you implement the method A.derived() ? I have the feeling that is not possible unless you use metaclasses. You can traverse the inheritance tree only from child to parent with the standard mechanism. To have the link in the other direction, you have to keep it "by hand", and this means overriding the traditional class declaration mechanics.
|
[
"If you define your classes as a new-style class (subclass of object) then this is possible since the subclasses are saved in __subclasses__.\nclass A(object):\n def hello(self):\n print \"Hello A\"\n\nclass B(A):\n def hello(self):\n print \"Hello B\"\n\n>>> for cls in A.__subclasses__():\n... print cls.__name__\n...\nB\n\nI do not know exactly when this was introduced or if there are any special considerations. It does however work fine to declare a subclass in a function:\n>>> def f(x):\n... class C(A):\n... def hello(self):\n... print \"Hello C\"\n... c = C()\n... c.hello()\n... print x\n... for cls in A.__subclasses__():\n... print cls.__name__\n...\n>>> f(4)\nHello C\n4\nB\nC\n\nHowever, you need to note that until the class definitions have been run the interpreter does not know about them. In the example above C is not recognized as a subclass of A until the function f is executed. But this is the same for python classes every time anyway, as I presume you are already aware of.\n",
"Given the discussion on subclasses then an implementation might look like this:\nclass A(object):\n @classmethod\n def derived(cls):\n return [c.__name__ for c in cls.__subclasses__()]\n\nedit: you might also want to look at this answer to a slightly different question.\n",
"Here is another implementation that will recursively print out all subclasses, with indentation.\n\ndef findsubclass(baseclass, indent=0):\n if indent == 0:\n print \"Subclasses of %s are:\" % baseclass.__name__\n indent = indent + 1\n for c in baseclass.__subclasses__():\n print \"-\"*indent*4 + \">\" + c.__name__\n findsubclass(c, indent)\n\n"
] |
[
22,
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002219998_python.txt
|
Q:
Equivalent functionality to Google Charts API from python ? (Venn Diagrams also needed!)
is there any library (for C or python) that I can use to get roughly the same functionality as I can get from Google Charts ?
I specifically need the pie diagrams (standard), multi-dataset-pie-diagrams (not-so-standard), and venn diagrams (rare)...
A:
http://pygooglechart.slowchop.com/ is a Python wrapper for the Google Charts API. Also see Pretty graphs and charts in Python
|
Equivalent functionality to Google Charts API from python ? (Venn Diagrams also needed!)
|
is there any library (for C or python) that I can use to get roughly the same functionality as I can get from Google Charts ?
I specifically need the pie diagrams (standard), multi-dataset-pie-diagrams (not-so-standard), and venn diagrams (rare)...
|
[
"http://pygooglechart.slowchop.com/ is a Python wrapper for the Google Charts API. Also see Pretty graphs and charts in Python\n"
] |
[
1
] |
[] |
[] |
[
"charts",
"python"
] |
stackoverflow_0002220929_charts_python.txt
|
Q:
Python + Komodo Edit
I am trying to get scapy to auto complete in komodo edit with no success, has anyone successfully done this?
Thanks,
Python New Comer
A:
Autocomplete in Python is a hit or miss proposition. It varies widely -- some things can be analyzed by Komodo and some can't.
If it won't autocomplete, it's probably because it relies on too many metaclass techniques that seem to baffle Komodo.
A:
If you're in virtualenv or have some tricky python paths you have to add additional import directories in:
Preferences -> Languages -> Python ->
Additional Python Import Directories
Komodo can't understand these things out of the box.
Also make sure you have following option enabled:
Preferences -> Code Intelligence ->
Include all files and directories from the project base directory
These steps would enable code completion to decent quality but as mentioned by S.Lott it is nearly impossible to implement full-featured auto-completion (like in Java or C#) in Python due its dynamic nature.
|
Python + Komodo Edit
|
I am trying to get scapy to auto complete in komodo edit with no success, has anyone successfully done this?
Thanks,
Python New Comer
|
[
"Autocomplete in Python is a hit or miss proposition. It varies widely -- some things can be analyzed by Komodo and some can't. \nIf it won't autocomplete, it's probably because it relies on too many metaclass techniques that seem to baffle Komodo.\n",
"If you're in virtualenv or have some tricky python paths you have to add additional import directories in:\n\nPreferences -> Languages -> Python ->\n Additional Python Import Directories\n\nKomodo can't understand these things out of the box.\nAlso make sure you have following option enabled:\n\nPreferences -> Code Intelligence ->\n Include all files and directories from the project base directory\n\nThese steps would enable code completion to decent quality but as mentioned by S.Lott it is nearly impossible to implement full-featured auto-completion (like in Java or C#) in Python due its dynamic nature.\n"
] |
[
1,
1
] |
[] |
[] |
[
"komodoedit",
"python",
"scapy"
] |
stackoverflow_0002218637_komodoedit_python_scapy.txt
|
Q:
Rasterizing a GDAL layer
Edit
Here is the proper way to do it, and the documentation:
import random
from osgeo import gdal, ogr
RASTERIZE_COLOR_FIELD = "__color__"
def rasterize(pixel_size=25):
# Open the data source
orig_data_source = ogr.Open("test.shp")
# Make a copy of the layer's data source because we'll need to
# modify its attributes table
source_ds = ogr.GetDriverByName("Memory").CopyDataSource(
orig_data_source, "")
source_layer = source_ds.GetLayer(0)
source_srs = source_layer.GetSpatialRef()
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create a field in the source layer to hold the features colors
field_def = ogr.FieldDefn(RASTERIZE_COLOR_FIELD, ogr.OFTReal)
source_layer.CreateField(field_def)
source_layer_def = source_layer.GetLayerDefn()
field_index = source_layer_def.GetFieldIndex(RASTERIZE_COLOR_FIELD)
# Generate random values for the color field (it's here that the value
# of the attribute should be used, but you get the idea)
for feature in source_layer:
feature.SetField(field_index, random.randint(0, 255))
source_layer.SetFeature(feature)
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', x_res,
y_res, 3, gdal.GDT_Byte)
target_ds.SetGeoTransform((
x_min, pixel_size, 0,
y_max, 0, -pixel_size,
))
if source_srs:
# Make the target raster have the same projection as the source
target_ds.SetProjection(source_srs.ExportToWkt())
else:
# Source has no projection (needs GDAL >= 1.7.0 to work)
target_ds.SetProjection('LOCAL_CS["arbitrary"]')
# Rasterize
err = gdal.RasterizeLayer(target_ds, (3, 2, 1), source_layer,
burn_values=(0, 0, 0),
options=["ATTRIBUTE=%s" % RASTERIZE_COLOR_FIELD])
if err != 0:
raise Exception("error rasterizing layer: %s" % err)
Original question
I'm looking for information on how to use osgeo.gdal.RasterizeLayer() (the docstring is very succinct, and I can't find it in the C or C++ API docs. I only found a doc for the java bindings).
I adapted a unit test and tried it on a .shp made of polygons:
import os
import sys
from osgeo import gdal, gdalconst, ogr, osr
def rasterize():
# Create a raster to rasterize into.
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', 1280, 1024, 3,
gdal.GDT_Byte)
# Create a layer to rasterize from.
cutline_ds = ogr.Open("data.shp")
# Run the algorithm.
err = gdal.RasterizeLayer(target_ds, [3,2,1], cutline_ds.GetLayer(0),
burn_values=[200,220,240])
if err != 0:
print("error:", err)
if __name__ == '__main__':
rasterize()
It runs fine, but all I obtain is a black .tif.
What's the burn_values parameter for ? Can RasterizeLayer() be used to rasterize a layer with features colored differently based on the value of an attribute ?
If it can't, what should I use ? Is AGG suitable for rendering geographic data (I want no antialiasing and a very robust renderer, able to draw very large and very small features correctly, possibly from "dirty data" (degenerate polygons, etc...), and sometimes specified in large coordinates) ?
Here, the polygons are differentiated by the value of an attribute (the colors don't matter, I just want to have a different one for each value of the attribute).
A:
EDIT: I guess I'd use qGIS python bindings: http://www.qgis.org/wiki/Python_Bindings
That's the easiest way I can think of. I remember hand rolling something before, but it's ugly. qGIS would be easier, even if you had to make a separate Windows installation (to get python to work with it) then set up an XML-RPC server to run it in a separate python process.
I you can get GDAL to rasterize properly that's great too.
I haven't used gdal for a while, but here's my guess:
burn_values is for false color if you don't use Z-values. Everything inside your polygon is [255,0,0] (red) if you use burn=[1,2,3],burn_values=[255,0,0]. I'm not sure what happens to points - they might not plot.
Use gdal.RasterizeLayer(ds,bands,layer,burn_values, options = ["BURN_VALUE_FROM=Z"]) if you want to use the Z values.
I'm just pulling this from the tests you were looking at: http://svn.osgeo.org/gdal/trunk/autotest/alg/rasterize.py
Another approach - pull the polygon objects out, and draw them using shapely, which may not be attractive. Or look into geodjango (I think it uses openlayers to plot into browsers using JavaScript).
Also, do you need to rasterize? A pdf export might be better, if you really want precision.
Actually, I think I found using Matplotlib (after extracting and projecting the features) was easier than rasterization, and I could get a lot more control.
EDIT:
A lower level approach is here:
http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/gdal2grd.py\
Finally, you can iterate over the polygons (after transforming them into a local projection), and plot them directly. But you better not have complex polygons, or you will have a bit of grief. If you have complex polygons ... you are probably best off using shapely and r-tree from http://trac.gispython.org/lab if you want to roll your own plotter.
Geodjango might be a good place to ask .. they will know a lot more than me. Do they have a mailing list? There's also lots of python mapping experts around, but none of them seem to worry about this. I guess they just plot it in qGIS or GRASS or something.
Seriously, I hope that somebody who knows what they are doing can reply.
|
Rasterizing a GDAL layer
|
Edit
Here is the proper way to do it, and the documentation:
import random
from osgeo import gdal, ogr
RASTERIZE_COLOR_FIELD = "__color__"
def rasterize(pixel_size=25):
# Open the data source
orig_data_source = ogr.Open("test.shp")
# Make a copy of the layer's data source because we'll need to
# modify its attributes table
source_ds = ogr.GetDriverByName("Memory").CopyDataSource(
orig_data_source, "")
source_layer = source_ds.GetLayer(0)
source_srs = source_layer.GetSpatialRef()
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create a field in the source layer to hold the features colors
field_def = ogr.FieldDefn(RASTERIZE_COLOR_FIELD, ogr.OFTReal)
source_layer.CreateField(field_def)
source_layer_def = source_layer.GetLayerDefn()
field_index = source_layer_def.GetFieldIndex(RASTERIZE_COLOR_FIELD)
# Generate random values for the color field (it's here that the value
# of the attribute should be used, but you get the idea)
for feature in source_layer:
feature.SetField(field_index, random.randint(0, 255))
source_layer.SetFeature(feature)
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', x_res,
y_res, 3, gdal.GDT_Byte)
target_ds.SetGeoTransform((
x_min, pixel_size, 0,
y_max, 0, -pixel_size,
))
if source_srs:
# Make the target raster have the same projection as the source
target_ds.SetProjection(source_srs.ExportToWkt())
else:
# Source has no projection (needs GDAL >= 1.7.0 to work)
target_ds.SetProjection('LOCAL_CS["arbitrary"]')
# Rasterize
err = gdal.RasterizeLayer(target_ds, (3, 2, 1), source_layer,
burn_values=(0, 0, 0),
options=["ATTRIBUTE=%s" % RASTERIZE_COLOR_FIELD])
if err != 0:
raise Exception("error rasterizing layer: %s" % err)
Original question
I'm looking for information on how to use osgeo.gdal.RasterizeLayer() (the docstring is very succinct, and I can't find it in the C or C++ API docs. I only found a doc for the java bindings).
I adapted a unit test and tried it on a .shp made of polygons:
import os
import sys
from osgeo import gdal, gdalconst, ogr, osr
def rasterize():
# Create a raster to rasterize into.
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', 1280, 1024, 3,
gdal.GDT_Byte)
# Create a layer to rasterize from.
cutline_ds = ogr.Open("data.shp")
# Run the algorithm.
err = gdal.RasterizeLayer(target_ds, [3,2,1], cutline_ds.GetLayer(0),
burn_values=[200,220,240])
if err != 0:
print("error:", err)
if __name__ == '__main__':
rasterize()
It runs fine, but all I obtain is a black .tif.
What's the burn_values parameter for ? Can RasterizeLayer() be used to rasterize a layer with features colored differently based on the value of an attribute ?
If it can't, what should I use ? Is AGG suitable for rendering geographic data (I want no antialiasing and a very robust renderer, able to draw very large and very small features correctly, possibly from "dirty data" (degenerate polygons, etc...), and sometimes specified in large coordinates) ?
Here, the polygons are differentiated by the value of an attribute (the colors don't matter, I just want to have a different one for each value of the attribute).
|
[
"EDIT: I guess I'd use qGIS python bindings: http://www.qgis.org/wiki/Python_Bindings\nThat's the easiest way I can think of. I remember hand rolling something before, but it's ugly. qGIS would be easier, even if you had to make a separate Windows installation (to get python to work with it) then set up an XML-RPC server to run it in a separate python process.\nI you can get GDAL to rasterize properly that's great too.\nI haven't used gdal for a while, but here's my guess:\nburn_values is for false color if you don't use Z-values. Everything inside your polygon is [255,0,0] (red) if you use burn=[1,2,3],burn_values=[255,0,0]. I'm not sure what happens to points - they might not plot.\nUse gdal.RasterizeLayer(ds,bands,layer,burn_values, options = [\"BURN_VALUE_FROM=Z\"]) if you want to use the Z values.\nI'm just pulling this from the tests you were looking at: http://svn.osgeo.org/gdal/trunk/autotest/alg/rasterize.py\nAnother approach - pull the polygon objects out, and draw them using shapely, which may not be attractive. Or look into geodjango (I think it uses openlayers to plot into browsers using JavaScript). \nAlso, do you need to rasterize? A pdf export might be better, if you really want precision.\nActually, I think I found using Matplotlib (after extracting and projecting the features) was easier than rasterization, and I could get a lot more control. \nEDIT:\nA lower level approach is here:\nhttp://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/gdal2grd.py\\\nFinally, you can iterate over the polygons (after transforming them into a local projection), and plot them directly. But you better not have complex polygons, or you will have a bit of grief. If you have complex polygons ... you are probably best off using shapely and r-tree from http://trac.gispython.org/lab if you want to roll your own plotter.\nGeodjango might be a good place to ask .. they will know a lot more than me. Do they have a mailing list? There's also lots of python mapping experts around, but none of them seem to worry about this. I guess they just plot it in qGIS or GRASS or something.\nSeriously, I hope that somebody who knows what they are doing can reply.\n"
] |
[
10
] |
[] |
[] |
[
"gdal",
"gis",
"python",
"rasterizing"
] |
stackoverflow_0002220749_gdal_gis_python_rasterizing.txt
|
Q:
Python: Setting an element of a Numpy matrix
I am a pretty new to python. I have created an empty matrix
a = numpy.zeros(shape=(n,n))
Now I can access each element using
a.item(i,j)
How do I set an index (i,j)?
A:
Here's how:
a[i,j] = x
A:
Or
a.itemset((i,j),x)
A:
Try this
a[i,j]=5
|
Python: Setting an element of a Numpy matrix
|
I am a pretty new to python. I have created an empty matrix
a = numpy.zeros(shape=(n,n))
Now I can access each element using
a.item(i,j)
How do I set an index (i,j)?
|
[
"Here's how:\na[i,j] = x\n\n",
"Or\na.itemset((i,j),x)\n\n",
"Try this\na[i,j]=5\n\n"
] |
[
65,
10,
3
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002220968_numpy_python.txt
|
Q:
Custom instance unpickling in Python: should the object dictionary be updated, or is replacing it OK?
When defining how objects of a certain class should be unpickled, via __setstate__, I gather that it is safe to do
def __setstate__(self, dict_returned_by_pickle):
self.__dict__.update(dict_returned_by_pickle)
when the pickled state is a dictionary. This is what I have seen in an answer here on stackoverflow.
However, is this a safety measure, taken just in case self.__dict__ contains some data when __setstate__ is called? or is it simply faster and cleaner than doing
self.__dict__ = dict_returned_by_pickle
which forces the old self.__dict__ to be garbage collected?
A:
Replacing it is fine. That is what the borg pattern does.
The original dict will be garbage collected if there are no other references to it.
|
Custom instance unpickling in Python: should the object dictionary be updated, or is replacing it OK?
|
When defining how objects of a certain class should be unpickled, via __setstate__, I gather that it is safe to do
def __setstate__(self, dict_returned_by_pickle):
self.__dict__.update(dict_returned_by_pickle)
when the pickled state is a dictionary. This is what I have seen in an answer here on stackoverflow.
However, is this a safety measure, taken just in case self.__dict__ contains some data when __setstate__ is called? or is it simply faster and cleaner than doing
self.__dict__ = dict_returned_by_pickle
which forces the old self.__dict__ to be garbage collected?
|
[
"Replacing it is fine. That is what the borg pattern does.\nThe original dict will be garbage collected if there are no other references to it.\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"pickle",
"python"
] |
stackoverflow_0002221279_dictionary_pickle_python.txt
|
Q:
Why doesn't this loop display an updated object count every five seconds?
I use this python code to output the number of Things every 5 seconds:
def my_count():
while True:
print "Number of Things: %d" % Thing.objects.count()
time.sleep(5)
my_count()
If another process generates a new Thing while my_count() is running, my_count() will keep printing the same number, even though it now has changed in the database. (But if I kill my_count() and restart it, it will display the new Thing count.)
Things are stored in a MYSQL innodb database, and this code runs on ubuntu.
Why won't my_count() display the new Thing.objects.count() without being restarted?
A:
Because Python DB API is by default in AUTOCOMMIT=OFF mode, and (at least for MySQLdb) on REPEATABLE READ isolation level. This means that behind the scenes you have an ongoing database transaction (InnoDB is transactional engine) in which the first access to given row (or maybe even table, I'm not sure) fixes "view" of this resource for the remaining part of the transaction.
To prevent this behaviour, you have to 'refresh' current transaction:
from django.db import transaction
@transaction.autocommit
def my_count():
while True:
transaction.commit()
print "Number of Things: %d" % Thing.objects.count()
time.sleep(5)
-- note that the transaction.autocommit decorator is only for entering transaction management mode (this could also be done manually using transaction.enter_transaction_management/leave_transaction_managemen functions).
One more thing - to be aware - Django's autocommit is not the same autocommit you have in database - it's completely independent. But this is out of scope for this question.
Edited on 22/01/2012
Here is a "twin answer" to a similar question.
|
Why doesn't this loop display an updated object count every five seconds?
|
I use this python code to output the number of Things every 5 seconds:
def my_count():
while True:
print "Number of Things: %d" % Thing.objects.count()
time.sleep(5)
my_count()
If another process generates a new Thing while my_count() is running, my_count() will keep printing the same number, even though it now has changed in the database. (But if I kill my_count() and restart it, it will display the new Thing count.)
Things are stored in a MYSQL innodb database, and this code runs on ubuntu.
Why won't my_count() display the new Thing.objects.count() without being restarted?
|
[
"Because Python DB API is by default in AUTOCOMMIT=OFF mode, and (at least for MySQLdb) on REPEATABLE READ isolation level. This means that behind the scenes you have an ongoing database transaction (InnoDB is transactional engine) in which the first access to given row (or maybe even table, I'm not sure) fixes \"view\" of this resource for the remaining part of the transaction.\nTo prevent this behaviour, you have to 'refresh' current transaction:\n from django.db import transaction\n\n\n @transaction.autocommit \n def my_count(): \n while True:\n transaction.commit()\n print \"Number of Things: %d\" % Thing.objects.count()\n time.sleep(5)\n\n-- note that the transaction.autocommit decorator is only for entering transaction management mode (this could also be done manually using transaction.enter_transaction_management/leave_transaction_managemen functions).\nOne more thing - to be aware - Django's autocommit is not the same autocommit you have in database - it's completely independent. But this is out of scope for this question.\nEdited on 22/01/2012\nHere is a \"twin answer\" to a similar question.\n"
] |
[
16
] |
[] |
[] |
[
"django",
"mysql",
"python"
] |
stackoverflow_0002221247_django_mysql_python.txt
|
Q:
Retrieving many-to-many relation properties using SQLAlchemy
I have a many-to-many relationship in which the relation-table contains more columns than only the primary key. As an example, consider a slide show system in which each image could have it's own timeout, and a different timeout depending on the slideshow. A daft example, but it will have to do for the sake of illustration ;)
So I imagine I would do something like the following (using Declarative):
show_has_image = Table( 'show_has_image',
DeclarativeBase.metadata,
Column( 'show_id', Integer, ForeignKey( 'show.id' ) ),
Column( 'image_id', Integer, ForeignKey( 'image.id' ) ),
Column( 'timeout', Integer, default=5 ),
PrimaryKeyConstraint( 'show_id', 'image_id' )
)
class Show(DeclarativeBase):
__tablename__ = "show"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
class Image(DeclarativeBase):
__tablename__ = "image"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
data = Column(Binary, nullable = True)
show = relation( "Show",
secondary=show_has_image,
backref="images" )
How would I access the "timeout" value? I cannot find anything in the docs about this.
So far, retrieving the images is straightforward:
show = DBSession.query(Show).filter_by(id=show_id).one()
for image in show.images:
print image.name
# print image.timeout <--- Obviously this cannot work, as SA has no idea
# how to map this field.
I'd be more than happy to have it work the way I just outlined in the previous code. Granted, I could add a timeout property to the Image class which would fetch the value dynamically. But that would result in unnecessary SQL queries.
I'd rather have it all returned in a single query. In SQL it's easy:
SELECT i.name, si.timeout
FROM show s
INNER JOIN show_has_image si ON (si.show_id = s.id)
INNER JOIN image i ON (si.image_id = i.id)
WHERE s.id = :show_id
A:
You can define intermediate model based on show_has_image table (use composite primary key) and define relations to it. Then use association_proxy to define Show.images property.
|
Retrieving many-to-many relation properties using SQLAlchemy
|
I have a many-to-many relationship in which the relation-table contains more columns than only the primary key. As an example, consider a slide show system in which each image could have it's own timeout, and a different timeout depending on the slideshow. A daft example, but it will have to do for the sake of illustration ;)
So I imagine I would do something like the following (using Declarative):
show_has_image = Table( 'show_has_image',
DeclarativeBase.metadata,
Column( 'show_id', Integer, ForeignKey( 'show.id' ) ),
Column( 'image_id', Integer, ForeignKey( 'image.id' ) ),
Column( 'timeout', Integer, default=5 ),
PrimaryKeyConstraint( 'show_id', 'image_id' )
)
class Show(DeclarativeBase):
__tablename__ = "show"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
class Image(DeclarativeBase):
__tablename__ = "image"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
data = Column(Binary, nullable = True)
show = relation( "Show",
secondary=show_has_image,
backref="images" )
How would I access the "timeout" value? I cannot find anything in the docs about this.
So far, retrieving the images is straightforward:
show = DBSession.query(Show).filter_by(id=show_id).one()
for image in show.images:
print image.name
# print image.timeout <--- Obviously this cannot work, as SA has no idea
# how to map this field.
I'd be more than happy to have it work the way I just outlined in the previous code. Granted, I could add a timeout property to the Image class which would fetch the value dynamically. But that would result in unnecessary SQL queries.
I'd rather have it all returned in a single query. In SQL it's easy:
SELECT i.name, si.timeout
FROM show s
INNER JOIN show_has_image si ON (si.show_id = s.id)
INNER JOIN image i ON (si.image_id = i.id)
WHERE s.id = :show_id
|
[
"You can define intermediate model based on show_has_image table (use composite primary key) and define relations to it. Then use association_proxy to define Show.images property.\n"
] |
[
1
] |
[] |
[] |
[
"declarative",
"python",
"sql",
"sqlalchemy",
"turbogears"
] |
stackoverflow_0002217465_declarative_python_sql_sqlalchemy_turbogears.txt
|
Q:
Independent instances of 'random'
The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that?
class RandomSeeded:
def __init__(self, seed):
import random as r1
self.random = r1
self.random.seed(seed)
def get(self):
print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])
class Random:
def __init__(self):
import random as r2
self.random = r2
self.random.seed()
def get(self):
print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])
if __name__ == '__main__':
t = RandomSeeded('asdf')
t.get() # random is seeded within t
s = Random()
s.get()
t.get() # random should still be seeded within t, but is no longer
A:
Class random.Random exists specifically to allow the behavior you want -- modules are intrinsically singletons, but classes are meant to be multiply instantiated, so both kinds of needs are covered.
Should you ever need an independent copy of a module (which you definitely don't in the case of random!), try using copy.deepcopy on it -- in many cases it will work. However, the need is very rare, because modules don't normally keep global mutable states except by keeping one privileged instance of a class they also offer for "outside consumption" (other examples besided random include fileinput).
A:
For the seeded random numbers, make your own instance of random.Random. The random documentation explains this class, which the module depends on a single instance of when you use the functions directly within it.
A:
Sadly, having two independent RNG's is can be less random than having a single RNG using an "offset" into the generated sequence.
Using an "offset" means you have to generate both complete sequences of samples, and then use them for your simulation. Something like this.
def makeSequences( sequences=2, size=1000000 ):
g = random.Random()
return [ [ g.random() for g in xrange(size) ] for s in xrange(sequences) ] ]
t, s = makeSequences( 2 )
RNG's can only be proven to have desirable randomness properties for a single seed and a single sequence of numbers. Because two parallel sequences use the same constants for the multiplier and modulus, there's a chance that they can have a detectable correlation with each other.
|
Independent instances of 'random'
|
The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that?
class RandomSeeded:
def __init__(self, seed):
import random as r1
self.random = r1
self.random.seed(seed)
def get(self):
print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])
class Random:
def __init__(self):
import random as r2
self.random = r2
self.random.seed()
def get(self):
print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])
if __name__ == '__main__':
t = RandomSeeded('asdf')
t.get() # random is seeded within t
s = Random()
s.get()
t.get() # random should still be seeded within t, but is no longer
|
[
"Class random.Random exists specifically to allow the behavior you want -- modules are intrinsically singletons, but classes are meant to be multiply instantiated, so both kinds of needs are covered.\nShould you ever need an independent copy of a module (which you definitely don't in the case of random!), try using copy.deepcopy on it -- in many cases it will work. However, the need is very rare, because modules don't normally keep global mutable states except by keeping one privileged instance of a class they also offer for \"outside consumption\" (other examples besided random include fileinput).\n",
"For the seeded random numbers, make your own instance of random.Random. The random documentation explains this class, which the module depends on a single instance of when you use the functions directly within it.\n",
"Sadly, having two independent RNG's is can be less random than having a single RNG using an \"offset\" into the generated sequence. \nUsing an \"offset\" means you have to generate both complete sequences of samples, and then use them for your simulation. Something like this.\ndef makeSequences( sequences=2, size=1000000 ):\n g = random.Random()\n return [ [ g.random() for g in xrange(size) ] for s in xrange(sequences) ] ]\n\nt, s = makeSequences( 2 )\n\nRNG's can only be proven to have desirable randomness properties for a single seed and a single sequence of numbers. Because two parallel sequences use the same constants for the multiplier and modulus, there's a chance that they can have a detectable correlation with each other.\n"
] |
[
21,
7,
4
] |
[] |
[] |
[
"class",
"module",
"python",
"random",
"seed"
] |
stackoverflow_0002219436_class_module_python_random_seed.txt
|
Q:
How to refer to a method name from with a method in Python?
Say I have the following class defined with the method foo:
class MyClass:
def foo(self):
print "My name is %s" % __name__
Now when I call foo() I expect/want to see this printed out
My name is foo
However I get
My name is __main__
And if I was to put the class definition into a module called FooBar I would get
My name is FooBar
However if I do
m = MyClass()
print m.foo.__name__
I get exactly what I want which is
My name is foo
Can someone please help explain why __name__ refers to the module and not the method name ?
Is there an easy way to get the method name?
Many thanks
A:
This does what you're after:
from inspect import currentframe, getframeinfo
class MyClass:
def foo(self):
print "My name is %s" % getframeinfo(currentframe())[2]
A:
Names always refer to local variables or (if one doesn't exist) then global variables. There is a a global __name__ that has the module's name.
class MyClass:
def foo(self):
print "My name is %s" % MyClass.foo.__name__
Of course, that's redundant and almost entirely pointless. Just type out the method name:
class MyClass:
def foo(self):
print "My name is %s" % "foo"
print "My name is foo"
A:
__name__ refers to the module because that's what it's supposed to do. The only way to get at the currently running function would be to introspect the stack.
A:
The other answers explain it quite well so I contribute with a more concrete example.
name.py
def foo():
print "name in foo",__name__
foo()
print "foo's name",foo.__name__
print "name at top",__name__
Output
name in foo __main__
foo's name foo
name at top __main__
name2.py
import name
Output
name in foo name
foo's name foo
name at top name
Notice how the __name__ refers to built-in property of the module? Which is __main__ if the module is run directly, or the name of the module if its imported.
You should have run across the if __name__=="__main__": snippet.
You can find the relevant docs here, go check them out. Good luck! :)
A:
Use introspection with the inspect module.
import inspect
class MyClass:
def foo(self):
print "My name is %s" % inspect.stack()[0][3]
A:
Have a look at the the inspect module.
Try:
>>> import inspect
>>> def foo():
... print inspect.getframeinfo(inspect.currentframe())[2]
...
>>> foo()
foo
or:
>>> def foo2():
... print inspect.stack()[0][3]
...
>>> foo2()
foo2
|
How to refer to a method name from with a method in Python?
|
Say I have the following class defined with the method foo:
class MyClass:
def foo(self):
print "My name is %s" % __name__
Now when I call foo() I expect/want to see this printed out
My name is foo
However I get
My name is __main__
And if I was to put the class definition into a module called FooBar I would get
My name is FooBar
However if I do
m = MyClass()
print m.foo.__name__
I get exactly what I want which is
My name is foo
Can someone please help explain why __name__ refers to the module and not the method name ?
Is there an easy way to get the method name?
Many thanks
|
[
"This does what you're after:\n\nfrom inspect import currentframe, getframeinfo\n\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % getframeinfo(currentframe())[2]\n\n",
"Names always refer to local variables or (if one doesn't exist) then global variables. There is a a global __name__ that has the module's name.\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % MyClass.foo.__name__\n\nOf course, that's redundant and almost entirely pointless. Just type out the method name:\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % \"foo\"\n print \"My name is foo\"\n\n",
"__name__ refers to the module because that's what it's supposed to do. The only way to get at the currently running function would be to introspect the stack.\n",
"The other answers explain it quite well so I contribute with a more concrete example.\nname.py\ndef foo():\n print \"name in foo\",__name__\n\nfoo()\nprint \"foo's name\",foo.__name__\nprint \"name at top\",__name__\n\nOutput\nname in foo __main__\nfoo's name foo\nname at top __main__\n\nname2.py\nimport name\n\nOutput\nname in foo name\nfoo's name foo\nname at top name\n\nNotice how the __name__ refers to built-in property of the module? Which is __main__ if the module is run directly, or the name of the module if its imported. \nYou should have run across the if __name__==\"__main__\": snippet.\nYou can find the relevant docs here, go check them out. Good luck! :)\n",
"Use introspection with the inspect module.\nimport inspect\n\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % inspect.stack()[0][3]\n\n",
"Have a look at the the inspect module.\nTry:\n>>> import inspect\n>>> def foo():\n... print inspect.getframeinfo(inspect.currentframe())[2]\n...\n>>> foo()\nfoo\n\nor:\n>>> def foo2():\n... print inspect.stack()[0][3]\n...\n>>> foo2()\nfoo2\n\n"
] |
[
11,
4,
3,
2,
1,
1
] |
[
"This will do it:\n(You need to refer to self.__class__._name__.)\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % self.__class__.__name__\n\n"
] |
[
-2
] |
[
"introspection",
"methods",
"python"
] |
stackoverflow_0002222044_introspection_methods_python.txt
|
Q:
The ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} syntax doesn't work in a Mako template
In a Mako template, I need to do something like:
${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}}
When A do that, I get this error:
SyntaxException: (SyntaxError) unexpected EOF while parsing
(, line 1) ("'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'") in file…
How do I fix this issue?
I need to use this syntax in translated text:
$(_(u'foo bar %(a)s ... %(b)s) % { ... })
A:
A work-around is to pass the dict object in a different way. For example:
from mako.template import Template
print Template("${'foo %(a)s bar %(b)s' % data}").render(data=dict(a='Alpha',b='Beta'))
|
The ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} syntax doesn't work in a Mako template
|
In a Mako template, I need to do something like:
${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}}
When A do that, I get this error:
SyntaxException: (SyntaxError) unexpected EOF while parsing
(, line 1) ("'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'") in file…
How do I fix this issue?
I need to use this syntax in translated text:
$(_(u'foo bar %(a)s ... %(b)s) % { ... })
|
[
"A work-around is to pass the dict object in a different way. For example:\nfrom mako.template import Template\n\nprint Template(\"${'foo %(a)s bar %(b)s' % data}\").render(data=dict(a='Alpha',b='Beta'))\n\n"
] |
[
0
] |
[
"Solution:\n${'foo %(a)s bar %(b)s' % dict((('a', '1'), ('b', '2'),))}\n\n"
] |
[
-1
] |
[
"mako",
"python",
"templates"
] |
stackoverflow_0002221910_mako_python_templates.txt
|
Q:
PyQt4 QDialog connections not being made
I am working on an application using PyQt4 and the designer it provides. I have a main window application that works fine, but I wanted to create custom message dialogs. I designed a dialog and set up some custom signal/slot connections in the __init__ method and wrote an if __name__=='__main__': and had a test. The custom slots work fine. However, when I create an instance of my dialog from my main window application, none of the buttons work. Here is my dialog:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import encode_dialog_ui
# Ui_EncodeDialog is the python class generated by pyuic4 from the Designer
class EncodeDialog(encode_dialog_ui.Ui_EncodeDialog):
def __init__(self, parent, in_org_im, txt_file, in_enc_im):
self.qd = QDialog(parent)
self.setupUi(self.qd)
self.qd.show()
self.message = (txt_file.split("/")[-1] + " encoded into " +
in_org_im.split("/")[-1] + " and written to " +
in_enc_im.split("/")[-1] + ".")
QObject.connect(self.view_image_button, SIGNAL("clicked()"),
self.on_view_image_button_press)
self.org_im = in_org_im
self.enc_im = in_enc_im
self.encoded_label.setText(self.message)
def on_view_image_button_press(self):
print "hello world"
if __name__ == '__main__':
app = QApplication(sys.argv)
tmp = QMainWindow()
myg = EncodeDialog(tmp,'flower2.png','b','flower.png')
app.exec_()
If I run this class it works fine, and pressing the view_image_button prints hello world to the console. However when I use the call
#self.mw is a QMainWindow, the rest are strings
EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
in my main window class, the dialog displays correctly but the view_image_button does nothing when clicked. I have googled for a solution, but couldn't find anything useful. Let me know if you need any more information. Any help on this would be appreciated!
As requested below is some more code from my main window class for brevity's sake I have added ellipses to remove code that seemed irrelevant. If no one can think of anything still, I will add more. (If indenting is a little off, it happened in copy-pasting. The orignal code is correct)
class MyGUI(MainWindow.Ui_MainWindow):
def __init__(self):
self.mw = QMainWindow()
self.setupUi(self.mw)
self.mw.show()
self.encode_red_bits = 1
self.encode_blue_bits = 1
self.encode_green_bits = 1
self.decode_red_bits = 1
self.decode_blue_bits = 1
self.decode_green_bits = 1
self.encode_image_filename = ""
self.encode_new_image_filename = ""
self.encode_txt_filename = ""
self.decode_image_filename = ""
self.decode_txt_filename = ""
# Encode events
...
QObject.connect(self.encode_button, SIGNAL("clicked()"),
self.on_encode_button_press)
# Decode events
...
# Encode event handlers
...
def on_encode_button_press(self):
tmp = QErrorMessage(self.mw)
if (self.encode_image_filename != "" and
self.encode_new_image_filename != "" and
self.encode_txt_filename != ""):
try:
im = Steganography.encode(self.encode_image_filename, self.encode_txt_filename,
self.encode_red_bits, self.encode_green_bits,
self.encode_blue_bits)
im.save(self.encode_new_image_filename)
encode_dialog.EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
except Steganography.FileTooLargeException:
tmp.showMessage(self.encode_txt_filename.split("/")[-1] +
" is to large to be encoded into " +
self.encode_image_filename.split("/")[-1])
else:
tmp.showMessage("Please specify all filenames.")
# Decode event handlers
...
if __name__ == '__main__':
app = QApplication(sys.argv)
myg = MyGUI()
app.exec_()
A:
It feels like the signal is just not getting passed from the parent down to your child QDIalog.
Try these suggestions:
Use the new method for connecting signals
Instead of extending the classes pyuic created, extend the actual QT classes and call the ones generated by pyuic
Your new code will look something like this:
class MyGUI(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.mw = MainWindow.Ui_MainWindow()
self.mw.setupUi(self)
self.mw.show()
...
self.encode_button.clicked.connect(self.on_encode_button_press)
...
class EncodeDialog(QDialog):
def __init__(self, parent, in_org_im, txt_file, in_enc_im):
QDialog.__init__(self, parent)
self.qd = encode_dialog_ui.Ui_EncodeDialog()
self.qd.setupUi(self)
self.qd.show()
...
self.view_image_button.clicked.connect(self.on_view_image_button_press)
...
|
PyQt4 QDialog connections not being made
|
I am working on an application using PyQt4 and the designer it provides. I have a main window application that works fine, but I wanted to create custom message dialogs. I designed a dialog and set up some custom signal/slot connections in the __init__ method and wrote an if __name__=='__main__': and had a test. The custom slots work fine. However, when I create an instance of my dialog from my main window application, none of the buttons work. Here is my dialog:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import encode_dialog_ui
# Ui_EncodeDialog is the python class generated by pyuic4 from the Designer
class EncodeDialog(encode_dialog_ui.Ui_EncodeDialog):
def __init__(self, parent, in_org_im, txt_file, in_enc_im):
self.qd = QDialog(parent)
self.setupUi(self.qd)
self.qd.show()
self.message = (txt_file.split("/")[-1] + " encoded into " +
in_org_im.split("/")[-1] + " and written to " +
in_enc_im.split("/")[-1] + ".")
QObject.connect(self.view_image_button, SIGNAL("clicked()"),
self.on_view_image_button_press)
self.org_im = in_org_im
self.enc_im = in_enc_im
self.encoded_label.setText(self.message)
def on_view_image_button_press(self):
print "hello world"
if __name__ == '__main__':
app = QApplication(sys.argv)
tmp = QMainWindow()
myg = EncodeDialog(tmp,'flower2.png','b','flower.png')
app.exec_()
If I run this class it works fine, and pressing the view_image_button prints hello world to the console. However when I use the call
#self.mw is a QMainWindow, the rest are strings
EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
in my main window class, the dialog displays correctly but the view_image_button does nothing when clicked. I have googled for a solution, but couldn't find anything useful. Let me know if you need any more information. Any help on this would be appreciated!
As requested below is some more code from my main window class for brevity's sake I have added ellipses to remove code that seemed irrelevant. If no one can think of anything still, I will add more. (If indenting is a little off, it happened in copy-pasting. The orignal code is correct)
class MyGUI(MainWindow.Ui_MainWindow):
def __init__(self):
self.mw = QMainWindow()
self.setupUi(self.mw)
self.mw.show()
self.encode_red_bits = 1
self.encode_blue_bits = 1
self.encode_green_bits = 1
self.decode_red_bits = 1
self.decode_blue_bits = 1
self.decode_green_bits = 1
self.encode_image_filename = ""
self.encode_new_image_filename = ""
self.encode_txt_filename = ""
self.decode_image_filename = ""
self.decode_txt_filename = ""
# Encode events
...
QObject.connect(self.encode_button, SIGNAL("clicked()"),
self.on_encode_button_press)
# Decode events
...
# Encode event handlers
...
def on_encode_button_press(self):
tmp = QErrorMessage(self.mw)
if (self.encode_image_filename != "" and
self.encode_new_image_filename != "" and
self.encode_txt_filename != ""):
try:
im = Steganography.encode(self.encode_image_filename, self.encode_txt_filename,
self.encode_red_bits, self.encode_green_bits,
self.encode_blue_bits)
im.save(self.encode_new_image_filename)
encode_dialog.EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
except Steganography.FileTooLargeException:
tmp.showMessage(self.encode_txt_filename.split("/")[-1] +
" is to large to be encoded into " +
self.encode_image_filename.split("/")[-1])
else:
tmp.showMessage("Please specify all filenames.")
# Decode event handlers
...
if __name__ == '__main__':
app = QApplication(sys.argv)
myg = MyGUI()
app.exec_()
|
[
"It feels like the signal is just not getting passed from the parent down to your child QDIalog.\nTry these suggestions:\n\nUse the new method for connecting signals\nInstead of extending the classes pyuic created, extend the actual QT classes and call the ones generated by pyuic\n\nYour new code will look something like this:\n class MyGUI(QMainWindow):\n def __init__(self, parent=None):\n QMainWindow.__init__(self, parent)\n self.mw = MainWindow.Ui_MainWindow()\n self.mw.setupUi(self)\n self.mw.show()\n ...\n self.encode_button.clicked.connect(self.on_encode_button_press)\n ...\n\n class EncodeDialog(QDialog):\n def __init__(self, parent, in_org_im, txt_file, in_enc_im):\n QDialog.__init__(self, parent)\n self.qd = encode_dialog_ui.Ui_EncodeDialog()\n self.qd.setupUi(self)\n self.qd.show()\n ...\n self.view_image_button.clicked.connect(self.on_view_image_button_press)\n ...\n\n"
] |
[
0
] |
[] |
[] |
[
"pyqt4",
"python",
"qdialog",
"signals_slots"
] |
stackoverflow_0002169325_pyqt4_python_qdialog_signals_slots.txt
|
Q:
Printing to a file from a list of lists in Python
I am trying to print to a file that will look like:
'A'
'1'
'B'
'2'
'C'
'3'
Given the code below, however, the result is :
['A']
['B']
['C']
This is probably a 'softball' question, but what am I doing wrong here?
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
itr = iter(listoflists)
f = open ('order.txt','w')
while True:
try:
itr.next()
s = str(itr.next())
f.write(str('\n'))
f.write(s)
except StopIteration:
break
f.close()
A:
First of all, don't use iter and next(), that's what for is for. Secondly, you are actually writing a list to the file, not its contents. So you could either print the first element of the list (i.e. l1[0]) or iterate through all the inner lists elements.
Your code should look like this:
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
f = open ('order.txt','w')
for inner_list in listoflists:
for element in inner_list:
f.write(element+'\n')
f.close()
A:
I think the best way to solve this is just with a basic nested loop. Try this:
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
f = open("out.txt","w")
# for each list and
# for each item in the list;
# write the item to the file, separated by a comma
for list in listoflists:
for item in list:
f.write(item+",")
f.close()
Out.txt now holds:
1,A,2,B,3,C,
Oh, and no Python question is complete without a one-liner solution (this also removes the trailing comma from my initial response).
open("out.txt","w").write(",".join(("".join(i) for i in listoflists)))
Out.txt now holds:
1,A,2,B,3,C
A:
Your code could be a lot simpler:
for list in listoflists:
f.write(str(list))
f.write('\n')
But, this is going to print something like ['1']. It seems like you want something more like:
for list in listoflists:
f.write(str(list[0]))
f.write('\n')
Also, why do you have a bunch of single-element lists? Couldn't you put all the elements into one list?
A:
The simple reason why you are getting the wrong file contents is because you are calling iter twice. Lines 15-16 are:
itr.next()
s = str(itr.next())
For more Pythonic printing semantics, see the other answers
A:
Including the quotes in the output is a bit odd, but if you insist:
for entry in listoflists:
print >>f, repr(entry[0])
You don't specify what will happen if the inner list does not have just one element, so any other possibility is ignored here.
A:
You can simply iterate through all list elements with itertools.chain (documented here):
import itertools
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
chainedlists = itertools.chain(l1,l2,l3,l4,l5,l6)
with open ('order.txt','wt') as f:
for element in chainedlists:
# Change this how you want it to be formatted, it will output
# a string "a" as 'a' (with the quotes)
f.write("%s\n" % repr(element))
|
Printing to a file from a list of lists in Python
|
I am trying to print to a file that will look like:
'A'
'1'
'B'
'2'
'C'
'3'
Given the code below, however, the result is :
['A']
['B']
['C']
This is probably a 'softball' question, but what am I doing wrong here?
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
itr = iter(listoflists)
f = open ('order.txt','w')
while True:
try:
itr.next()
s = str(itr.next())
f.write(str('\n'))
f.write(s)
except StopIteration:
break
f.close()
|
[
"First of all, don't use iter and next(), that's what for is for. Secondly, you are actually writing a list to the file, not its contents. So you could either print the first element of the list (i.e. l1[0]) or iterate through all the inner lists elements.\nYour code should look like this:\nl1 = ['1']\nl2 = ['A']\nl3 = ['2']\nl4 = ['B']\nl5 = ['3']\nl6 = ['C']\n\nlistoflists = [l1,l2,l3,l4,l5,l6]\n\nf = open ('order.txt','w')\n\nfor inner_list in listoflists:\n for element in inner_list:\n f.write(element+'\\n')\n\nf.close()\n\n",
"I think the best way to solve this is just with a basic nested loop. Try this:\nl1 = ['1']\nl2 = ['A']\nl3 = ['2']\nl4 = ['B']\nl5 = ['3']\nl6 = ['C']\nlistoflists = [l1,l2,l3,l4,l5,l6]\n\nf = open(\"out.txt\",\"w\")\n\n# for each list and\n# for each item in the list;\n# write the item to the file, separated by a comma\nfor list in listoflists: \n for item in list: \n f.write(item+\",\") \n\nf.close()\n\nOut.txt now holds:\n1,A,2,B,3,C,\n\n\nOh, and no Python question is complete without a one-liner solution (this also removes the trailing comma from my initial response).\nopen(\"out.txt\",\"w\").write(\",\".join((\"\".join(i) for i in listoflists)))\n\nOut.txt now holds:\n1,A,2,B,3,C\n\n",
"Your code could be a lot simpler:\nfor list in listoflists:\n f.write(str(list))\n f.write('\\n')\n\nBut, this is going to print something like ['1']. It seems like you want something more like:\nfor list in listoflists:\n f.write(str(list[0]))\n f.write('\\n')\n\nAlso, why do you have a bunch of single-element lists? Couldn't you put all the elements into one list?\n",
"The simple reason why you are getting the wrong file contents is because you are calling iter twice. Lines 15-16 are:\nitr.next()\ns = str(itr.next())\n\nFor more Pythonic printing semantics, see the other answers\n",
"Including the quotes in the output is a bit odd, but if you insist:\nfor entry in listoflists:\n print >>f, repr(entry[0])\n\nYou don't specify what will happen if the inner list does not have just one element, so any other possibility is ignored here.\n",
"You can simply iterate through all list elements with itertools.chain (documented here):\nimport itertools\n\nl1 = ['1']\nl2 = ['A']\nl3 = ['2']\nl4 = ['B']\nl5 = ['3']\nl6 = ['C']\n\nchainedlists = itertools.chain(l1,l2,l3,l4,l5,l6)\n\nwith open ('order.txt','wt') as f:\n for element in chainedlists:\n # Change this how you want it to be formatted, it will output\n # a string \"a\" as 'a' (with the quotes)\n f.write(\"%s\\n\" % repr(element))\n\n"
] |
[
7,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"file",
"iteration",
"list",
"python"
] |
stackoverflow_0002222189_file_iteration_list_python.txt
|
Q:
Making your own statements
Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject?
A:
No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.
A:
You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What you could do perhaps is write a something like a DSL (domain-specific language) and something that translates your keyword statements into proper python statements, which might be an easier route.
A:
While you can't modify the syntax of Python itself (without recompiling as Alex has mentioned), you can use metaprogramming techniques. Below is a link to a presentation on creating a DSL in Python.
http://blog.brianbeck.com/post/53538107/python-dsl-i
If you're not married to Python, Ruby is a great language for defining DSL's, as it has broader metaprogramming capabilities.
http://www.themomorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-rails
A:
Ren'Py is an example of an extension for Python that allows custom statements by implementing its own parser and compiler.
A:
There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages.
|
Making your own statements
|
Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject?
|
[
"No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.\n",
"You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What you could do perhaps is write a something like a DSL (domain-specific language) and something that translates your keyword statements into proper python statements, which might be an easier route.\n",
"While you can't modify the syntax of Python itself (without recompiling as Alex has mentioned), you can use metaprogramming techniques. Below is a link to a presentation on creating a DSL in Python.\nhttp://blog.brianbeck.com/post/53538107/python-dsl-i\nIf you're not married to Python, Ruby is a great language for defining DSL's, as it has broader metaprogramming capabilities.\nhttp://www.themomorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-rails\n",
"Ren'Py is an example of an extension for Python that allows custom statements by implementing its own parser and compiler.\n",
"There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages. \n"
] |
[
10,
3,
2,
2,
1
] |
[] |
[] |
[
"keyword",
"python",
"statements",
"syntax"
] |
stackoverflow_0002222843_keyword_python_statements_syntax.txt
|
Q:
cx_Freeze ImportError: cannot import name
I'm trying create an executable for Windows for a GUI application in tkinter using the ttk module. I made an exe with cx_freeze, but when I run the app in the console it gives me the following error:
D:\My Dropbox\python\SAR Calculator\src\dist_tk>
Traceback (most recent call last):
File "C:\Python31\lib\site-packages\cx_Freeze\
7, in <module>
exec(code, m.__dict__)
File "sarcalc_tk.py", line 14, in <module>
File "C:\Python31\lib\tkinter\__init__.py", li
from tkinter import _fix
ImportError: cannot import name _fix
Here are lines 14 and 15 from my code:
import tkinter as tk
import tkinter.ttk as ttk
A:
Looks like cx_freeze doesn't realize it should include the tkinter._fix module, which is conditionally imported by tkinter/__init__.py. You can tell it to include that module explicitly with the --include-modules command-line argument, or the includes keyword argument to cx_Freeze.Executable in your setup.py
|
cx_Freeze ImportError: cannot import name
|
I'm trying create an executable for Windows for a GUI application in tkinter using the ttk module. I made an exe with cx_freeze, but when I run the app in the console it gives me the following error:
D:\My Dropbox\python\SAR Calculator\src\dist_tk>
Traceback (most recent call last):
File "C:\Python31\lib\site-packages\cx_Freeze\
7, in <module>
exec(code, m.__dict__)
File "sarcalc_tk.py", line 14, in <module>
File "C:\Python31\lib\tkinter\__init__.py", li
from tkinter import _fix
ImportError: cannot import name _fix
Here are lines 14 and 15 from my code:
import tkinter as tk
import tkinter.ttk as ttk
|
[
"Looks like cx_freeze doesn't realize it should include the tkinter._fix module, which is conditionally imported by tkinter/__init__.py. You can tell it to include that module explicitly with the --include-modules command-line argument, or the includes keyword argument to cx_Freeze.Executable in your setup.py\n"
] |
[
5
] |
[] |
[] |
[
"cx_freeze",
"exe",
"python",
"python_3.x",
"tkinter"
] |
stackoverflow_0002223128_cx_freeze_exe_python_python_3.x_tkinter.txt
|
Q:
Deciding on a blog URL scheme with regard to python performance
I'm writing a blog in Python and have come to the point where I have to decide on the URL scheme to use. It's tempting to just list the entries start to end, like:
http://myblog.com/1
http://myblog.com/2
...
http://myblog.com/1568
And on the server side I would just have the blog entries in a python list. My fear though is that it will become slow to traverse to the requested entry as the list grows. I don't know how big (as in memory) the entries will be so I can't store them in a lower level array (if there even is in python) or fixed size table of any sort.
The other option I'm thinking of is to prefix the entry URLs with a year:
http://myblog.com/2010/1
http://myblog.com/2010/2
http://myblog.com/2011/1
I guess this speeds things up as I could store the entries in a tree structure:
entries = {
'2010': [entry1, entry2, ...],
'2012': [entry1, entry2, ...]
}
How would you do it? I leave the discussion open as I'm interested in how people think here.
Thanks!
A:
The performance difference between the two will be negligible. The overhead of the list or dictionary will be much smaller than the size of the text in the entries.
Keeping everything in memory is not a good solution though. You should persist the entries to disk (database, flat file, etc.), then (if necessary) use a cache to keep the most frequently accessed entries in memory.
A:
What about mapping URLs to blog entries using a dictionary? This is simple, and dictionary has O(1) lookup so it would be fast even if your blog had many entries.
|
Deciding on a blog URL scheme with regard to python performance
|
I'm writing a blog in Python and have come to the point where I have to decide on the URL scheme to use. It's tempting to just list the entries start to end, like:
http://myblog.com/1
http://myblog.com/2
...
http://myblog.com/1568
And on the server side I would just have the blog entries in a python list. My fear though is that it will become slow to traverse to the requested entry as the list grows. I don't know how big (as in memory) the entries will be so I can't store them in a lower level array (if there even is in python) or fixed size table of any sort.
The other option I'm thinking of is to prefix the entry URLs with a year:
http://myblog.com/2010/1
http://myblog.com/2010/2
http://myblog.com/2011/1
I guess this speeds things up as I could store the entries in a tree structure:
entries = {
'2010': [entry1, entry2, ...],
'2012': [entry1, entry2, ...]
}
How would you do it? I leave the discussion open as I'm interested in how people think here.
Thanks!
|
[
"The performance difference between the two will be negligible. The overhead of the list or dictionary will be much smaller than the size of the text in the entries.\nKeeping everything in memory is not a good solution though. You should persist the entries to disk (database, flat file, etc.), then (if necessary) use a cache to keep the most frequently accessed entries in memory.\n",
"What about mapping URLs to blog entries using a dictionary? This is simple, and dictionary has O(1) lookup so it would be fast even if your blog had many entries.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"url"
] |
stackoverflow_0002218363_python_url.txt
|
Q:
How to turn a SVG image to a SDL surface or an array of RGBA pixels with python?
I'm guessing it has to be done with the aid of some sort of framework. Google gives libCairo as the most common result, but that is way too many dependencies.
I mean something that would work on Win/Lin/OSX, be non-GPL, python-compatible, freely re-distributable. And preferably a few hundred KB in size.
Thing is, it doesn't even have to support the full SVG spec. Just lines, shapes, gradient fills and blur.
Alternatively, is there any vector format that could be more easily used?
A:
Try python-rsvg from http://www.cairographics.org/pyrsvg/
Too many dependencies? Really? http://www.cairographics.org/download/ has Windows binaries. It depends on libpng and zlib. Don't know about getting the Python bindings up though. If the bindings are too hard, you could just shell out to rsvg file.svg output.png.
You might try searching PyPi for 'svg': http://pypi.python.org/pypi?%3Aaction=search&term=svg&submit=search . There is a SVG loader for OpenGL in there somewhere.
|
How to turn a SVG image to a SDL surface or an array of RGBA pixels with python?
|
I'm guessing it has to be done with the aid of some sort of framework. Google gives libCairo as the most common result, but that is way too many dependencies.
I mean something that would work on Win/Lin/OSX, be non-GPL, python-compatible, freely re-distributable. And preferably a few hundred KB in size.
Thing is, it doesn't even have to support the full SVG spec. Just lines, shapes, gradient fills and blur.
Alternatively, is there any vector format that could be more easily used?
|
[
"Try python-rsvg from http://www.cairographics.org/pyrsvg/\nToo many dependencies? Really? http://www.cairographics.org/download/ has Windows binaries. It depends on libpng and zlib. Don't know about getting the Python bindings up though. If the bindings are too hard, you could just shell out to rsvg file.svg output.png.\nYou might try searching PyPi for 'svg': http://pypi.python.org/pypi?%3Aaction=search&term=svg&submit=search . There is a SVG loader for OpenGL in there somewhere.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"rgb",
"sdl",
"svg"
] |
stackoverflow_0002198499_python_rgb_sdl_svg.txt
|
Q:
Python sort parallel arrays in place?
Is there an easy (meaning without rolling one's own sorting function) way to sort parallel lists without unnecessary copying in Python? For example:
foo = range(5)
bar = range(5, 0, -1)
parallelSort(bar, foo)
print foo # [4,3,2,1,0]
print bar # [1,2,3,4,5]
I've seen the examples using zip but it seems silly to copy all your data from parallel lists to a list of tuples and back again if this can be easily avoided.
A:
Here's an easy way:
perm = sorted(xrange(len(foo)), key=lambda x:foo[x])
This generates a list of permutations - the value in perm[i] is the index of the ith smallest value in foo. Then, you can access both lists in order:
for p in perm:
print "%s: %s" % (foo[p], bar[p])
You'd need to benchmark it to find out if it's any more efficient, though - I doubt it makes much of a difference.
A:
Is there an easy way? Yes. Use zip.
Is there an "easy way that doesn't use a zip variant"? No.
If you wanted to elaborate on why you object to using zip, that would be helpful. Either you're copying objects, in which case Python will copy by reference, or you're copying something so lightweight into a lightweight tuple as to not be worthy of optimization.
If you really don't care about execution speed but are especially concerned for some reason about memory pressure, you could roll your own bubble sort (or your sort algorithm of choice) on your key list which swaps both the key list and the target lists elements when it does a swap. I would call this the opposite of easy, but it would certainly limit your working set.
A:
To achieve this, you would have to implement your own sort.
However: Does the unnecessary copying really hurt your application? Often parts of Python strike me as inefficient, too, but they are efficient enough for what I need.
A:
Any solution I can imagine short of introducing a sort from scratch uses indices, or a dict, or something else that really is not apt to save you memory. In any event, using zip will only increase memory usage by a constant factor, so it is worth making sure this is really a problem before a solution.
If it does get to be a problem, there may be more effective solutions. Since the elements of foo and bar are so closely related, are you sure their right representation is not a list of tuples? Are you sure they should not be in a more compact data structure if you are running out of memory, such as a numpy array or a database (the latter of which is really good at this kind of manipulation)?
(Also, incidentally, itertools.izip can save you a little bit of memory over zip, though you still end up with the full zipped list in list form as the result of sorted.)
|
Python sort parallel arrays in place?
|
Is there an easy (meaning without rolling one's own sorting function) way to sort parallel lists without unnecessary copying in Python? For example:
foo = range(5)
bar = range(5, 0, -1)
parallelSort(bar, foo)
print foo # [4,3,2,1,0]
print bar # [1,2,3,4,5]
I've seen the examples using zip but it seems silly to copy all your data from parallel lists to a list of tuples and back again if this can be easily avoided.
|
[
"Here's an easy way:\nperm = sorted(xrange(len(foo)), key=lambda x:foo[x])\n\nThis generates a list of permutations - the value in perm[i] is the index of the ith smallest value in foo. Then, you can access both lists in order:\nfor p in perm:\n print \"%s: %s\" % (foo[p], bar[p])\n\nYou'd need to benchmark it to find out if it's any more efficient, though - I doubt it makes much of a difference.\n",
"Is there an easy way? Yes. Use zip.\nIs there an \"easy way that doesn't use a zip variant\"? No.\nIf you wanted to elaborate on why you object to using zip, that would be helpful. Either you're copying objects, in which case Python will copy by reference, or you're copying something so lightweight into a lightweight tuple as to not be worthy of optimization.\nIf you really don't care about execution speed but are especially concerned for some reason about memory pressure, you could roll your own bubble sort (or your sort algorithm of choice) on your key list which swaps both the key list and the target lists elements when it does a swap. I would call this the opposite of easy, but it would certainly limit your working set.\n",
"To achieve this, you would have to implement your own sort. \nHowever: Does the unnecessary copying really hurt your application? Often parts of Python strike me as inefficient, too, but they are efficient enough for what I need.\n",
"Any solution I can imagine short of introducing a sort from scratch uses indices, or a dict, or something else that really is not apt to save you memory. In any event, using zip will only increase memory usage by a constant factor, so it is worth making sure this is really a problem before a solution. \nIf it does get to be a problem, there may be more effective solutions. Since the elements of foo and bar are so closely related, are you sure their right representation is not a list of tuples? Are you sure they should not be in a more compact data structure if you are running out of memory, such as a numpy array or a database (the latter of which is really good at this kind of manipulation)?\n(Also, incidentally, itertools.izip can save you a little bit of memory over zip, though you still end up with the full zipped list in list form as the result of sorted.)\n"
] |
[
6,
3,
0,
0
] |
[] |
[] |
[
"algorithm",
"python",
"sorting"
] |
stackoverflow_0002222769_algorithm_python_sorting.txt
|
Q:
Stopping a thread in python
I am creating a thread in my Python app with thread.start_new_thread.
How do I stop it if it hasn't finished in three seconds time?
A:
You can't do that directly. Anyway aborting a thread is not good practice - rather think about using synchronization mechanisms that let you abort the thread in a "soft" way.
But daemonic threads will automatically be aborted if no non-daemonic threads remain (e.g. if the only main thread ends). Maybe that's what you want.
A:
You cannot. Threads can't be killed from outside. The only thing you can do is add a way to ask the thread to exit. Obviously you won't be able to do this if the thread is blocked in some systemcall.
A:
If you really need to do this (e.g. the thread calls code that may hang forever) then consider rewriting your code to spawn a process with the multiprocessing module. You can then kill the process with the Process.terminate() method. You will need 2.6 or later for this, of course.
A:
As noted in a related question, you might be able to raise an exception through ctypes.pythonapi, but not while it's waiting on a system call.
|
Stopping a thread in python
|
I am creating a thread in my Python app with thread.start_new_thread.
How do I stop it if it hasn't finished in three seconds time?
|
[
"You can't do that directly. Anyway aborting a thread is not good practice - rather think about using synchronization mechanisms that let you abort the thread in a \"soft\" way.\nBut daemonic threads will automatically be aborted if no non-daemonic threads remain (e.g. if the only main thread ends). Maybe that's what you want.\n",
"You cannot. Threads can't be killed from outside. The only thing you can do is add a way to ask the thread to exit. Obviously you won't be able to do this if the thread is blocked in some systemcall.\n",
"If you really need to do this (e.g. the thread calls code that may hang forever) then consider rewriting your code to spawn a process with the multiprocessing module. You can then kill the process with the Process.terminate() method. You will need 2.6 or later for this, of course.\n",
"As noted in a related question, you might be able to raise an exception through ctypes.pythonapi, but not while it's waiting on a system call.\n"
] |
[
2,
1,
1,
1
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002223654_multithreading_python.txt
|
Q:
UnicodeEncodeError when redirecting stdout
I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout elsewhere (or capture it with the subprocess module), I get a UnicodeEncodeError:
$ cat example.py
print u'Example: \u00F1'
$ python example.py
Example: ñ
$ python example.py > /dev/null
Traceback (most recent call last):
File "example.py", line 1, in <module>
print u'Example: \u00F1'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)
Why is this? How can I fix it?
A:
Pipes that don't lead to the terminal don't have an encoding, therefore you'll need to check sys.stdout.isatty() and encode if needed.
|
UnicodeEncodeError when redirecting stdout
|
I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout elsewhere (or capture it with the subprocess module), I get a UnicodeEncodeError:
$ cat example.py
print u'Example: \u00F1'
$ python example.py
Example: ñ
$ python example.py > /dev/null
Traceback (most recent call last):
File "example.py", line 1, in <module>
print u'Example: \u00F1'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)
Why is this? How can I fix it?
|
[
"Pipes that don't lead to the terminal don't have an encoding, therefore you'll need to check sys.stdout.isatty() and encode if needed.\n"
] |
[
9
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002224130_python_unicode.txt
|
Q:
Multiple database connections with Python + Pylons + SQLAlchemy
I'm trying to implement the proper architecture for multiple databases under Python + Pylons. I can't put everything in the config files since one of the database connections requires the connection info from a previous database connection (sharding).
What's the best way to implement such an infrastructure?
A:
Pylons's template configures the database in config/environment.py, probably with the engine_from_config method. It finds all the config settings with a particular prefix and passes them as keyword arguments to create_engine.
You can just replace that with a few calls to sqlalchemy.create_engine() with the per-engine url, and common username, and password from your config file.
|
Multiple database connections with Python + Pylons + SQLAlchemy
|
I'm trying to implement the proper architecture for multiple databases under Python + Pylons. I can't put everything in the config files since one of the database connections requires the connection info from a previous database connection (sharding).
What's the best way to implement such an infrastructure?
|
[
"Pylons's template configures the database in config/environment.py, probably with the engine_from_config method. It finds all the config settings with a particular prefix and passes them as keyword arguments to create_engine.\nYou can just replace that with a few calls to sqlalchemy.create_engine() with the per-engine url, and common username, and password from your config file.\n"
] |
[
1
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002205047_pylons_python.txt
|
Q:
IPython demo mode
I'm trying to use the IPython demo mode. I created a file called test.py containing:
print 1
print 2
print 3
and then launched IPython and did the following:
In [1]: from IPython.demo import LineDemo
In [2]: d = LineDemo('test.py')
In [3]: d()
********************* <test.py> block # 0 (5 remaining) *********************
p
********************************** output: **********************************
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/tom/Library/Python/2.6/site-packages/ipython-0.10-py2.6.egg/IPython/demo.pyc in runlines(self, source)
400 """Execute a string with one or more lines of code"""
401
--> 402 exec source in self.user_ns
403
404 def __call__(self,index=None):
/Users/tom/tmp/<string> in <module>()
----> 1
2
3
4
5
NameError: name 'p' is not defined
What is likely to be causing this error? Am I using LineDemo incorrectly?
A:
There seems to be a bug in IPython. In demo.py in LineDemo.reload, the line that says:
src_b = [l for l in self.fobj.readline() if l.strip()]
should say:
src_b = [l for l in self.fobj.readlines() if l.strip()]
Currently it's trying to execute all the letters in the first line instead of all the lines in the file.
Edit: Bug reported.
A:
It works ok in IPython 0.9.1
Which version do you have?
In [1]: from IPython.demo import LineDemo
In [2]: d = LineDemo('test.py')
In [3]: d()
********************* <test.py> block # 0 (2 remaining) *********************
print 1
********************************** output: **********************************
1
In [4]: d()
********************* <test.py> block # 1 (1 remaining) *********************
print 2
********************************** output: **********************************
2
In [5]: d()
********************* <test.py> block # 2 (0 remaining) *********************
print 3
********************************** output: **********************************
3
******************************** END OF DEMO ********************************
******************** Use reset() if you want to rerun it. ********************
|
IPython demo mode
|
I'm trying to use the IPython demo mode. I created a file called test.py containing:
print 1
print 2
print 3
and then launched IPython and did the following:
In [1]: from IPython.demo import LineDemo
In [2]: d = LineDemo('test.py')
In [3]: d()
********************* <test.py> block # 0 (5 remaining) *********************
p
********************************** output: **********************************
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/tom/Library/Python/2.6/site-packages/ipython-0.10-py2.6.egg/IPython/demo.pyc in runlines(self, source)
400 """Execute a string with one or more lines of code"""
401
--> 402 exec source in self.user_ns
403
404 def __call__(self,index=None):
/Users/tom/tmp/<string> in <module>()
----> 1
2
3
4
5
NameError: name 'p' is not defined
What is likely to be causing this error? Am I using LineDemo incorrectly?
|
[
"There seems to be a bug in IPython. In demo.py in LineDemo.reload, the line that says:\nsrc_b = [l for l in self.fobj.readline() if l.strip()]\n\nshould say:\nsrc_b = [l for l in self.fobj.readlines() if l.strip()]\n\nCurrently it's trying to execute all the letters in the first line instead of all the lines in the file.\nEdit: Bug reported.\n",
"It works ok in IPython 0.9.1\nWhich version do you have?\nIn [1]: from IPython.demo import LineDemo\n\nIn [2]: d = LineDemo('test.py')\n\nIn [3]: d()\n********************* <test.py> block # 0 (2 remaining) *********************\nprint 1\n********************************** output: **********************************\n1\n\nIn [4]: d()\n********************* <test.py> block # 1 (1 remaining) *********************\nprint 2\n********************************** output: **********************************\n2\n\nIn [5]: d()\n********************* <test.py> block # 2 (0 remaining) *********************\nprint 3\n********************************** output: **********************************\n3\n\n******************************** END OF DEMO ********************************\n******************** Use reset() if you want to rerun it. ********************\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"demo",
"ipython",
"python"
] |
stackoverflow_0002224082_demo_ipython_python.txt
|
Q:
Lazy evaluation in Python? Between modules?
I'm not sure if something like this is even possible in Python, but if it is it'd be really useful (at least to me in this instance).
I have a test framework in which I want to keep the test configuration separate from the test commands. This is useful because it allows you to mix and match configurations/tests without actually having to modify any code. I essentially just a have a short runner script that takes the names of a config module and a test module, then loads and runs both, like so:
config = __import__(configmod)
test = __import__(commandsmod)
config.run(test.commands)
The only problem with this is I'd actually like the test script to have some limited awareness of the configuration parameters. Ideally I'd like to be able to do something like the following in the test/commands module:
command1 = MyCommand(arg1, arg2, LazyArg1())
command2 = MyCommand(arg1, arg2, LazyArg2())
commands = [command1, command2]
where LazyArg1 and LazyArg2 are methods that are defined in the config module (or the runner module that imports both config/commands). Is there any way to delay evaluation of these functions until they are actually defined?
I'd also be open to other ways of achieving the same end. The only other idea I had was to have the config module write a dictionary to file and then have the commands module import that (assuming you just write out repr(mydict)). This isn't very appealing .. though it would work.
A:
Python is dynamically typed, so this is nothing fancy:
configMod.py:
##### this is configMod.py #####
modTestArg1 = "Brian"
def runTest(testMod, *args, **kwargs):
testMod.doTest(*args, **kwargs)
testMod.py:
##### this is testMod.py #####
def doTest(name, address, city="San Francisco"):
print "doTest called with name: %s, address: %s, city: %s" % \
(name, address, city)
controlMod.py
##### this is controlMod.py #####
import configMod
import testMod
configMod.runTest(testMod, configMod.modTestArg1, "123 Fake Street")
Run it:
python controlMod.py
doTest called with name: Brian, address: 123 Fake Street, city: San Francisco
A:
I hate to answer my own question, but after some more thought, I came up with a potential solution (though I'd love to hear other ideas).
Suppose we have a module mod1:
def myfunc(z):
return z
and a module mod2:
x = lambda mod: mod.myfunc
You can now do the following in a third module:
import mod1
from mod2 import *
x(mod1)(5)
and you end up calling mod1's myfunc. If the double function call is confusing looking, you can assign x(mod1) to another variable name.
|
Lazy evaluation in Python? Between modules?
|
I'm not sure if something like this is even possible in Python, but if it is it'd be really useful (at least to me in this instance).
I have a test framework in which I want to keep the test configuration separate from the test commands. This is useful because it allows you to mix and match configurations/tests without actually having to modify any code. I essentially just a have a short runner script that takes the names of a config module and a test module, then loads and runs both, like so:
config = __import__(configmod)
test = __import__(commandsmod)
config.run(test.commands)
The only problem with this is I'd actually like the test script to have some limited awareness of the configuration parameters. Ideally I'd like to be able to do something like the following in the test/commands module:
command1 = MyCommand(arg1, arg2, LazyArg1())
command2 = MyCommand(arg1, arg2, LazyArg2())
commands = [command1, command2]
where LazyArg1 and LazyArg2 are methods that are defined in the config module (or the runner module that imports both config/commands). Is there any way to delay evaluation of these functions until they are actually defined?
I'd also be open to other ways of achieving the same end. The only other idea I had was to have the config module write a dictionary to file and then have the commands module import that (assuming you just write out repr(mydict)). This isn't very appealing .. though it would work.
|
[
"Python is dynamically typed, so this is nothing fancy:\nconfigMod.py:\n\n##### this is configMod.py #####\nmodTestArg1 = \"Brian\"\n\ndef runTest(testMod, *args, **kwargs):\n testMod.doTest(*args, **kwargs)\n\ntestMod.py:\n\n##### this is testMod.py #####\ndef doTest(name, address, city=\"San Francisco\"):\n print \"doTest called with name: %s, address: %s, city: %s\" % \\\n (name, address, city)\n\ncontrolMod.py\n\n##### this is controlMod.py #####\nimport configMod\nimport testMod\n\nconfigMod.runTest(testMod, configMod.modTestArg1, \"123 Fake Street\")\n\nRun it:\n\npython controlMod.py\ndoTest called with name: Brian, address: 123 Fake Street, city: San Francisco\n\n",
"I hate to answer my own question, but after some more thought, I came up with a potential solution (though I'd love to hear other ideas).\nSuppose we have a module mod1:\ndef myfunc(z):\n return z\n\nand a module mod2:\nx = lambda mod: mod.myfunc\n\nYou can now do the following in a third module:\nimport mod1\nfrom mod2 import *\n\nx(mod1)(5)\n\nand you end up calling mod1's myfunc. If the double function call is confusing looking, you can assign x(mod1) to another variable name.\n"
] |
[
1,
0
] |
[] |
[] |
[
"lazy_evaluation",
"python",
"testing"
] |
stackoverflow_0002223025_lazy_evaluation_python_testing.txt
|
Q:
How to extract signature from function reference in Python?
Let's say I have a function in Python like so:
def foo(x): pass
According to Python, 'foo' alone is a function reference, right?
>>> def foo(x): pass
...
>>> foo
<function foo at 0xb7f3d1b4>
Is there any way I can examine the function reference to determine the number of arguments it expects?
A:
You need inspect.getfullargspec in py3k or inspect.getargspec in earlier versions.
>>> def foo(x): pass
>>> import inspect
>>> inspect.getfullargspec(foo)
FullArgSpec(args=['x'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})
|
How to extract signature from function reference in Python?
|
Let's say I have a function in Python like so:
def foo(x): pass
According to Python, 'foo' alone is a function reference, right?
>>> def foo(x): pass
...
>>> foo
<function foo at 0xb7f3d1b4>
Is there any way I can examine the function reference to determine the number of arguments it expects?
|
[
"You need inspect.getfullargspec in py3k or inspect.getargspec in earlier versions.\n >>> def foo(x): pass\n\n>>> import inspect\n>>> inspect.getfullargspec(foo)\nFullArgSpec(args=['x'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})\n\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002224428_python.txt
|
Q:
How do I do text wrapping in pyCairo + Pango?
What I need pyCairo to do is :
generate an image of size 100x100 containing some text and an image from filesystem as background
the text should be within a box which has text wrapping of size 20x20 with bottom left corner at (40,40).
save this image
A:
You need to find a way to get the Pango context and set pango.Layout.set_wrap() and pango.Layout.set_width().
|
How do I do text wrapping in pyCairo + Pango?
|
What I need pyCairo to do is :
generate an image of size 100x100 containing some text and an image from filesystem as background
the text should be within a box which has text wrapping of size 20x20 with bottom left corner at (40,40).
save this image
|
[
"You need to find a way to get the Pango context and set pango.Layout.set_wrap() and pango.Layout.set_width().\n"
] |
[
3
] |
[] |
[] |
[
"cairo",
"pango",
"python",
"word_wrap"
] |
stackoverflow_0001973990_cairo_pango_python_word_wrap.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.