content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How do I send/get a JSON Object with Django? I know how to use the JQuery ajax feature to call the "url view" of Django. import simplejson as json def the_view(request): fruits = {'color':5, 'type': 22} jfruit = json.dump(fruits) return render_to_response( THE JSON OBJECT!!! ...how? ) A: return HttpResponse(simplejson.dumps(mydictionary), mimetype="application/json") see b-list A: Or shorter: download http://bitbucket.org/offline/django-annoying/ and write: @ajax_request def the_view(request): return {'color':5, 'type': 22} There are a few such nice tiny things in django-annoying.
How do I send/get a JSON Object with Django?
I know how to use the JQuery ajax feature to call the "url view" of Django. import simplejson as json def the_view(request): fruits = {'color':5, 'type': 22} jfruit = json.dump(fruits) return render_to_response( THE JSON OBJECT!!! ...how? )
[ "return HttpResponse(simplejson.dumps(mydictionary), mimetype=\"application/json\")\nsee b-list\n", "Or shorter: \ndownload http://bitbucket.org/offline/django-annoying/ and write:\n@ajax_request \ndef the_view(request):\n return {'color':5, 'type': 22}\n\nThere are a few such nice tiny things in django-annoying.\n" ]
[ 5, 3 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002023577_django_json_python.txt
Q: wrapping cmd.exe with subprocess I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ? import subprocess process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None) process.stdin.write("dir\r\n") output = process.stdout.readlines() print output A: Usually when trying to call command prompt with an actual command, it is simpler to just call it with the "/k" parameter rather than passing commands in via stdin. That is, just call "cmd.exe /k dir". For example, from os import * a = popen("cmd /k dir") print (a.read()) The code below does the same thing, though lacks a string for you to manipulate, since it pipes to output directly: from subprocess import * Popen("cmd /k dir") A: process = subprocess.Popen('cmd.exe /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None) process.stdin.write("dir\n") o,e=process.communicate() print o process.stdin.close() by the way, if your actual task is really to do a directory listing, please use Python's own os module, eg os.listdir(), or glob module... etc. Don't call system commands like that unnecessarily. It makes your code not portable. A: This locks up because process.stdout.readlines() reads all output by the process (until it terminates). Since cmd.exe is still running, it keeps waiting forever for it to close. To fix this, you can start a separate thread to read the process output. This is something you need to do anyway if you don't call communicate(), to avoid possible deadlock. This thread can call process.stdout.readline() repeatedly and handle the data or send it back to the main thread for handling.
wrapping cmd.exe with subprocess
I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ? import subprocess process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None) process.stdin.write("dir\r\n") output = process.stdout.readlines() print output
[ "Usually when trying to call command prompt with an actual command, it is simpler to just call it with the \"/k\" parameter rather than passing commands in via stdin. That is, just call \"cmd.exe /k dir\". For example, \nfrom os import *\na = popen(\"cmd /k dir\")\nprint (a.read())\n\nThe code below does the same thing, though lacks a string for you to manipulate, since it pipes to output directly:\nfrom subprocess import *\nPopen(\"cmd /k dir\")\n\n", "process = subprocess.Popen('cmd.exe /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)\nprocess.stdin.write(\"dir\\n\")\no,e=process.communicate()\nprint o\nprocess.stdin.close()\n\nby the way, if your actual task is really to do a directory listing, please use Python's own os module, eg os.listdir(), or glob module... etc. Don't call system commands like that unnecessarily. It makes your code not portable.\n", "This locks up because process.stdout.readlines() reads all output by the process (until it terminates). Since cmd.exe is still running, it keeps waiting forever for it to close.\nTo fix this, you can start a separate thread to read the process output. This is something you need to do anyway if you don't call communicate(), to avoid possible deadlock. This thread can call process.stdout.readline() repeatedly and handle the data or send it back to the main thread for handling.\n" ]
[ 5, 5, 2 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0002028207_python_subprocess_windows.txt
Q: Running Different Django Versions But Sharing Authentication Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code. We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x I'm trying to figure out how to get this working and I've narrowed it down to the following: Use an old forum solution that works w/django 0.96 (does this exist?) Try to patch a forum solution to make it "backwards compatible" with 0.96 (possible nightmare) Use two different djangos: 0.96 and 1.x and (since we're using Apache w/mod_python) have two different Location directives; adjust PYTHONPATH for each appropriately (or use virtualenv, etc.) But will option #3 even work? I don't know enough about how django.contrib.auth and friends work so if I run two different versions of django will the user stay logged in? I didn't mention trying to patch our 0.96 project to bring it to 1.x but we don't really have the time to do that. Any suggestions? A: It's possible, but it may be pretty painful to do option #3. How about Option 4: bite the bullet and upgrade to Django 1.1.1. I did this with a couple of 0.97pre sites and it took less time than I thought it would. The biggest pain was dealing with admin stuff. Instead of going with separate admin.py files, we simply put the Admin classes directly below the Model classes. I use Mercurial for my DVCS and I just cloned, hacked, merged and it worked. It took about 3-5 hours per site and that included some custom template tag munging. A: A user's login status is stored using sessions. As far as I can tell from comparing trunk to the 0.96 source, the sessions are committed to a cookie the same way, and auth stores the user ID and backend the same way, so as long as the two apps use the same session storage and are on the same domain, it should work. (Just to be safe, I wouldn't use secure cookies in case the backend logic has changed - I didn't check out that part.) However, 0.96 did not feature pluggable session stores like modern Django does. Probably, to get a current version of Django to work with your 0.96 sessions, you would need to write a session backend for the current Django that connects to the 0.96 database and manipulates the sessions there. I'm not sure how well that would work, though. A: It's possible to expose Django 0.96 tables to 1.1 - you can use unmanaged models wrapped around database VIEWs. In other words you issue: CREATE VIEW auth_user AS SELECT * from django096db.auth_user; (and similar cmd for other tables) and then you have Django 1.1 synchronized with 0.96 (assuming 0.96 tables are compatible with 1.1, I haven't checked that).
Running Different Django Versions But Sharing Authentication
Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code. We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x I'm trying to figure out how to get this working and I've narrowed it down to the following: Use an old forum solution that works w/django 0.96 (does this exist?) Try to patch a forum solution to make it "backwards compatible" with 0.96 (possible nightmare) Use two different djangos: 0.96 and 1.x and (since we're using Apache w/mod_python) have two different Location directives; adjust PYTHONPATH for each appropriately (or use virtualenv, etc.) But will option #3 even work? I don't know enough about how django.contrib.auth and friends work so if I run two different versions of django will the user stay logged in? I didn't mention trying to patch our 0.96 project to bring it to 1.x but we don't really have the time to do that. Any suggestions?
[ "It's possible, but it may be pretty painful to do option #3.\nHow about Option 4: bite the bullet and upgrade to Django 1.1.1. I did this with a couple of 0.97pre sites and it took less time than I thought it would. The biggest pain was dealing with admin stuff. Instead of going with separate admin.py files, we simply put the Admin classes directly below the Model classes.\nI use Mercurial for my DVCS and I just cloned, hacked, merged and it worked. It took about 3-5 hours per site and that included some custom template tag munging.\n", "A user's login status is stored using sessions. As far as I can tell from comparing trunk to the 0.96 source, the sessions are committed to a cookie the same way, and auth stores the user ID and backend the same way, so as long as the two apps use the same session storage and are on the same domain, it should work. (Just to be safe, I wouldn't use secure cookies in case the backend logic has changed - I didn't check out that part.)\nHowever, 0.96 did not feature pluggable session stores like modern Django does. Probably, to get a current version of Django to work with your 0.96 sessions, you would need to write a session backend for the current Django that connects to the 0.96 database and manipulates the sessions there. I'm not sure how well that would work, though.\n", "It's possible to expose Django 0.96 tables to 1.1 - you can use unmanaged models wrapped around database VIEWs. In other words you issue:\nCREATE VIEW auth_user AS SELECT * from django096db.auth_user;\n(and similar cmd for other tables)\nand then you have Django 1.1 synchronized with 0.96 (assuming 0.96 tables are compatible with 1.1, I haven't checked that).\n" ]
[ 1, 0, 0 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0002022178_django_mod_python_python.txt
Q: adding lighting effects to an image in python I want to specify a light source at a particular location in an image using Python. PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this? thank you! A: So, the bad news is that PIL can't do that. I trhow a couple of ideas bellow, unfortunatelly none of which is straightforward. GIMP (GNU Image Manipulation Program) does have an awesome "ligthning effects" plug-in, GIMP is scriptable in Python, and it is possible to call teh plug-in paramtrically. The drawback is that your plug-in has to urn from within GIMP's process. (So you'd either estart GIMP as a batch for a one time run, or have to design a server python plug-in that processes your images through the lightning effects plug-in) Other optionn I ma familiar with also involves off-process rendering would be use POVRay: render your image as the pigment-map for a 1x1x0.1 plane slab and then you can place "real" light-sources around. Another way is using OpenGL yourself - I browseddarond a bit, and maybe this "gloss" project can provide a way for you to use light sources without havign to descend into lowlevel opengl: http://www.tuxradar.com/gloss Or -- "fake" it with a rectangular grid of black and white rectangles that you combine with your through color multiplication. This is the only way that would allow yiou to keep with PIL alone, but the "grid" lines are too visible, and I think that trying to smooth with blur would not cut it: def fake_light(image, tilesize=50): WIDTH, HEIGHT = i.size for x in xrange(0, WIDTH, tilesize): for y in xrange(0, HEIGHT, tilesize): br = int(255 * (1 - x / float(WIDTH) * y /float(HEIGHT))) tile = Image.new("RGBA", (tilesize, tilesize), (255,255,255,128)) image.paste((br,br,br), (x, y, x + tilesize, y + tilesize), mask=tile)
adding lighting effects to an image in python
I want to specify a light source at a particular location in an image using Python. PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this? thank you!
[ "So, the bad news is that PIL can't do that. I trhow a couple of ideas bellow, unfortunatelly none of which is straightforward.\nGIMP (GNU Image Manipulation Program) does have an awesome \"ligthning effects\" plug-in,\nGIMP is scriptable in Python, and it is possible to call teh plug-in paramtrically. \nThe drawback is that your plug-in has to urn from within GIMP's process. (So you'd either estart GIMP as a batch for a one time run, or have to design a server python plug-in that processes your images through the lightning effects plug-in)\nOther optionn I ma familiar with also involves off-process rendering would be use POVRay: render your image as the pigment-map for a 1x1x0.1 plane slab and then you can place \"real\" light-sources around.\nAnother way is using OpenGL yourself - I browseddarond a bit, and maybe this \"gloss\" project can provide a way for you to use light sources without havign to descend into lowlevel opengl:\nhttp://www.tuxradar.com/gloss\nOr -- \"fake\" it with a rectangular grid of black and white rectangles that you combine with your through color multiplication. \nThis is the only way that would allow yiou to keep with PIL alone, but the \"grid\" lines are too visible, and I think that trying to smooth with blur would not cut it:\ndef fake_light(image, tilesize=50):\n WIDTH, HEIGHT = i.size\n for x in xrange(0, WIDTH, tilesize):\n for y in xrange(0, HEIGHT, tilesize):\n br = int(255 * (1 - x / float(WIDTH) * y /float(HEIGHT)))\n tile = Image.new(\"RGBA\", (tilesize, tilesize), (255,255,255,128))\n image.paste((br,br,br), (x, y, x + tilesize, y + tilesize), mask=tile)\n\n" ]
[ 1 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002028809_image_processing_python_python_imaging_library.txt
Q: Creating an image editing application in Python I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor? A: You just need a gui toolkit (gtk, qt, wx) a image library (PIL) and 500 hours of free time ... A: Have you looked at the Python Imaging Library (PIL)? A: So, the fact is that creating a complex app with a nice UI takes time - I am just expanding a little bit on the answer by THC4k. PIL, at least PIL alone is useless for this: it does have some functions to manipulate images, but the complicate task here is creating and tunning your desired UI. That's where the widgets toolkits come in: You would have to pick a toolkit platform that can offer you buttons, images, load and save the image files, maybe some specialzed widgets you can use to create your color swatches, etc. both GTK+ and QT4.5 have a liberal license, are very complete and very unpythonic on their use :-( (While you are at it, when using these libraries and toolkits our app can easily be multiplatform: you don't have to make it windows specific, it is equally easy to create an app that will run on Windows, Linux and Mac using python and either GTK+ or Qt4) One thing I would suggest is for you to learn to proper use GIMP: it is an Image editor, and certainly it will lack a lot of tools you are needing for sprites: but you can expand it's capabilities with Python plug-ins. On the other hand GIMP does have thousands of features that you'd no longer will need to create for your stand-alone app. (think on layer support, color filters, image rotation etc...) Check around on how to install GIMP with Python support on Windows, then spend some hours learning the app, with some book-like text around preferably so you can find the hidden features. Ah, ok, finally: If you want a very simple thing, just for the taste of "i did it" - you can use Pygame: You have to do all the drawing on the window, including text - but have straighter access to pixels, colors, mouse clicks and coordinates than with GTK+ or Qt, in a sense it would be a lot less of overhead for you to learn in terms of API's and internal working. A: You could try PyGame but, seriously, you couldn't find a freeware graphics editor for Windows??!! EDIT: In the past I've used Aha-Soft's IconXP for pixel work, but it costs USD 30 and doesn't offer all of the Pixen features that I guess you'll want.
Creating an image editing application in Python
I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?
[ "You just need a gui toolkit (gtk, qt, wx) a image library (PIL) and 500 hours of free time ...\n", "Have you looked at the Python Imaging Library (PIL)? \n", "So, the fact is that creating a complex app with a nice UI takes time - I am just expanding a little bit on the answer by THC4k. \nPIL, at least PIL alone is useless for this: it does have some functions to manipulate images, but the complicate task here is creating and tunning your desired UI. \nThat's where the widgets toolkits come in: You would have to pick a toolkit platform that can offer you buttons, images, load and save the image files, maybe some specialzed widgets you can use to create your color swatches, etc.\nboth GTK+ and QT4.5 have a liberal license, are very complete and very unpythonic on their use :-( \n(While you are at it, when using these libraries and toolkits our app can easily be multiplatform: you don't have to make it windows specific, it is equally easy to create an app that will run on Windows, Linux and Mac using python and either GTK+ or Qt4)\nOne thing I would suggest is for you to learn to proper use GIMP: it is an Image editor, and certainly it will lack a lot of tools you are needing for sprites: but you can expand it's capabilities with Python plug-ins. On the other hand GIMP does have thousands of features that you'd no longer will need to create for your stand-alone app. (think on layer support, color filters, image rotation etc...)\nCheck around on how to install GIMP with Python support on Windows, then spend some hours learning the app, with some book-like text around preferably so you can find the hidden features. \nAh, ok, finally:\nIf you want a very simple thing, just for the taste of \"i did it\" - you can use Pygame: You have to do all the drawing on the window, including text - but have straighter access to pixels, colors, mouse clicks and coordinates than with GTK+ or Qt, in a sense it would be a lot less of overhead for you to learn in terms of API's and internal working.\n", "You could try PyGame but, seriously, you couldn't find a freeware graphics editor for Windows??!!\nEDIT: In the past I've used Aha-Soft's IconXP for pixel work, but it costs USD 30 and doesn't offer all of the Pixen features that I guess you'll want.\n" ]
[ 6, 3, 2, 1 ]
[]
[]
[ "image_editor", "python" ]
stackoverflow_0002028025_image_editor_python.txt
Q: Drag and drop ordering of formset with extra entries I have been looking for a way to allow the user to easily change the order of entries in a formset. I found a StackOverflow question that addresses this subject, with the accepted answer referencing a Django Snippet that uses a JQuery tool to allow drag 'n drop of the entries. This is nifty and cool, but I have a problem with 'extra' entries. If an 'extra' entry is modified and then dragged I get an error on the submit: (1048, "Column 'order' cannot be null") I believe Django keeps the 'extra' entries separate, since they have to be inserted instead of updates. So the reordering probably confuses matters. Is there a way to make this work, or are there other suggestions for reordering and/or adding new entries? Edit: Added some relevant code excerpts. I'm trying this out in the admin, as the snippet shows. I'd like to put it in my own page ultimately, however. models.py: class Section(models.Model): section_id = models.AutoField(primary_key=True) section_name = models.CharField(max_length=135) score_order = models.IntegerField() def __unicode__(self): return self.section_name class Meta: db_table = u'section' ordering = [u"score_order"] class Chair(models.Model): chair_id = models.AutoField(primary_key=True) member = models.ForeignKey(Member, null=True, blank=True, limit_choices_to={'current_member': True}) section = models.ForeignKey(Section) description = models.CharField(max_length=135) order = models.IntegerField(blank=True, null=True) def __unicode__(self): return "%s - %s" % (self.description, self.member) class Meta: db_table = u'chair' ordering = (u'section', u'order') admin.py class SectionForm(forms.ModelForm): model = Section class Media: js = ( '/scripts/jquery.js', '/scripts/ui.core.js', '/scripts/ui.sortable.js', '/scripts/section-sort.js', ) class ChairInline(admin.StackedInline): model = Chair admin.site.register(Section, inlines = [ChairInline], form = SectionForm, ) A: I found my own solution. The snippet was setting the order for every row that had a non-empty primary key value. But the extra rows have an empty primary key, and I believe they have to stay empty for Django to know that they are to be inserted instead of updated. I modified the function to check for the other fields being empty (fortunately, I only have a couple) as well as the primary key: jQuery(function($) { $('div.inline-group').sortable({ items: 'div.inline-related', handle: 'h3:first', update: function() { $(this).find('div.inline-related').each(function(i) { if ($(this).find('input[id$=chair_id]').val() || $(this).find('select[id$=member]').val() || $(this).find('select[id$=description]').val()) { $(this).find('input[id$=order]').val(i+1); } }); } }); $('div.inline-related h3').css('cursor', 'move'); $('div.inline-related').find('input[id$=order]').parent('div').hide(); }); This did the trick for me. I could maybe improve it by adding a hidden field to the form that gets set whenever any field on a row gets modified. But at this point I'm still a jQuery n00b, so this will do. If anybody has better ideas, feel free to comment or add another answer. A: I do sortable formsets in one of my apps. I use this jQuery drag and drop plugin: http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/ I bind the plugin's onDrop event to a function that resets the value of all "order" fields. Additionally, I pass initial data to the formset so the formset's extra "order" fields always have a value in cases where there is no javascript available - the user won't be able to re-order rows, but they can edit and post changes without the null error you described.
Drag and drop ordering of formset with extra entries
I have been looking for a way to allow the user to easily change the order of entries in a formset. I found a StackOverflow question that addresses this subject, with the accepted answer referencing a Django Snippet that uses a JQuery tool to allow drag 'n drop of the entries. This is nifty and cool, but I have a problem with 'extra' entries. If an 'extra' entry is modified and then dragged I get an error on the submit: (1048, "Column 'order' cannot be null") I believe Django keeps the 'extra' entries separate, since they have to be inserted instead of updates. So the reordering probably confuses matters. Is there a way to make this work, or are there other suggestions for reordering and/or adding new entries? Edit: Added some relevant code excerpts. I'm trying this out in the admin, as the snippet shows. I'd like to put it in my own page ultimately, however. models.py: class Section(models.Model): section_id = models.AutoField(primary_key=True) section_name = models.CharField(max_length=135) score_order = models.IntegerField() def __unicode__(self): return self.section_name class Meta: db_table = u'section' ordering = [u"score_order"] class Chair(models.Model): chair_id = models.AutoField(primary_key=True) member = models.ForeignKey(Member, null=True, blank=True, limit_choices_to={'current_member': True}) section = models.ForeignKey(Section) description = models.CharField(max_length=135) order = models.IntegerField(blank=True, null=True) def __unicode__(self): return "%s - %s" % (self.description, self.member) class Meta: db_table = u'chair' ordering = (u'section', u'order') admin.py class SectionForm(forms.ModelForm): model = Section class Media: js = ( '/scripts/jquery.js', '/scripts/ui.core.js', '/scripts/ui.sortable.js', '/scripts/section-sort.js', ) class ChairInline(admin.StackedInline): model = Chair admin.site.register(Section, inlines = [ChairInline], form = SectionForm, )
[ "I found my own solution. The snippet was setting the order for every row that had a non-empty primary key value. But the extra rows have an empty primary key, and I believe they have to stay empty for Django to know that they are to be inserted instead of updated. I modified the function to check for the other fields being empty (fortunately, I only have a couple) as well as the primary key:\njQuery(function($) {\n $('div.inline-group').sortable({\n items: 'div.inline-related',\n handle: 'h3:first',\n update: function() {\n $(this).find('div.inline-related').each(function(i) {\n if ($(this).find('input[id$=chair_id]').val() ||\n $(this).find('select[id$=member]').val() ||\n $(this).find('select[id$=description]').val()) {\n $(this).find('input[id$=order]').val(i+1);\n }\n });\n }\n });\n $('div.inline-related h3').css('cursor', 'move');\n $('div.inline-related').find('input[id$=order]').parent('div').hide();\n});\n\nThis did the trick for me. I could maybe improve it by adding a hidden field to the form that gets set whenever any field on a row gets modified. But at this point I'm still a jQuery n00b, so this will do. If anybody has better ideas, feel free to comment or add another answer.\n", "I do sortable formsets in one of my apps. I use this jQuery drag and drop plugin:\nhttp://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/\nI bind the plugin's onDrop event to a function that resets the value of all \"order\" fields. \nAdditionally, I pass initial data to the formset so the formset's extra \"order\" fields always have a value in cases where there is no javascript available - the user won't be able to re-order rows, but they can edit and post changes without the null error you described.\n" ]
[ 3, 1 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0001993826_django_javascript_jquery_python.txt
Q: How do I search through regex matches in Python? I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is: m = firstre.match(str) if m: # Do something m = secondre.match(str) if m: # Do something else m = thirdre.match(str) if m: # Do something different from both Apart from the ugliness, this code matches against all regexes even after it has matched one of them (say firstre), which is inefficient. I tried to use: elif m = secondre.match(str) but learnt that assignment is not allowed in if statements. Is there an elegant way to achieve what I want? A: def doit( s ): # with some side-effect on a a = [] def f1( s, m ): a.append( 1 ) print 'f1', a, s, m def f2( s, m ): a.append( 2 ) print 'f2', a, s, m def f3( s, m ): a.append( 3 ) print 'f3', a, s, m re1 = re.compile( 'one' ) re2 = re.compile( 'two' ) re3 = re.compile( 'three' ) func_re_list = ( ( f1, re1 ), ( f2, re2 ), ( f3, re3 ), ) for myfunc, myre in func_re_list: m = myre.match( s ) if m: myfunc( s, m ) break doit( 'one' ) doit( 'two' ) doit( 'three' ) A: This might be a bit over engineering the solution, but you could combine them as a single regexp with named groups and see which group matched. This could be encapsulated as a helper class: import re class MultiRe(object): def __init__(self, **regexps): self.keys = regexps.keys() self.union_re = re.compile("|".join("(?P<%s>%s)" % kv for kv in regexps.items())) def match(self, string, *args): result = self.union_re.match(string, *args) if result: for key in self.keys: if result.group(key) is not None: return key Lookup would be like this: multi_re = MultiRe(foo='fo+', bar='ba+r', baz='ba+z') match = multi_re.match('baaz') if match == 'foo': # one thing elif match == 'bar': # some other thing elif match == 'baz': # or this else: # no match A: This is a good application for the undocumented but quite useful re.Scanner class. A: A few ideas, none of them good necessarily, but it might fit your code well: How about putting the code in a separate function, i.e. MatchRegex(), which returns which regex it matched. That way, inside the function, you can use a return after you matched the first (or second) regex, meaning you lose the inefficiency. Of course, you could always go with just nested if statements: m = firstre.match(str) if m: # Do something else: m = secondre.match(str) ... I really don't see any reason not to go with nested ifs. They're very easy to understand and as efficient as you want. I'd go for them just for their simplicity. A: You could use def do_first(str, res, actions): for re,action in zip(res, actions): m = re.match(str) if m: action(str) return So, for example, say you've defined def do_something_1(str): print "#1: %s" % str def do_something_2(str): print "#2: %s" % str def do_something_3(str): print "#3: %s" % str firstre = re.compile("foo") secondre = re.compile("bar") thirdre = re.compile("baz") Then call it with do_first("baz", [firstre, secondre, thirdre], [do_something_1, do_something_2, do_something_3]) A: Early returns, perhaps? def doit(s): m = re1.match(s) if m: # Do something return m = re2.match(s) if m: # Do something else return ... Ants Aasma's answer is good too. If you prefer less scaffolding you can write that out yourself using the verbose regex syntax. re = re.compile(r'''(?x) # set the verbose flag (?P<foo> fo+ ) | (?P<bar> ba+r ) | #...other alternatives... ''') def doit(s): m = re.match(s) if m.group('foo'): # Do something elif m.group('bar'): # Do something else ... I've done this a lot. It's fast and it works with re.finditer. A: Do it with an elif in case you just need a True/False out of regex matching: if regex1.match(str): # do stuff elif regex2.match(str): # and so on
How do I search through regex matches in Python?
I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is: m = firstre.match(str) if m: # Do something m = secondre.match(str) if m: # Do something else m = thirdre.match(str) if m: # Do something different from both Apart from the ugliness, this code matches against all regexes even after it has matched one of them (say firstre), which is inefficient. I tried to use: elif m = secondre.match(str) but learnt that assignment is not allowed in if statements. Is there an elegant way to achieve what I want?
[ "def doit( s ):\n\n # with some side-effect on a\n a = [] \n\n def f1( s, m ):\n a.append( 1 )\n print 'f1', a, s, m\n\n def f2( s, m ):\n a.append( 2 )\n print 'f2', a, s, m\n\n def f3( s, m ):\n a.append( 3 )\n print 'f3', a, s, m\n\n re1 = re.compile( 'one' )\n re2 = re.compile( 'two' )\n re3 = re.compile( 'three' )\n\n\n func_re_list = (\n ( f1, re1 ), \n ( f2, re2 ), \n ( f3, re3 ),\n )\n for myfunc, myre in func_re_list:\n m = myre.match( s )\n if m:\n myfunc( s, m )\n break\n\n\ndoit( 'one' ) \ndoit( 'two' ) \ndoit( 'three' ) \n\n", "This might be a bit over engineering the solution, but you could combine them as a single regexp with named groups and see which group matched. This could be encapsulated as a helper class:\nimport re\nclass MultiRe(object):\n def __init__(self, **regexps):\n self.keys = regexps.keys()\n self.union_re = re.compile(\"|\".join(\"(?P<%s>%s)\" % kv for kv in regexps.items()))\n\n def match(self, string, *args):\n result = self.union_re.match(string, *args)\n if result:\n for key in self.keys:\n if result.group(key) is not None:\n return key\n\nLookup would be like this:\nmulti_re = MultiRe(foo='fo+', bar='ba+r', baz='ba+z')\nmatch = multi_re.match('baaz')\nif match == 'foo':\n # one thing\nelif match == 'bar':\n # some other thing\nelif match == 'baz':\n # or this\nelse:\n # no match\n\n", "This is a good application for the undocumented but quite useful re.Scanner class.\n", "A few ideas, none of them good necessarily, but it might fit your code well:\nHow about putting the code in a separate function, i.e. MatchRegex(), which returns which regex it matched. That way, inside the function, you can use a return after you matched the first (or second) regex, meaning you lose the inefficiency.\nOf course, you could always go with just nested if statements:\nm = firstre.match(str)\nif m:\n # Do something\nelse:\n m = secondre.match(str)\n ...\n\nI really don't see any reason not to go with nested ifs. They're very easy to understand and as efficient as you want. I'd go for them just for their simplicity.\n", "You could use\ndef do_first(str, res, actions):\n for re,action in zip(res, actions):\n m = re.match(str)\n if m:\n action(str)\n return\n\nSo, for example, say you've defined\ndef do_something_1(str):\n print \"#1: %s\" % str\n\ndef do_something_2(str):\n print \"#2: %s\" % str\n\ndef do_something_3(str):\n print \"#3: %s\" % str\n\nfirstre = re.compile(\"foo\")\nsecondre = re.compile(\"bar\")\nthirdre = re.compile(\"baz\")\n\nThen call it with\ndo_first(\"baz\",\n [firstre, secondre, thirdre],\n [do_something_1, do_something_2, do_something_3])\n\n", "Early returns, perhaps?\ndef doit(s):\n m = re1.match(s)\n if m:\n # Do something\n return\n\n m = re2.match(s)\n if m:\n # Do something else\n return\n\n ...\n\nAnts Aasma's answer is good too. If you prefer less scaffolding you can write that out yourself using the verbose regex syntax.\nre = re.compile(r'''(?x) # set the verbose flag\n (?P<foo> fo+ )\n | (?P<bar> ba+r )\n | #...other alternatives...\n''')\n\ndef doit(s):\n m = re.match(s)\n if m.group('foo'):\n # Do something\n elif m.group('bar'):\n # Do something else\n ...\n\nI've done this a lot. It's fast and it works with re.finditer.\n", "Do it with an elif in case you just need a True/False out of regex matching:\nif regex1.match(str):\n # do stuff\nelif regex2.match(str):\n # and so on\n\n" ]
[ 4, 3, 3, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex", "switch_statement" ]
stackoverflow_0002028164_python_regex_switch_statement.txt
Q: Python data structures, dictionary? I hope somebody can help. I am using Python and I would like to be able to do the following. I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or integers For example the shape 'Rectangle' may have the following commands 'ChangeColor' 'green' 'FillStyle' 'hatch' 'Dimensions' 10 15 etc..... What would be the best data structure to store this information. I need to be able to easily retrieve these commands from the data structure given the 'shape' of the object. Would a dictionary be the correct choice, I have never used these before Thanks A: You might be better off creating your own class: class Shape(object): def __init__(self): self.shape = "rectangle" self.color = "green" self.fillstyle = "hatch" # etc def ChangeColor(self, color): self.color = color # etc A: dicts are for when the order isn't important but you want store values for different names. lists are ordered sequences of objects, usually of the same type and the position doesn't mean anything particular. tuples are ordered sequences of objects, possibly of different types and each different position has a specific meaning. A: I would suggest using an object class and storing all of the values/commands within that object so that you can pass it around easily. (Similar to what recursive said). However; you could also use a dictionary with the key being the object name and the values being a list containing possible commands. A: It seems to me that a command could be represented as a list [] or tuple (), and so could a series of commands. So one possibility is that you have a list of lists of strings. Generally you want to use a dictionary only when you want to look up a value by key. For example, if you knew the name of a command (wrt a shape) and wanted to know which parameters were passed to that command, you could have a dictionary mapping from string to list. If you post more about how you plan to use this data, I could give a better answer. Here is a link to the Python documentation on basic data structures, which should be very helpful: http://docs.python.org/tutorial/datastructures.html Edit: in response to first comment, do you need to store the commands or just read them from input one by one and execute them? A: What about this? Example s = {'Rectangle': {'ChangeColor':'green','FillStyle':'hatch', 'Dimension1': 10, 'Dimension2':15}} s['Triangle'] = {'ChangeColor':'red','FillStyle':'hatch', 'Dimension1': 10, 'Dimension2':15, 'Dimension3':5} for k, v in s.iteritems(): print k for k1, v1 in v.iteritems(): print " ", k1, "=", v1 Result: Triangle Dimension1 = 10 Dimension2 = 15 Dimension3 = 5 ChangeColor = red FillStyle = hatch Rectangle Dimension1 = 10 Dimension2 = 15 ChangeColor = green FillStyle = hatch A: I would store the commands as a list of lists, or of tuples, depending on whether or not I thought I'd modify commands. Note that argument unpacking in Python makes for a very simple mechanism for executing these commands, e.g.: class Shape(object): def background(self, color): print "background:", color def foreground(self, color): print "foreground:", color def rect(self, left, top, right, bottom): print "rect:", left, top, right, bottom def execute_commands(self, command_list): for command in command_list: if hasattr(self, command[0]): getattr(self, command[0])(*command[1:]) >>> s = Shape() >>> c = [('background', 'blue'), ('foreground', 'yellow'), ('rect', 10, 0, 20, 20)] >>> s.execute_commands(c) background: blue foreground: yellow rect: 10 0 20 20
Python data structures, dictionary?
I hope somebody can help. I am using Python and I would like to be able to do the following. I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or integers For example the shape 'Rectangle' may have the following commands 'ChangeColor' 'green' 'FillStyle' 'hatch' 'Dimensions' 10 15 etc..... What would be the best data structure to store this information. I need to be able to easily retrieve these commands from the data structure given the 'shape' of the object. Would a dictionary be the correct choice, I have never used these before Thanks
[ "You might be better off creating your own class:\nclass Shape(object):\n def __init__(self):\n self.shape = \"rectangle\"\n self.color = \"green\"\n self.fillstyle = \"hatch\"\n # etc\n\n def ChangeColor(self, color):\n self.color = color\n\n # etc\n\n", "dicts are for when the order isn't important but you want store values for different names.\nlists are ordered sequences of objects, usually of the same type and the position doesn't mean anything particular.\ntuples are ordered sequences of objects, possibly of different types and each different position has a specific meaning.\n", "I would suggest using an object class and storing all of the values/commands within that object so that you can pass it around easily. (Similar to what recursive said). \nHowever; you could also use a dictionary with the key being the object name and the values being a list containing possible commands. \n", "It seems to me that a command could be represented as a list [] or tuple (), and so could a series of commands. So one possibility is that you have a list of lists of strings. Generally you want to use a dictionary only when you want to look up a value by key. For example, if you knew the name of a command (wrt a shape) and wanted to know which parameters were passed to that command, you could have a dictionary mapping from string to list.\nIf you post more about how you plan to use this data, I could give a better answer.\nHere is a link to the Python documentation on basic data structures, which should be very helpful: http://docs.python.org/tutorial/datastructures.html\nEdit: in response to first comment, do you need to store the commands or just read them from input one by one and execute them?\n", "What about this?\nExample\ns = {'Rectangle':\n {'ChangeColor':'green','FillStyle':'hatch',\n 'Dimension1': 10, 'Dimension2':15}}\ns['Triangle'] = {'ChangeColor':'red','FillStyle':'hatch',\n 'Dimension1': 10, 'Dimension2':15, 'Dimension3':5}\n\nfor k, v in s.iteritems():\n print k\n for k1, v1 in v.iteritems():\n print \" \", k1, \"=\", v1\n\nResult:\nTriangle\n Dimension1 = 10\n Dimension2 = 15\n Dimension3 = 5\n ChangeColor = red\n FillStyle = hatch\nRectangle\n Dimension1 = 10\n Dimension2 = 15\n ChangeColor = green\n FillStyle = hatch\n\n", "I would store the commands as a list of lists, or of tuples, depending on whether or not I thought I'd modify commands. Note that argument unpacking in Python makes for a very simple mechanism for executing these commands, e.g.:\nclass Shape(object):\n def background(self, color):\n print \"background:\", color\n def foreground(self, color):\n print \"foreground:\", color\n def rect(self, left, top, right, bottom):\n print \"rect:\", left, top, right, bottom\n def execute_commands(self, command_list):\n for command in command_list:\n if hasattr(self, command[0]):\n getattr(self, command[0])(*command[1:])\n\n>>> s = Shape()\n>>> c = [('background', 'blue'), ('foreground', 'yellow'), ('rect', 10, 0, 20, 20)]\n>>> s.execute_commands(c)\nbackground: blue\nforeground: yellow\nrect: 10 0 20 20\n\n" ]
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002028723_dictionary_python.txt
Q: Writing a LaTeX document with Python code snippets I am using LaTeX to write a document about Python. This document will contain code snippets (examples). I could use the verbatim environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight would be a plus. Thanks. Edit: I must point out that the package minted is exactly what I was looking for. It has beautiful syntax highlighting and it is very simple to use. Check this question to know more about it. A: Take a look at this question Source code highlighting in LaTeX for more information. You should also look at the pygments program for source code highlighting. I personally use Emacs org-mode with #+BEGIN_SRC python and let htmlize.el take care of the highlighting during export. You can see a sample here (This is an HTML export but with the latest version of org-mode, it can use the listings LaTeX package to colourise exported PDFs too). A: Use Docutils and RST for this. It has Latex with Syntax highlighting. http://docutils.sourceforge.net/docs/user/latex.html A: The LaTeX Listings package seems to know about Python. Worth taking a look at. Mark
Writing a LaTeX document with Python code snippets
I am using LaTeX to write a document about Python. This document will contain code snippets (examples). I could use the verbatim environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight would be a plus. Thanks. Edit: I must point out that the package minted is exactly what I was looking for. It has beautiful syntax highlighting and it is very simple to use. Check this question to know more about it.
[ "Take a look at this question Source code highlighting in LaTeX for more information.\nYou should also look at the pygments program for source code highlighting. \nI personally use Emacs org-mode with #+BEGIN_SRC python and let htmlize.el take care of the highlighting during export. You can see a sample here (This is an HTML export but with the latest version of org-mode, it can use the listings LaTeX package to colourise exported PDFs too).\n", "Use Docutils and RST for this. It has Latex with Syntax highlighting.\nhttp://docutils.sourceforge.net/docs/user/latex.html\n", "The LaTeX Listings package seems to know about Python. Worth taking a look at.\nMark\n" ]
[ 5, 2, 2 ]
[]
[]
[ "latex", "python" ]
stackoverflow_0002029957_latex_python.txt
Q: python - good places to check out example prog / code online? there is a year old, similar question - but in case there have been changes afoot: i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- code that i can learn from, ideally with some sort of commentary. anything come to mind? thanks A: The standard library is an excellent place to the start. It's maintained by the core python team and is of high quality with a lot of interesting idioms. I'd recommend the newer modules since they don't have much backward compatibility cruft and are more representative of the language as it is now. The older ones were written for earlier versions of Python and have some restrictions when it comes to API changes etc. The list of modules in the standard library is described at http://docs.python.org/library/. You can go through it and decide which one you want to look at (area of interest etc.). Their sources are viewable at the mercurial repo here http://hg.python.org/cpython/file/d7e85ddb1336/Lib (as of today). These are for the mainline 2.6 release. You can also checkout the repo and browse it on your local machine. You can also start up your interpreter, import a module (say os) and do a print os.__file__ to see where the source file is if you want to look at the code in your local editor. A: ActiveState Recipes is a good source for all kinds of Python scripts. But if you want to learn the basics of Python, you might just want to look at the standard library that ships with Python ("lib" directory"). A: i came across This The other day, Probably you can learn some python basics and have a laugh too! Anyways, look at the libs as they said above, they are very useful A: If you enjoy riddles: www.pythonchallenge.com If you're an intermediate C++ programmer, you're already equipped to handle to programming concepts. I like it because it gives me a reason to learn each part of the language, without being mundane 'Hello World' tasks. However, some of the riddles are pretty tough and/or unrelated to programming. Either way, doing the first few will probably be enough to get your confidence up with Python syntax.
python - good places to check out example prog / code online?
there is a year old, similar question - but in case there have been changes afoot: i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- code that i can learn from, ideally with some sort of commentary. anything come to mind? thanks
[ "The standard library is an excellent place to the start. It's maintained by the core python team and is of high quality with a lot of interesting idioms. I'd recommend the newer modules since they don't have much backward compatibility cruft and are more representative of the language as it is now. The older ones were written for earlier versions of Python and have some restrictions when it comes to API changes etc.\nThe list of modules in the standard library is described at http://docs.python.org/library/. You can go through it and decide which one you want to look at (area of interest etc.).\nTheir sources are viewable at the mercurial repo here http://hg.python.org/cpython/file/d7e85ddb1336/Lib (as of today). These are for the mainline 2.6 release. You can also checkout the repo and browse it on your local machine.\nYou can also start up your interpreter, import a module (say os) and do a print os.__file__ to see where the source file is if you want to look at the code in your local editor. \n", "ActiveState Recipes is a good source for all kinds of Python scripts. But if you want to learn the basics of Python, you might just want to look at the standard library that ships with Python (\"lib\" directory\").\n", "i came across This The other day, Probably you can learn some python basics and have a laugh too!\nAnyways, look at the libs as they said above, they are very useful\n", "If you enjoy riddles:\nwww.pythonchallenge.com\nIf you're an intermediate C++ programmer, you're already equipped to handle to programming concepts. I like it because it gives me a reason to learn each part of the language, without being mundane 'Hello World' tasks.\nHowever, some of the riddles are pretty tough and/or unrelated to programming. Either way, doing the first few will probably be enough to get your confidence up with Python syntax.\n" ]
[ 4, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002029606_python.txt
Q: Project Euler #101 - how to work around numpy polynomial overflow? Project Euler #101 I just started learning Numpy and it so far looks pretty straightforward to me. One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur. u = numpy.poly1d([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]) for i in xrange(1, 11): print(i, u(i)) The results are: (1, 1) (2, 683) (3, 44287) (4, 838861) (5, 8138021) (6, 51828151) (7, 247165843) (8, 954437177) (9, -1156861335) (10, 500974499) The last two items are clearly incorrect. The work around I can think of is factoring the coefficients by 100 u = numpy.poly1d([0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01]) for i in xrange(1, 11): print(i, int(u(i) * 100)) This time the results are correct (1, 1) (2, 682) (3, 44286) (4, 838860) (5, 8138020) (6, 51828151) (7, 247165843) (8, 954437177) (9, 3138105961L) (10, 9090909091L) Is there a better way? Does Numpy allow me to change the data type? Thanks. A: It wasn't the scaling by 100 that helped, but the fact that the numbers given were floats instead of ints, and thus had a higher range. Due to the floating-point calculations, there are some inaccuracies introduced to the calculations as you have seen. You can specify the type manually like this: u = numpy.poly1d(numpy.array([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1], dtype=numpy.int64)) The calculations for this problem fit in 64-bit ints, so this will work. The supported types are listed here. A: Interjay posted a better answer while I was writing this up, but I figured you might want an alternative anyway. Here's a simple implementation for the examples you showed: class Poly(object): def __init__(self, coefficients): assert len(coefficients) > 0 self.coefficients = coefficients def __call__(self, value): total = self.coefficients[0] for c in self.coefficients[1:]: total = total * value + c return total along with some tests assert Poly([5])(1) == 5 assert Poly([7])(1) == 7 assert Poly([2,3])(5) == 13 assert Poly([1,0,0,0,0])(-2) == 16 u = Poly([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]) for i in range(1, 11): print (i, u(i)) and the rather useless assert Poly([2,"!"])("Hello ") == "Hello Hello !"
Project Euler #101 - how to work around numpy polynomial overflow?
Project Euler #101 I just started learning Numpy and it so far looks pretty straightforward to me. One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur. u = numpy.poly1d([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]) for i in xrange(1, 11): print(i, u(i)) The results are: (1, 1) (2, 683) (3, 44287) (4, 838861) (5, 8138021) (6, 51828151) (7, 247165843) (8, 954437177) (9, -1156861335) (10, 500974499) The last two items are clearly incorrect. The work around I can think of is factoring the coefficients by 100 u = numpy.poly1d([0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01]) for i in xrange(1, 11): print(i, int(u(i) * 100)) This time the results are correct (1, 1) (2, 682) (3, 44286) (4, 838860) (5, 8138020) (6, 51828151) (7, 247165843) (8, 954437177) (9, 3138105961L) (10, 9090909091L) Is there a better way? Does Numpy allow me to change the data type? Thanks.
[ "It wasn't the scaling by 100 that helped, but the fact that the numbers given were floats instead of ints, and thus had a higher range. Due to the floating-point calculations, there are some inaccuracies introduced to the calculations as you have seen.\nYou can specify the type manually like this:\nu = numpy.poly1d(numpy.array([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1], dtype=numpy.int64))\n\nThe calculations for this problem fit in 64-bit ints, so this will work.\nThe supported types are listed here.\n", "Interjay posted a better answer while I was writing this up, but I figured you might want an alternative anyway.\nHere's a simple implementation for the examples you showed:\nclass Poly(object):\n def __init__(self, coefficients):\n assert len(coefficients) > 0\n self.coefficients = coefficients\n def __call__(self, value):\n total = self.coefficients[0]\n for c in self.coefficients[1:]:\n total = total * value + c\n return total\n\nalong with some tests\nassert Poly([5])(1) == 5\nassert Poly([7])(1) == 7\nassert Poly([2,3])(5) == 13\nassert Poly([1,0,0,0,0])(-2) == 16\nu = Poly([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1])\nfor i in range(1, 11):\n print (i, u(i))\n\nand the rather useless\nassert Poly([2,\"!\"])(\"Hello \") == \"Hello Hello !\"\n\n" ]
[ 4, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002030422_numpy_python.txt
Q: How do I get Sphinx to test code embedded in documentation? If this code is a blockquote in my documentation, what do I need to do to make Sphinx run it when the documentation is generated? I tried adding .. testcode:: import datetime def today(): return datetime.datetime.now().date() if True: today() to one of the .rst sources and the Sphinx doctest extension to conf.py, but I got an error complaining about unexpected indentation on the first line of the function body. Is Sphinx's doctest able to run functions defined in the documentation? A: The testcode directive needs a matching testoutput directive. Here's the example from the documentation. .. testcode:: print 'Output text.' .. testoutput:: :hide: :options: -ELLIPSIS, +NORMALIZE_WHITESPACE Output text.
How do I get Sphinx to test code embedded in documentation?
If this code is a blockquote in my documentation, what do I need to do to make Sphinx run it when the documentation is generated? I tried adding .. testcode:: import datetime def today(): return datetime.datetime.now().date() if True: today() to one of the .rst sources and the Sphinx doctest extension to conf.py, but I got an error complaining about unexpected indentation on the first line of the function body. Is Sphinx's doctest able to run functions defined in the documentation?
[ "The testcode directive needs a matching testoutput directive.\nHere's the example from the documentation.\n.. testcode::\n\n print 'Output text.'\n\n.. testoutput::\n :hide:\n :options: -ELLIPSIS, +NORMALIZE_WHITESPACE\n\n Output text.\n\n" ]
[ 4 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002021671_python_python_sphinx.txt
Q: Bazaar VCS under IronPython? Has anyone successfully executed the source control system Bazaar in IronPython? A: Yes, Bazaar is pure-python with optional extensions and will run on IronPython. There are a few caveats though. Firstly some changes are needed to Bazaar that haven't yet been merged with the main branch. Secondly, IronPython's slow startup time makes it unsuitable for general bzr usage, and there are are some outstanding issues due to missing modules and the like. If you want to give it a go yourself though, you can. Download and install IronPython 2.6 and Jeff Hardy's implementation of the zlib module for IronPython (follow the readme in the zip). You'll also need to copy gzip.py from the CPython standard library to the IronPython lib folder. Finally, get a release version of Bazaar so you can get a copy of a development branch. With that done, you can follow something like this (adjusting for your own paths as needed) and have a functional(ish) Bazaar-on-IronPython: >set IPYDIR="C:\Program Files\IronPython 2.6"\ >bzr branch lp:~gz/bzr/noncpython Branched 4715 revision(s). >cd noncpython >%IPYDIR%ipy setup.py build_ext --allow-python-fallback install_lib --no-compile install ... >%IPYDIR%ipy %IPYDIR%Scripts\bzr version ... Bazaar (bzr) 2.1.0dev Python interpreter: C:\Program Files\IronPython 2.6\ipy.exe 2.6.0 Python standard library: C:\Program Files\IronPython 2.6\Lib Platform: cli-32bit bzrlib: C:\Program Files\IronPython 2.6\lib\site-packages\bzrlib ... Yes, all that junk for setup.py is needed (to tell Bazaar not to compile the pyrex versions of things and disutils not to try and make pyc files). There will probably be some extra (harmless) output complaining about encodings, but you should find that most things with local branches work fine. A: There is several important modules still absent in IronPython which required to run bzr. So, AFAIK today (December 2009) is not possible to run bzr under IronPython. You may ask this question in main bzr mailing list: http://lists.canonical.com/mailman/listinfo/bazaar. Several months ago Martin (gzlist or gz) has reported about his achievements in this area.
Bazaar VCS under IronPython?
Has anyone successfully executed the source control system Bazaar in IronPython?
[ "Yes, Bazaar is pure-python with optional extensions and will run on IronPython. There are a few caveats though. Firstly some changes are needed to Bazaar that haven't yet been merged with the main branch. Secondly, IronPython's slow startup time makes it unsuitable for general bzr usage, and there are are some outstanding issues due to missing modules and the like.\nIf you want to give it a go yourself though, you can. Download and install IronPython 2.6 and Jeff Hardy's implementation of the zlib module for IronPython (follow the readme in the zip). You'll also need to copy gzip.py from the CPython standard library to the IronPython lib folder. Finally, get a release version of Bazaar so you can get a copy of a development branch.\nWith that done, you can follow something like this (adjusting for your own paths as needed) and have a functional(ish) Bazaar-on-IronPython:\n>set IPYDIR=\"C:\\Program Files\\IronPython 2.6\"\\\n\n>bzr branch lp:~gz/bzr/noncpython\nBranched 4715 revision(s).\n\n>cd noncpython\n\n>%IPYDIR%ipy setup.py build_ext --allow-python-fallback install_lib --no-compile install\n...\n\n>%IPYDIR%ipy %IPYDIR%Scripts\\bzr version\n...\nBazaar (bzr) 2.1.0dev\n Python interpreter: C:\\Program Files\\IronPython 2.6\\ipy.exe 2.6.0\n Python standard library: C:\\Program Files\\IronPython 2.6\\Lib\n Platform: cli-32bit\n bzrlib: C:\\Program Files\\IronPython 2.6\\lib\\site-packages\\bzrlib\n...\n\nYes, all that junk for setup.py is needed (to tell Bazaar not to compile the pyrex versions of things and disutils not to try and make pyc files). There will probably be some extra (harmless) output complaining about encodings, but you should find that most things with local branches work fine.\n", "There is several important modules still absent in IronPython which required to run bzr. So, AFAIK today (December 2009) is not possible to run bzr under IronPython.\nYou may ask this question in main bzr mailing list: http://lists.canonical.com/mailman/listinfo/bazaar. Several months ago Martin (gzlist or gz) has reported about his achievements in this area.\n" ]
[ 2, 1 ]
[]
[]
[ "bazaar", "dynamic_language_runtime", "ironpython", "python" ]
stackoverflow_0001909057_bazaar_dynamic_language_runtime_ironpython_python.txt
Q: Python - automating MySQL index: passing parameter I have a function with a new improved version of the code for automatic table indexing: def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,) updateIndex=1 self.cursorMySQL.execute(getIndexMySQLQuery) for row in self.cursorMySQL: indexID = row[0] self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID)) updateIndex+=1 While the query 'getIndexMySQLQuery' works fine with this syntax, the other one 'updateIndexMySQLQuery' doesn't work. Any hints or suggestion how to get that fixed? All comments and suggestions are highly appreciated. A: Second one doesn't work, because you are using three placeholders inside the query string and provide only one variable for interpolation. updateIndexMySQLQuery = """UPDATE %s SET numberID=%%s WHERE numberID=%%s;""" % (tableName,) This way the string formatting mechanism doesn't expect you to provide 3 values, as the percent signs are "escaped" (shame on me for the first version of the answer). A: Use %s to replace the table name in the beginning, but use a question mark to create a parameter replacement. updateIndexMySQLQuery = """UPDATE %s SET numberID=? WHERE numberID=?;""" % (tableName,) ... self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID)) A: thanks for the input. I just re-did the whole function. Here is how it's working and looks now: def update_tableIndex(self,tableName,indexName): getIndexMySQLQuery = """SELECT %s FROM %s;""" % (indexName,tableName,) updateIndex=1 self.cursorMySQL.execute(getIndexMySQLQuery) for row in self.cursorMySQL: indexID = row[0] updateIndexMySQLQuery = """UPDATE %s SET %s=%s WHERE %s=%s;""" % (tableName, indexName,updateIndex, indexName,indexID) self.cursorMySQL.execute(updateIndexMySQLQuery) updateIndex+=1 So, the only thing to do is to inform the column name and the table name as parameters. It allows to re-use the code for all other tables in the database. Hope this can be useful for others too.
Python - automating MySQL index: passing parameter
I have a function with a new improved version of the code for automatic table indexing: def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,) updateIndex=1 self.cursorMySQL.execute(getIndexMySQLQuery) for row in self.cursorMySQL: indexID = row[0] self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID)) updateIndex+=1 While the query 'getIndexMySQLQuery' works fine with this syntax, the other one 'updateIndexMySQLQuery' doesn't work. Any hints or suggestion how to get that fixed? All comments and suggestions are highly appreciated.
[ "Second one doesn't work, because you are using three placeholders inside the query string and provide only one variable for interpolation.\nupdateIndexMySQLQuery = \"\"\"UPDATE %s \nSET numberID=%%s WHERE numberID=%%s;\"\"\" % (tableName,)\n\nThis way the string formatting mechanism doesn't expect you to provide 3 values, as the percent signs are \"escaped\" (shame on me for the first version of the answer). \n", "Use %s to replace the table name in the beginning, but use a question mark to create a parameter replacement.\nupdateIndexMySQLQuery = \"\"\"UPDATE %s \nSET numberID=? WHERE numberID=?;\"\"\" % (tableName,)\n...\n self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID))\n\n", "thanks for the input. I just re-did the whole function. Here is how it's working and looks now:\ndef update_tableIndex(self,tableName,indexName):\n\n getIndexMySQLQuery = \"\"\"SELECT %s\n FROM %s;\"\"\" % (indexName,tableName,)\n\n updateIndex=1\n self.cursorMySQL.execute(getIndexMySQLQuery)\n for row in self.cursorMySQL:\n indexID = row[0]\n\n updateIndexMySQLQuery = \"\"\"UPDATE %s \n SET %s=%s WHERE \n %s=%s;\"\"\" % (tableName,\n indexName,updateIndex,\n indexName,indexID)\n\n self.cursorMySQL.execute(updateIndexMySQLQuery)\n updateIndex+=1\n\nSo, the only thing to do is to inform the column name and the table name as parameters. It allows to re-use the code for all other tables in the database.\nHope this can be useful for others too.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "automation", "mysql", "parameters", "python" ]
stackoverflow_0002031401_automation_mysql_parameters_python.txt
Q: Python logging over multiple files I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4. My program consists of several different python files, from which I want to send logging messages to a text file and, potentially, the screen. I imagine this is a common thing to do so I'm messing this up somewhere. What my code is doing at the minute is logging to the text file correctly, kinda. But logging to the screen is being duplicated, one with the specified formatting, and one without. Also, when I turn off the screen output, I'm still getting the text printed once, which I don't want - I just want it to be logged to the file. Anyway, some code: #logger.py import logging from logging.handlers import RotatingFileHandler import os def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG): logdir = os.path.abspath(logdir) if not os.path.exists(logdir): os.mkdir(logdir) log = logging.getLogger('stumbler') log.setLevel(loglevel) log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s") if txtlog: txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5) txt_handler.doRollover() txt_handler.setFormatter(log_formatter) log.addHandler(txt_handler) log.info("Logger initialised.") if scrnlog: console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) log.addHandler(console_handler) Nothing unusual there. #core.py import logging corelog = logging.getLogger('stumbler.core') # From what I understand of the docs, this should work :/ class Stumbler: [...] corelog.debug("Messages and rainbows...") The screen output shows how this is being duplicated: 2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3 DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3 2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe Although the textfile is getting the correctly formatted output, turning the screen logging off in logger.py still has the incorrectly formatted output displayed. From what I understand of the docs, calling corelog.debug(), seeing as corelog is a child of the "stumbler" logger, it should use that formatting and output the logs as such. Apologies for the essay over such a trivial issue. TL;DR: How do I do logging from multiple files? A: Are you sure no other logging setup is being done in anything you import. The incorrect output in your console logs look like the default configuration for a logger, so something else may be setting that up. Running this quick test script: import logging from logging.handlers import RotatingFileHandler import os def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG): logdir = os.path.abspath(logdir) if not os.path.exists(logdir): os.mkdir(logdir) log = logging.getLogger('stumbler') log.setLevel(loglevel) log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s") if txtlog: txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5) txt_handler.doRollover() txt_handler.setFormatter(log_formatter) log.addHandler(txt_handler) log.info("Logger initialised.") if scrnlog: console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) log.addHandler(console_handler) setup_logging('/tmp/logs') corelog = logging.getLogger('stumbler.core') corelog.debug("Messages and rainbows...") yields this result: 2010-01-08 15:39:25,335 - DEBUG :: Messages and rainbows... and in my /tmp/logs/Stumbler.log 2010-01-08 15:39:25,335 - INFO :: Logger initialised. 2010-01-08 15:39:25,335 - DEBUG :: Messages and rainbows... This worked as expected when I ran it in python 2.4, 2.5, and 2.6.4
Python logging over multiple files
I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4. My program consists of several different python files, from which I want to send logging messages to a text file and, potentially, the screen. I imagine this is a common thing to do so I'm messing this up somewhere. What my code is doing at the minute is logging to the text file correctly, kinda. But logging to the screen is being duplicated, one with the specified formatting, and one without. Also, when I turn off the screen output, I'm still getting the text printed once, which I don't want - I just want it to be logged to the file. Anyway, some code: #logger.py import logging from logging.handlers import RotatingFileHandler import os def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG): logdir = os.path.abspath(logdir) if not os.path.exists(logdir): os.mkdir(logdir) log = logging.getLogger('stumbler') log.setLevel(loglevel) log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s") if txtlog: txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5) txt_handler.doRollover() txt_handler.setFormatter(log_formatter) log.addHandler(txt_handler) log.info("Logger initialised.") if scrnlog: console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) log.addHandler(console_handler) Nothing unusual there. #core.py import logging corelog = logging.getLogger('stumbler.core') # From what I understand of the docs, this should work :/ class Stumbler: [...] corelog.debug("Messages and rainbows...") The screen output shows how this is being duplicated: 2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3 DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3 2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe Although the textfile is getting the correctly formatted output, turning the screen logging off in logger.py still has the incorrectly formatted output displayed. From what I understand of the docs, calling corelog.debug(), seeing as corelog is a child of the "stumbler" logger, it should use that formatting and output the logs as such. Apologies for the essay over such a trivial issue. TL;DR: How do I do logging from multiple files?
[ "Are you sure no other logging setup is being done in anything you import.\nThe incorrect output in your console logs look like the default configuration for a logger, so something else may be setting that up. \nRunning this quick test script:\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport os\n\ndef setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG):\n logdir = os.path.abspath(logdir)\n\n if not os.path.exists(logdir):\n os.mkdir(logdir)\n\n log = logging.getLogger('stumbler')\n log.setLevel(loglevel)\n\n log_formatter = logging.Formatter(\"%(asctime)s - %(levelname)s :: %(message)s\")\n\n if txtlog:\n txt_handler = RotatingFileHandler(os.path.join(logdir, \"Stumbler.log\"), backupCount=5)\n txt_handler.doRollover()\n txt_handler.setFormatter(log_formatter)\n log.addHandler(txt_handler)\n log.info(\"Logger initialised.\")\n\n if scrnlog:\n console_handler = logging.StreamHandler()\n console_handler.setFormatter(log_formatter)\n log.addHandler(console_handler)\n\n\n\nsetup_logging('/tmp/logs')\ncorelog = logging.getLogger('stumbler.core')\ncorelog.debug(\"Messages and rainbows...\")\n\nyields this result:\n\n2010-01-08 15:39:25,335 - DEBUG ::\n Messages and rainbows...\n\nand in my /tmp/logs/Stumbler.log\n\n2010-01-08 15:39:25,335 - INFO ::\n Logger initialised. 2010-01-08\n 15:39:25,335 - DEBUG :: Messages and\n rainbows...\n\nThis worked as expected when I ran it in python 2.4, 2.5, and 2.6.4\n" ]
[ 12 ]
[]
[]
[ "error_logging", "logging", "python" ]
stackoverflow_0002031394_error_logging_logging_python.txt
Q: Optimize Game-of-Life iteration over 80x60 RGB pixel array Okay, so I've got a piece of Python code which really needs optimizing. It's a Game-of-Life iteration over a small (80x60-pixel) image and extracts the RGB values from it. currently using nested for-loops; I'd rather swap out those for loops for the faster map() c function, but if I do that I can't figure out how I can get the x,y values, nor the local values defined out of the scope of the functions I'd need to define. would using map() be any faster than this current set of for loops? How could I use it and still get x,y? I currently use pygame Surfaces, and I've tried the surfarray/pixelarray modules, but since I'm changing/getting every pixel, it's a lot slower than Surface.get_at()/set_at(). Also, slightly irrelevant... do you think this could be made quicker if Python wasn't traversing a list of numbers but just incrementing a number, like in other languages? Why doesn't python include a normal for() as well as their foreach()? The amount of conditionals there probably makes things slower too, right? The slowest part is checking for neighbours (where it builds the list n)... I replaced that whole bit with slice access on a 2D array but it doesn't work properly. Redacted version of code: xr = xrange(80) yr = xrange(60) # surface is an instance of pygame.Surface get_at = surface.get_at() set_at = surface.set_at() for x in xr: # .... for y in yr: # ... pixelR = get_at((x,y))[0] pixelG = get_at((x,y))[1] pixelB = get_at((x,y))[2] # ... more complex stuff here which changes R,G,B values independently of each other set_at((x,y),(pixelR,pixelG,pixelB)) Full version of the function: # xr, yr = xrange(80), xrange(60) def live(surface,xr,yr): randint = random.randint set_at = surface.set_at get_at = surface.get_at perfect = perfectNeighbours # minN = minNeighbours # All global variables that're defined in a config file. maxN = maxNeighbours # pos = actual # actual = (80,60) n = [] append = n.append NEIGHBOURS = 0 for y in yr: # going height-first for aesthetic reasons. decay = randint(1,maxDecay) growth = randint(1,maxGrowth) for x in xr: r, g, b, a = get_at((x,y)) del n[:] NEIGHBOURS = 0 if x>0 and y>0 and x<pos[0]-1 and y<pos[1]-1: append(get_at((x-1,y-1))[1]) append(get_at((x+1,y-1))[1]) append(get_at((x,y-1))[1]) append(get_at((x-1,y))[1]) append(get_at((x+1,y))[1]) append(get_at((x-1,y+1))[1]) append(get_at((x+1,y+1))[1]) append(get_at((x,y+1))[1]) for a in n: if a > 63: NEIGHBOURS += 1 if NEIGHBOURS == 0 and (r,g,b) == (0,0,0): pass else: if NEIGHBOURS < minN or NEIGHBOURS > maxN: g = 0 b = 0 elif NEIGHBOURS==perfect: g += growth if g > 255: g = 255 b += growth if b > growth: b = growth else: if g > 10: r = g-10 if g > 200: b = g-100 if r > growth: g = r g -= decay if g < 0: g = 0 b = 0 r -= 1 if r < 0: r = 0 set_at((x,y),(r,g,b)) A: What's making your code slow is probably not the loops, they are incredibly fast. What slows done your code are the number of function calls. For example pixelR = get_at((x,y))[0] pixelG = get_at((x,y))[1] pixelB = get_at((x,y))[2] is a lot slower than (about 3 times I guess) r, g, b, a = get_at((x,y)) Every get_at, set_at call locks the surface, therefore it's faster to directly access the pixels using the available methods. The one that seems most reasonable is Surface.get_buffer. Using map doesn't work in your example, because you need the indexes. With as few as 80 and 60 numbers it might even be faster to use range() instead of xrange(). A: map(do_stuff, ((x, y) for x in xrange(80) for y in xrange(60))) where do_stuff would presumably be defined like so: def do_stuff(coords): r, g, b, a = get_at(coords) # ... whatever you need to do with those ... set_at(coords, (r, g, b)) You could alternatively use a list comprehension instead of a generator expression as the second argument to map (replace ((x, y) ...) with [(x, y) ...]) and use range instead of xrange. I'd say that it's not very likely to have a significant effect on performance, though. Edit: Note that gs is certainly right about the for loops not being the main thing in need of optimisation in your code... Cutting down on superfluous calls to get_at is more important. In fact, I'm not sure if replacing the loops with map will actually improve performance here at all... Having said that, I find the map version more readable (perhaps because of my FP background...), so here you go anyway. ;-) A: Since you are reading and rewriting every pixel, I think you can get the best speed improvement by not using a Surface. I suggest first taking your 80x60 image and converting it to a plain bitmap file with 32-bit pixels. Then read the pixel data into a python array object. Now you can walk over the array object, reading values, calculating new values, and poking the new values into place with maximum speed. When done, save your new bitmap image, and then convert it to a Surface. You could also use 24-bit pixels, but that should be slower. 32-bit pixels means one pixel is one 32-bit integer value, which makes the array of pixels much easier to index. 24-bit packed pixels means each pixel is 3 bytes, which is much more annoying to index into. I believe you will gain much more speed out of this approach than by trying to avoid the use of for. If you try this, please post something here to let us know how well it worked or didn't. Good luck. EDIT: I thought that an array has only a single index. I'm not sure how you managed to get two indexes to work. I was expecting you to do something like this: def __i(x, y): assert(0 <= x < 80) assert(0 <= y < 60) i = (y*80 + x) * 4 return i def red(x, y): return __a[__i(x, y)] def green(x, y): return __a[__i(x, y) + 1] def blue(x, y): return __a[__i(x, y) + 2] def rgb(x, y): i = __i(x, y) return __a[i], __a[i + 1], __a[i + 2] def set_rgb(x, y, r, g, b): i = __i(x, y) _a[i] = r _a[i + 1] = g _a[i + 2] = b # example: r, g, b = rgb(23, 33) Since a Python array can only hold a single type, you will want to set the type to "unsigned byte" and then index like I showed. Where of course __a is the actual array variable. If none of this is helpful, try converting your bitmap into a list, or perhaps three lists. You can use nested lists to get 2D addressing. I hope this helps. If it is not helpful, then I am not understanding what you are doing; if you explain more I'll try to improve the answer.
Optimize Game-of-Life iteration over 80x60 RGB pixel array
Okay, so I've got a piece of Python code which really needs optimizing. It's a Game-of-Life iteration over a small (80x60-pixel) image and extracts the RGB values from it. currently using nested for-loops; I'd rather swap out those for loops for the faster map() c function, but if I do that I can't figure out how I can get the x,y values, nor the local values defined out of the scope of the functions I'd need to define. would using map() be any faster than this current set of for loops? How could I use it and still get x,y? I currently use pygame Surfaces, and I've tried the surfarray/pixelarray modules, but since I'm changing/getting every pixel, it's a lot slower than Surface.get_at()/set_at(). Also, slightly irrelevant... do you think this could be made quicker if Python wasn't traversing a list of numbers but just incrementing a number, like in other languages? Why doesn't python include a normal for() as well as their foreach()? The amount of conditionals there probably makes things slower too, right? The slowest part is checking for neighbours (where it builds the list n)... I replaced that whole bit with slice access on a 2D array but it doesn't work properly. Redacted version of code: xr = xrange(80) yr = xrange(60) # surface is an instance of pygame.Surface get_at = surface.get_at() set_at = surface.set_at() for x in xr: # .... for y in yr: # ... pixelR = get_at((x,y))[0] pixelG = get_at((x,y))[1] pixelB = get_at((x,y))[2] # ... more complex stuff here which changes R,G,B values independently of each other set_at((x,y),(pixelR,pixelG,pixelB)) Full version of the function: # xr, yr = xrange(80), xrange(60) def live(surface,xr,yr): randint = random.randint set_at = surface.set_at get_at = surface.get_at perfect = perfectNeighbours # minN = minNeighbours # All global variables that're defined in a config file. maxN = maxNeighbours # pos = actual # actual = (80,60) n = [] append = n.append NEIGHBOURS = 0 for y in yr: # going height-first for aesthetic reasons. decay = randint(1,maxDecay) growth = randint(1,maxGrowth) for x in xr: r, g, b, a = get_at((x,y)) del n[:] NEIGHBOURS = 0 if x>0 and y>0 and x<pos[0]-1 and y<pos[1]-1: append(get_at((x-1,y-1))[1]) append(get_at((x+1,y-1))[1]) append(get_at((x,y-1))[1]) append(get_at((x-1,y))[1]) append(get_at((x+1,y))[1]) append(get_at((x-1,y+1))[1]) append(get_at((x+1,y+1))[1]) append(get_at((x,y+1))[1]) for a in n: if a > 63: NEIGHBOURS += 1 if NEIGHBOURS == 0 and (r,g,b) == (0,0,0): pass else: if NEIGHBOURS < minN or NEIGHBOURS > maxN: g = 0 b = 0 elif NEIGHBOURS==perfect: g += growth if g > 255: g = 255 b += growth if b > growth: b = growth else: if g > 10: r = g-10 if g > 200: b = g-100 if r > growth: g = r g -= decay if g < 0: g = 0 b = 0 r -= 1 if r < 0: r = 0 set_at((x,y),(r,g,b))
[ "What's making your code slow is probably not the loops, they are incredibly fast.\nWhat slows done your code are the number of function calls. For example\npixelR = get_at((x,y))[0]\npixelG = get_at((x,y))[1]\npixelB = get_at((x,y))[2]\n\nis a lot slower than (about 3 times I guess)\nr, g, b, a = get_at((x,y))\n\nEvery get_at, set_at call locks the surface, therefore it's faster to directly access the pixels using the available methods. The one that seems most reasonable is Surface.get_buffer.\nUsing map doesn't work in your example, because you need the indexes. With as few as 80 and 60 numbers it might even be faster to use range() instead of xrange().\n", "map(do_stuff, ((x, y) for x in xrange(80) for y in xrange(60)))\n\nwhere do_stuff would presumably be defined like so:\ndef do_stuff(coords):\n r, g, b, a = get_at(coords)\n # ... whatever you need to do with those ...\n set_at(coords, (r, g, b))\n\nYou could alternatively use a list comprehension instead of a generator expression as the second argument to map (replace ((x, y) ...) with [(x, y) ...]) and use range instead of xrange. I'd say that it's not very likely to have a significant effect on performance, though.\nEdit: Note that gs is certainly right about the for loops not being the main thing in need of optimisation in your code... Cutting down on superfluous calls to get_at is more important. In fact, I'm not sure if replacing the loops with map will actually improve performance here at all... Having said that, I find the map version more readable (perhaps because of my FP background...), so here you go anyway. ;-)\n", "Since you are reading and rewriting every pixel, I think you can get the best speed improvement by not using a Surface.\nI suggest first taking your 80x60 image and converting it to a plain bitmap file with 32-bit pixels. Then read the pixel data into a python array object. Now you can walk over the array object, reading values, calculating new values, and poking the new values into place with maximum speed. When done, save your new bitmap image, and then convert it to a Surface.\nYou could also use 24-bit pixels, but that should be slower. 32-bit pixels means one pixel is one 32-bit integer value, which makes the array of pixels much easier to index. 24-bit packed pixels means each pixel is 3 bytes, which is much more annoying to index into.\nI believe you will gain much more speed out of this approach than by trying to avoid the use of for. If you try this, please post something here to let us know how well it worked or didn't. Good luck.\nEDIT: I thought that an array has only a single index. I'm not sure how you managed to get two indexes to work. I was expecting you to do something like this:\ndef __i(x, y):\n assert(0 <= x < 80)\n assert(0 <= y < 60)\n i = (y*80 + x) * 4\n return i\ndef red(x, y):\n return __a[__i(x, y)]\ndef green(x, y):\n return __a[__i(x, y) + 1]\ndef blue(x, y):\n return __a[__i(x, y) + 2]\ndef rgb(x, y):\n i = __i(x, y)\n return __a[i], __a[i + 1], __a[i + 2]\ndef set_rgb(x, y, r, g, b):\n i = __i(x, y)\n _a[i] = r\n _a[i + 1] = g\n _a[i + 2] = b\n\n# example:\nr, g, b = rgb(23, 33)\n\nSince a Python array can only hold a single type, you will want to set the type to \"unsigned byte\" and then index like I showed.\nWhere of course __a is the actual array variable.\nIf none of this is helpful, try converting your bitmap into a list, or perhaps three lists. You can use nested lists to get 2D addressing.\nI hope this helps. If it is not helpful, then I am not understanding what you are doing; if you explain more I'll try to improve the answer.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "arrays", "conways_game_of_life", "optimization", "pixels", "python" ]
stackoverflow_0002031216_arrays_conways_game_of_life_optimization_pixels_python.txt
Q: Debugging Django Forms validation errors One of my forms fails on form.is_valid() First time I debug a Django form so I am not too sure where to look forms.py class ImageForm(forms.ModelForm): def __init__(self,user,*args,**kwargs): super(ImageForm,self ).__init__(*args,**kwargs) # populates the form class Meta: model = KMSImageP fields = ('name', 'caption', 'image', ) models.py from photologue.models import ImageModel class KMSImageP(ImageModel): name = models.CharField(max_length=100) slug = AutoSlugField(max_length=45, unique=True, populate_from='name') num_views = models.PositiveIntegerField(editable=False, default=0) caption = models.TextField(_('caption'), blank I got that >>>> image_form.__dict__['_errors'] >>>>django.forms.util.ErrorDict({'image': django.forms.util.ErrorList([<django.utils.functional.__proxy__ object at 0xecc770>])}) So I am guessing that my 'image' field (an ImageField inherited from an abstract base class) is the cause of the failure but I don't know why. I've tried changing the type of the attributes to FileField (as my other forms use FileField to upload with no problem) but it still fails... Anyhow, I am clueless... A: You really should learn how to use debugger with Django and it's built in server- it has saved me lot's of print/dir expressions and endless edit-run-observe output-edit iterations. The most basic way to debug python applications is by using pdb It's as easy as dropping in these two lines of code: import pdb pdb.set_trace() in that part of code you want to debug. As soon as the second line is executed, program execution stops at that point and you have to switch to console and you can observe the state and contents of variables, execute next line, go to next breakpoint and so on. Just type ? and press enter. Of course, if you use sophisticated enough IDE debugging is much more easier than this, but this should get you a general idea of how to use debugger.
Debugging Django Forms validation errors
One of my forms fails on form.is_valid() First time I debug a Django form so I am not too sure where to look forms.py class ImageForm(forms.ModelForm): def __init__(self,user,*args,**kwargs): super(ImageForm,self ).__init__(*args,**kwargs) # populates the form class Meta: model = KMSImageP fields = ('name', 'caption', 'image', ) models.py from photologue.models import ImageModel class KMSImageP(ImageModel): name = models.CharField(max_length=100) slug = AutoSlugField(max_length=45, unique=True, populate_from='name') num_views = models.PositiveIntegerField(editable=False, default=0) caption = models.TextField(_('caption'), blank I got that >>>> image_form.__dict__['_errors'] >>>>django.forms.util.ErrorDict({'image': django.forms.util.ErrorList([<django.utils.functional.__proxy__ object at 0xecc770>])}) So I am guessing that my 'image' field (an ImageField inherited from an abstract base class) is the cause of the failure but I don't know why. I've tried changing the type of the attributes to FileField (as my other forms use FileField to upload with no problem) but it still fails... Anyhow, I am clueless...
[ "You really should learn how to use debugger with Django and it's built in server- it has saved me lot's of print/dir expressions and endless edit-run-observe output-edit iterations.\nThe most basic way to debug python applications is by using pdb\nIt's as easy as dropping in these two lines of code:\nimport pdb\npdb.set_trace()\n\nin that part of code you want to debug. As soon as the second line is executed, program execution stops at that point and you have to switch to console and you can observe the state and contents of variables, execute next line, go to next breakpoint and so on. Just type ? and press enter.\nOf course, if you use sophisticated enough IDE debugging is much more easier than this, but this should get you a general idea of how to use debugger.\n" ]
[ 5 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002030896_django_django_forms_python.txt
Q: Any way to set request headers when doing a request using urllib in Python 2.x? I am trying to make an HTTP request in Python 2.6.4, using the urllib module. Is there any way to set the request headers? I am sure that this is possible using urllib2, but I would prefer to use urllib since it seems simpler. A: There isn't any way to do that, which is precisely the reason urllib is deprecated in favour of urllib2. So just use urllib2 rather than writing new code to a deprecated interface. A: I don't think so, but urllib2 can. Check out the documentation of urllib2.Request. A: You could actually overwrite methods in FancyURLopener, but that does not seem right (see http://docs.python.org/library/urllib.html#urllib._urlopener). You could also use httplib which basically is the backend for urllib. But anyhow, using urllib2 might be the best idea. It is not difficult to use. (I use it all the time.)
Any way to set request headers when doing a request using urllib in Python 2.x?
I am trying to make an HTTP request in Python 2.6.4, using the urllib module. Is there any way to set the request headers? I am sure that this is possible using urllib2, but I would prefer to use urllib since it seems simpler.
[ "There isn't any way to do that, which is precisely the reason urllib is deprecated in favour of urllib2. So just use urllib2 rather than writing new code to a deprecated interface.\n", "I don't think so, but urllib2 can. Check out the documentation of urllib2.Request.\n", "You could actually overwrite methods in FancyURLopener, but that does not seem right (see http://docs.python.org/library/urllib.html#urllib._urlopener). You could also use httplib which basically is the backend for urllib. \nBut anyhow, using urllib2 might be the best idea. It is not difficult to use. (I use it all the time.)\n" ]
[ 2, 1, 1 ]
[]
[]
[ "http", "python", "python_2.6", "python_2.x", "urllib" ]
stackoverflow_0002031745_http_python_python_2.6_python_2.x_urllib.txt
Q: how can i use django.utils.safestring.py from django.utils.safestring import * print SafeString('\u3042') print '\u3042' \u3042 \u3042 who can give me a better example. thanks A: An instance of django.utils.safestring.SafeString is a string which has already been vetted or escaped, so it contains no characters that could give HTML a parsing problem ('<', '>', '&'). See the docs.
how can i use django.utils.safestring.py
from django.utils.safestring import * print SafeString('\u3042') print '\u3042' \u3042 \u3042 who can give me a better example. thanks
[ "An instance of django.utils.safestring.SafeString is a string which has already been vetted or escaped, so it contains no characters that could give HTML a parsing problem ('<', '>', '&'). See the docs.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002031788_django_python.txt
Q: How do I sort this list? I have a list of lists. List<List<T>> li = { {a1,a2,a3 ... aN}, {b1,b2,b3 ... bN}, ... }; double foo(List<T> list) { // do something // e.g {1,2,3} // it = 1 + 2 + 3 return it; } Now I want to sort li in such a way that higher the foo(x) for a x higher it should appear in a sorted list. What is the best way in C#/Python/any other lang to this? A: With a little bit of LINQ: var q = from el in li orderby foo(el) select el; li = q.ToList(); A: The Haskell solution is particularly elegant with the on combinator from Data.Function. import Data.Function (on) import Data.List (sortBy) lists = [ [ 5, 6, 8 ] , [ 1, 2, 3 ] ] main = do print $ sortBy (compare `on` foo) lists where foo = sum Output: [[1,2,3],[5,6,8]] There's also comparing from Data.Ord that lets us instead write main = do print $ sortBy (comparing foo) lists where foo = sum The definition of comparing is a straightforward comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering comparing p x y = compare (p x) (p y) but we could also define it in terms of on: comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering comparing f = compare `on` f or completely point-free with comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering comparing = (compare `on`) Haskell manipulates functions as powerfully as Perl manipulates strings. A: This is the Python way: Just pass the function as the key argument to sorted() or .sort(): >>> mylist = [123, 765, 4, 13] >>> def mod5(x): ... return x%5 ... >>> sorted(mylist, key = mod5) [765, 123, 13, 4] >>> sorted(mylist, key = mod5, reverse = True) [4, 123, 13, 765] A: Ruby: mylist = [[1,2,3], [3,5,9], [1,1,1], [10,23,14]] sortedlist = mylist.sort {|a,b| b.inject {|sum, n| sum + n } <=> a.inject {|sum,n| sum + n}} I'm not sure the rules of Code Golf and I didn't write a foo method, but the sum could easily occur in foo. My test output: puts sortedlist.inspect [[10, 23, 14], [3, 5, 9], [1, 2, 3], [1, 1, 1]] A: In Perl, this is often done with the well-known Schwartzian transform. use List::Util qw(sum); @li = map {$$_[0]} sort {$$a[1] <=> $$b[1]} map {[$_, sum(@$_)]} @li; Reusing Sort::Key is better, though. use List::Util qw(sum); use Sort::Key qw(nkeysort); @li = nkeysort {sum(@$_)} @li; A: Any other language? Ok, here's some F#: Example: sort by sum: let foo = List.sum let li = [[1;2];[42;1];[3;4]] let result = li |> List.sortBy (fun el -> foo el) Result (F# interactive): val result : int list list = [[1; 2]; [3; 4]; [42; 1]] Golfed: let result = li |> List.sortBy (fun el -> foo el) //shorter let res = li |> List.sortBy foo //evn shrtr let r=List.sortBy foo li The C# version: var result = li.OrderBy(el=>el.Sum()); A: in erlang: -module (codegolfs). -export ([sortmain/0]). sortmain() -> sort( fun (SubList) -> lists:sum(SubList) end, [ [1,2,3],[1,3],[2,5,6] ]). % output: [[2,5,6],[1,2,3],[1,3]] sort(Fun,List) -> lists:sort( fun(A,B) -> Fun(A) < Fun(B) end,List ). A: Ruby (shamelessly copying Beanish's input data): list = [ [1, 2, 3], [3, 5, 9], [1, 1, 1], [10, 23, 14] ] p list.sort_by { |a| -a.inject(&:+) } # => [[10, 23, 14], [3, 5, 9], [1, 2, 3], [1, 1, 1]] A: Clojure: (let [lst '((1 2 3) (3 5 9) (1 1 1) (10 23 14))] (sort #(> (foo %1) (foo %2)) lst)) A: You could adapt any of the popular sorting routines to do this. Just use foo(x) for comparison rather than x. A: Tcl: proc foo nums {tcl::mathop::+ {*}$nums} set l {{1 2 3} {4 5 6} {3} {42 -40}} lsort -command {apply {{a b} {expr {[foo $a] - [foo $b]}}}} $l # => {42 -40} 3 {1 2 3} {4 5 6}
How do I sort this list?
I have a list of lists. List<List<T>> li = { {a1,a2,a3 ... aN}, {b1,b2,b3 ... bN}, ... }; double foo(List<T> list) { // do something // e.g {1,2,3} // it = 1 + 2 + 3 return it; } Now I want to sort li in such a way that higher the foo(x) for a x higher it should appear in a sorted list. What is the best way in C#/Python/any other lang to this?
[ "With a little bit of LINQ:\nvar q = from el in li\n orderby foo(el)\n select el;\nli = q.ToList();\n\n", "The Haskell solution is particularly elegant with the on combinator from Data.Function.\nimport Data.Function (on)\nimport Data.List (sortBy)\n\nlists = [ [ 5, 6, 8 ]\n , [ 1, 2, 3 ]\n ]\n\nmain = do\n print $ sortBy (compare `on` foo) lists\n where\n foo = sum\n\nOutput:\n[[1,2,3],[5,6,8]]\nThere's also comparing from Data.Ord that lets us instead write\nmain = do\n print $ sortBy (comparing foo) lists\n where\n foo = sum\n\nThe definition of comparing is a straightforward\ncomparing :: (Ord a) => (b -> a) -> b -> b -> Ordering\ncomparing p x y = compare (p x) (p y)\n\nbut we could also define it in terms of on:\ncomparing :: (Ord b) => (a -> b) -> a -> a -> Ordering\ncomparing f = compare `on` f\n\nor completely point-free with\ncomparing :: (Ord b) => (a -> b) -> a -> a -> Ordering\ncomparing = (compare `on`)\n\nHaskell manipulates functions as powerfully as Perl manipulates strings.\n", "This is the Python way: Just pass the function as the key argument to sorted() or .sort():\n>>> mylist = [123, 765, 4, 13]\n>>> def mod5(x):\n... return x%5\n...\n>>> sorted(mylist, key = mod5)\n[765, 123, 13, 4]\n>>> sorted(mylist, key = mod5, reverse = True)\n[4, 123, 13, 765]\n\n", "Ruby:\nmylist = [[1,2,3],\n [3,5,9],\n [1,1,1],\n [10,23,14]]\n\nsortedlist = mylist.sort {|a,b| b.inject {|sum, n| sum + n } <=> a.inject {|sum,n| sum + n}}\n\nI'm not sure the rules of Code Golf and I didn't write a foo method, but the sum could easily occur in foo.\nMy test output:\nputs sortedlist.inspect\n\n[[10, 23, 14], [3, 5, 9], [1, 2, 3], [1, 1, 1]]\n", "In Perl, this is often done with the well-known Schwartzian transform.\nuse List::Util qw(sum);\n@li = map {$$_[0]} sort {$$a[1] <=> $$b[1]} map {[$_, sum(@$_)]} @li;\n\nReusing Sort::Key is better, though.\nuse List::Util qw(sum);\nuse Sort::Key qw(nkeysort);\n@li = nkeysort {sum(@$_)} @li;\n\n", "Any other language? Ok, here's some F#:\nExample: sort by sum:\nlet foo = List.sum\nlet li = [[1;2];[42;1];[3;4]]\n\nlet result = li |> List.sortBy (fun el -> foo el)\n\nResult (F# interactive):\nval result : int list list = [[1; 2]; [3; 4]; [42; 1]]\n\nGolfed:\nlet result = li |> List.sortBy (fun el -> foo el)\n//shorter\nlet res = li |> List.sortBy foo\n//evn shrtr\nlet r=List.sortBy foo li\n\nThe C# version:\nvar result = li.OrderBy(el=>el.Sum());\n\n", "in erlang:\n-module (codegolfs).\n-export ([sortmain/0]).\n\nsortmain() ->\n sort( \n fun (SubList) -> lists:sum(SubList) end,\n [ [1,2,3],[1,3],[2,5,6] ]).\n % output: [[2,5,6],[1,2,3],[1,3]]\n\nsort(Fun,List) ->\n lists:sort( fun(A,B) -> Fun(A) < Fun(B) end,List ).\n\n", "Ruby (shamelessly copying Beanish's input data):\nlist = [\n [1, 2, 3],\n [3, 5, 9],\n [1, 1, 1],\n [10, 23, 14]\n]\n\np list.sort_by { |a| -a.inject(&:+) }\n# => [[10, 23, 14], [3, 5, 9], [1, 2, 3], [1, 1, 1]]\n\n", "Clojure:\n(let [lst '((1 2 3) (3 5 9) (1 1 1) (10 23 14))] \n (sort #(> (foo %1) (foo %2)) lst))\n\n", "You could adapt any of the popular sorting routines to do this. Just use foo(x) for comparison rather than x. \n", "Tcl: \nproc foo nums {tcl::mathop::+ {*}$nums}\nset l {{1 2 3} {4 5 6} {3} {42 -40}}\nlsort -command {apply {{a b} {expr {[foo $a] - [foo $b]}}}} $l\n# => {42 -40} 3 {1 2 3} {4 5 6}\n\n" ]
[ 10, 10, 5, 2, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "c#", "haskell", "python", "ruby", "sorting" ]
stackoverflow_0002019951_c#_haskell_python_ruby_sorting.txt
Q: Is there a python hamcrest matcher library for performing XML document matching? I'm interested in both xpath matching and full document comparisons: assert_that(mydoc, hasTextAtXPath('/foo/bar', 'text')) assert_that(mydoc, matchesStructurally('<some_xml/>')) Does any matcher library exist for this? If not, what is the best place to start with for this type of comparison, so that I can write one of my own? A: lxml has XPath matching: http://codespeak.net/lxml/ A: There is a Python version of Hamcrest. It does not currently provide XML matchers. I'd be happy to work on some if you define what you need.
Is there a python hamcrest matcher library for performing XML document matching?
I'm interested in both xpath matching and full document comparisons: assert_that(mydoc, hasTextAtXPath('/foo/bar', 'text')) assert_that(mydoc, matchesStructurally('<some_xml/>')) Does any matcher library exist for this? If not, what is the best place to start with for this type of comparison, so that I can write one of my own?
[ "lxml has XPath matching: http://codespeak.net/lxml/\n", "There is a Python version of Hamcrest. It does not currently provide XML matchers. I'd be happy to work on some if you define what you need.\n" ]
[ 0, 0 ]
[]
[]
[ "hamcrest", "python", "unit_testing", "xml", "xpath" ]
stackoverflow_0001941431_hamcrest_python_unit_testing_xml_xpath.txt
Q: Scripting Python for Linux commands I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb questions. Here is my function for running the script: def runScript(): # Cannot concatenate 'str' and 'list' objects #script = rdiff + rdiffArgs script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \ + ' ' + clientName + '@' + clientHost + '::' + clientDir \ + ' ' + serverDir os.system(script) What I originally thought would be neat was to add all the variables into a list, so I could just run say script = rdiff + rdiffArgs Is there a better way to do this without all the space concatenation? Thanks for your assistance EDIT: Let me post the whole script so far. I wasn't very clear and I really appreciate your help and patience #!/usr/bin/env python import os import smtplib # Global variables rdiff = '/usr/bin/rdiff-backup' rdiffVerbosity = '-v5' rdiffStatistics = '--print-statistics' emailSmtp = 'smtp.gmail.com' smtpPort = '465' emailUsername = 'reports' emailPassword = '3kc9dl' emailTo = 'user@domain.com' emailFrom = 'internal@domain.com' serverName = 'root' serverHost = 'SV-Datasafe' serverDir = '/srv/backup/SV-Samba01' clientName = 'root' clientHost = 'SV-Samba01' clientDir = '/srv' rdiffArgs = rdiffArgs = [rdiffVerbosity, rdiffStatistics, \ clientName + '@' + clientHost + '::' \ +clientDir + ' ' + serverDir] time = '' dateStamp = datetime.now() def sendEmail(): subject = dateStamp + clientName body = clientDir + ' on ' + clientHost + ' backed up to ' + serverName + \ ' in the directory ' + serverDir + ' on ' + dateStamp message = """\ From: %s To: %s Subject: %s %s """ % (emailFrom, emailTo, subject, body) deliverEmail = smtplib.SMTP(emailSmtp, port=smtpPort) deliverEmail.login(emailUsername, emailPassword) def runScript(): # Cannot concatenate 'str' and 'list' objects #script = rdiff + rdiffArgs script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \ + ' ' + clientName + '@' + clientHost + '::' + clientDir \ + ' ' + serverDir os.system(script) # TODO:: Logging A: you can use format specifiers def runScript(): script = "%s %s %s@%s %s::%s %s" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir) os.system(script) or say your rdiffArgs is already in a list rdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir] you can join them with a space rdiffArgs = ' '.join(rdiffArgs) lastly, just so you might want to know, you can import rdiff in your script , since rdiff-backup is written in Python from rdiff_backup.Main import Main as backup task=['/etc', '/tmp/backup'] backup(task) the above backs up /etc/ to /tmp/backup. That way, you don't have to make system call to rdiff-backup. Of course, this is up to you. making system call is sometimes easier A: try to use subprocess module and pass arguments as list e.g. client = clientName + '@' + clientHost + '::' + clientDir cmd = [rdiff, rdiffVerbosity, rdiffStatistics, client , serverDir] p = Popen(cmd ", shell=True) print os.waitpid(p.pid, 0)[1] or if have args already as list use something like this cmd = [rdiff] + args A: You join paths using os.path.join You concatenate strings like so: "".join(['a', 'b']) or ", ".join(['c', 'd']) Which part is difficult? I am not sure I understand the question 100% Is this it? script = rdiff + " ".join(rdiffArgs)
Scripting Python for Linux commands
I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb questions. Here is my function for running the script: def runScript(): # Cannot concatenate 'str' and 'list' objects #script = rdiff + rdiffArgs script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \ + ' ' + clientName + '@' + clientHost + '::' + clientDir \ + ' ' + serverDir os.system(script) What I originally thought would be neat was to add all the variables into a list, so I could just run say script = rdiff + rdiffArgs Is there a better way to do this without all the space concatenation? Thanks for your assistance EDIT: Let me post the whole script so far. I wasn't very clear and I really appreciate your help and patience #!/usr/bin/env python import os import smtplib # Global variables rdiff = '/usr/bin/rdiff-backup' rdiffVerbosity = '-v5' rdiffStatistics = '--print-statistics' emailSmtp = 'smtp.gmail.com' smtpPort = '465' emailUsername = 'reports' emailPassword = '3kc9dl' emailTo = 'user@domain.com' emailFrom = 'internal@domain.com' serverName = 'root' serverHost = 'SV-Datasafe' serverDir = '/srv/backup/SV-Samba01' clientName = 'root' clientHost = 'SV-Samba01' clientDir = '/srv' rdiffArgs = rdiffArgs = [rdiffVerbosity, rdiffStatistics, \ clientName + '@' + clientHost + '::' \ +clientDir + ' ' + serverDir] time = '' dateStamp = datetime.now() def sendEmail(): subject = dateStamp + clientName body = clientDir + ' on ' + clientHost + ' backed up to ' + serverName + \ ' in the directory ' + serverDir + ' on ' + dateStamp message = """\ From: %s To: %s Subject: %s %s """ % (emailFrom, emailTo, subject, body) deliverEmail = smtplib.SMTP(emailSmtp, port=smtpPort) deliverEmail.login(emailUsername, emailPassword) def runScript(): # Cannot concatenate 'str' and 'list' objects #script = rdiff + rdiffArgs script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \ + ' ' + clientName + '@' + clientHost + '::' + clientDir \ + ' ' + serverDir os.system(script) # TODO:: Logging
[ "you can use format specifiers\ndef runScript():\n script = \"%s %s %s@%s %s::%s %s\" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir) \n os.system(script)\n\nor say your rdiffArgs is already in a list\nrdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir]\n\nyou can join them with a space\nrdiffArgs = ' '.join(rdiffArgs)\n\nlastly, just so you might want to know, you can import rdiff in your script , since rdiff-backup is written in Python\nfrom rdiff_backup.Main import Main as backup\ntask=['/etc', '/tmp/backup']\nbackup(task)\n\nthe above backs up /etc/ to /tmp/backup. That way, you don't have to make system call to rdiff-backup. Of course, this is up to you. making system call is sometimes easier\n", "try to use subprocess module and pass arguments as list e.g.\nclient = clientName + '@' + clientHost + '::' + clientDir\ncmd = [rdiff, rdiffVerbosity, rdiffStatistics, client , serverDir]\np = Popen(cmd \", shell=True)\nprint os.waitpid(p.pid, 0)[1]\n\nor if have args already as list use something like this\ncmd = [rdiff] + args\n\n", "You join paths using os.path.join\nYou concatenate strings like so: \"\".join(['a', 'b']) or \", \".join(['c', 'd'])\nWhich part is difficult? I am not sure I understand the question 100%\nIs this it?\nscript = rdiff + \" \".join(rdiffArgs)\n\n" ]
[ 5, 5, 3 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0002032228_linux_python.txt
Q: Detect if a process is already running and collaborate with it I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where: The number of producers varies. The number of consumers is constant. The producers can be started at different times by different programs or even different users. I'm using the builtin multiprocessing module, currently in Python 2.6.4., but with the intent to move to 3.1.1 eventually. Here's a basic usage scenario: Beginning state - no processes running. User starts program.py operation - one producer, five consumers running. Operation completes - five consumers running. User starts program.py operation - one producer, five consumers running. User starts program.py operation - two producers, five consumers running. Operation completes - one producer, five consumers running. Operation completes - five consumers running. User starts program.py stop and it completes - no processes running. User starts program.py start and it completes - five consumers running. User starts program.py operation - one procucer, five consumers running. Operation completes - five consumers running. User starts program.py stop and it completes - no processes running. The problem I have is that I don't know where to start on: Detecting that the consumer processes are running. Gaining access to them from a previously unrelated program. Doing 1 and 2 in a cross-platform way. Once I can do that, I know how to manage the processes. There has to be some reliable way to detect existing processes since I've seen Firefox do this to prevent multiple instances of Firefox from running, but I have no idea how to do that in Python. A: There are a couple of common ways to do your item #1 (detecting running processes), but to use them would first require that you slightly tweak your mental picture of how these background processes are started by the first invocation of the program. Think of the first program not as starting the five processes and then exiting, but rather as detecting that it is the first instance started and not exiting. It can create a file lock (one of the common approaches for preventing multiple occurrences of an application from running), or merely bind to some socket (another common approach). Either approach will raise an exception in a second instance, which then knows that it is not the first and can refocus its attention on contacting the first instance. If you're using multiprocessing, you should be able simply to use the Manager support, which involves binding to a socket to act as a server. The first program starts the processes, creates Queues, proxies, or whatever. It creates a Manager to allow access to them, possibly allowing remote access. Subsequent invocations first attempt to contact said server/Manager on the predefined socket (or using other techniques to discover the socket it's on). Instead of doing a server_forever() call they connect() and communicate using the usual multiprocessing mechanisms. A: Take a look at these different Service Discovery mechanisms: http://en.wikipedia.org/wiki/Service_discovery The basic idea is that the consumers would each register a service when they start. The producer would go through the discovery process when starting. If it finds the consumers, it binds to them. If it doesn't find them it starts up new consumers. In most all of these systems, services can typically also publish properties, so you can have each consumer uniquely identify itself and give other information to the discovering producer. Bonjour/zeroconf is pretty well supported cross-platform. You can even configure Safari to show you the zeroconf services on your local network, so you can use that to debug the service advertisement for the consumers. One side advantage of this kind of approach is that you could easily run the producers on different machines than the consumers. A: You need a client-server model on a local system. You could do this using TCP/IP sockets to communicate between your clients and servers, but it's faster to use local named pipes if you don't have the need to communicate over a network. The basic requirements for you if I understood correctly are these: 1. A producer should be able to spawn consumers if none exist already. 2. A producer should be able to communicate with consumers. 3. A producer should be able to find pre-existing consumers and communicate with them. 4. Even if a producer completes, consumers should continue running. 5. More than one producer should be able to communicate with the consumers. Let's tackle each one of these one by one: (1) is a simple process-creation problem, except that consumer (child) processes should continue running, even if the producer (parent) exits. See (4) below. (2) A producer can communicate with consumers using named pipes. See os.mkfifo() and unix man page of mkfifo() to create named pipes. (3) You need to create named pipes from the consumer processes in a well known path, when they start running. The producer can find out if any consumers are running by looking for this well-known pipe(s) in the same location. If the pipe(s) do not exist, no consumers are running, and the producers can spawn these. (4) You'll need to use os.setuid() for this, and make the consumer processes act like a daemon. See unix man page of setsid(). (5) This one is tricky. Multiple producers can communicate with the consumers using the same named pipe, but you cannot transfer more than "PIPE_BUF" amount of data from the producer to the consumer, if you want to reliably identify which producer sent the data, or if you want to prevent some kind of interleaving of data from different producers. A better way to do (5) is to have the consumers open a "control" named pipe (/tmp/control.3456, 3456 being the consumer pid) on execution. Producers first set up a communication channel using the "control" pipe. When a producer connects, it sends its pid say "1234", to the consumer on the "control" pipe, which tells the consumer to create a named pipe for data exchange with the producer, say "/tmp/data.1234". Then the producer closes the "control" pipe, and opens "/tmp/data.1234" to communicate with the consumer. Each consumer can have its own "control" pipes (use the consumer pids to distinguish between pipes of different consumers), and each producer gets its own "data" pipe.. When a producer finishes, it should clean up its data pipe or tell the consumer to do so. Similarly, when the consumer finishes, it should clean up its control pipes. A difficulty here is to prevent multiple producers from connecting to the control pipes of a single consumer at the same time. The "control" pipe here is a shared resource and you need to synchronize between different producers to access it. Use semaphores for it or file locking. See the posix_ipc python module for this. Note: I have described most of the above in terms of general UNIX semantics, but all you really need is the ability to create daemon processes, ability to create "named" pipes/queues/whatever so that they can be found by an unrelated process, and ability to synchronize between unrelated processes. You can use any python module which provides such semantics.
Detect if a process is already running and collaborate with it
I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where: The number of producers varies. The number of consumers is constant. The producers can be started at different times by different programs or even different users. I'm using the builtin multiprocessing module, currently in Python 2.6.4., but with the intent to move to 3.1.1 eventually. Here's a basic usage scenario: Beginning state - no processes running. User starts program.py operation - one producer, five consumers running. Operation completes - five consumers running. User starts program.py operation - one producer, five consumers running. User starts program.py operation - two producers, five consumers running. Operation completes - one producer, five consumers running. Operation completes - five consumers running. User starts program.py stop and it completes - no processes running. User starts program.py start and it completes - five consumers running. User starts program.py operation - one procucer, five consumers running. Operation completes - five consumers running. User starts program.py stop and it completes - no processes running. The problem I have is that I don't know where to start on: Detecting that the consumer processes are running. Gaining access to them from a previously unrelated program. Doing 1 and 2 in a cross-platform way. Once I can do that, I know how to manage the processes. There has to be some reliable way to detect existing processes since I've seen Firefox do this to prevent multiple instances of Firefox from running, but I have no idea how to do that in Python.
[ "There are a couple of common ways to do your item #1 (detecting running processes), but to use them would first require that you slightly tweak your mental picture of how these background processes are started by the first invocation of the program.\nThink of the first program not as starting the five processes and then exiting, but rather as detecting that it is the first instance started and not exiting. It can create a file lock (one of the common approaches for preventing multiple occurrences of an application from running), or merely bind to some socket (another common approach). Either approach will raise an exception in a second instance, which then knows that it is not the first and can refocus its attention on contacting the first instance.\nIf you're using multiprocessing, you should be able simply to use the Manager support, which involves binding to a socket to act as a server.\nThe first program starts the processes, creates Queues, proxies, or whatever. It creates a Manager to allow access to them, possibly allowing remote access.\nSubsequent invocations first attempt to contact said server/Manager on the predefined socket (or using other techniques to discover the socket it's on). Instead of doing a server_forever() call they connect() and communicate using the usual multiprocessing mechanisms.\n", "Take a look at these different Service Discovery mechanisms: http://en.wikipedia.org/wiki/Service_discovery\nThe basic idea is that the consumers would each register a service when they start. The producer would go through the discovery process when starting. If it finds the consumers, it binds to them. If it doesn't find them it starts up new consumers. In most all of these systems, services can typically also publish properties, so you can have each consumer uniquely identify itself and give other information to the discovering producer.\nBonjour/zeroconf is pretty well supported cross-platform. You can even configure Safari to show you the zeroconf services on your local network, so you can use that to debug the service advertisement for the consumers. One side advantage of this kind of approach is that you could easily run the producers on different machines than the consumers.\n", "You need a client-server model on a local system. You could do this using TCP/IP sockets to communicate between your clients and servers, but it's faster to use local named pipes if you don't have the need to communicate over a network.\nThe basic requirements for you if I understood correctly are these: \n1. A producer should be able to spawn consumers if none exist already. \n2. A producer should be able to communicate with consumers. \n3. A producer should be able to find pre-existing consumers and communicate with them.\n4. Even if a producer completes, consumers should continue running.\n5. More than one producer should be able to communicate with the consumers.\nLet's tackle each one of these one by one:\n(1) is a simple process-creation problem, except that consumer (child) processes should continue running, even if the producer (parent) exits. See (4) below.\n(2) A producer can communicate with consumers using named pipes. See os.mkfifo() and unix man page of mkfifo() to create named pipes.\n(3) You need to create named pipes from the consumer processes in a well known path, when they start running. The producer can find out if any consumers are running by looking for this well-known pipe(s) in the same location. If the pipe(s) do not exist, no consumers are running, and the producers can spawn these.\n(4) You'll need to use os.setuid() for this, and make the consumer processes act like a daemon. See unix man page of setsid().\n(5) This one is tricky. Multiple producers can communicate with the consumers using the same named pipe, but you cannot transfer more than \"PIPE_BUF\" amount of data from the producer to the consumer, if you want to reliably identify which producer sent the data, or if you want to prevent some kind of interleaving of data from different producers.\nA better way to do (5) is to have the consumers open a \"control\" named pipe (/tmp/control.3456, 3456 being the consumer pid) on execution. Producers first set up a communication channel using the \"control\" pipe. When a producer connects, it sends its pid say \"1234\", to the consumer on the \"control\" pipe, which tells the consumer to create a named pipe for data exchange with the producer, say \"/tmp/data.1234\". Then the producer closes the \"control\" pipe, and opens \"/tmp/data.1234\" to communicate with the consumer. Each consumer can have its own \"control\" pipes (use the consumer pids to distinguish between pipes of different consumers), and each producer gets its own \"data\" pipe.. When a producer finishes, it should clean up its data pipe or tell the consumer to do so. Similarly, when the consumer finishes, it should clean up its control pipes.\nA difficulty here is to prevent multiple producers from connecting to the control pipes of a single consumer at the same time. The \"control\" pipe here is a shared resource and you need to synchronize between different producers to access it. Use semaphores for it or file locking. See the posix_ipc python module for this.\nNote: I have described most of the above in terms of general UNIX semantics, but all you really need is the ability to create daemon processes, ability to create \"named\" pipes/queues/whatever so that they can be found by an unrelated process, and ability to synchronize between unrelated processes. You can use any python module which provides such semantics.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002031121_multiprocessing_python.txt
Q: is something wrong with Python Shell (Google App)? Python Shell - shell.appspot.com is acting weird? or am I missing something? Google App Engine/1.3.0 Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26) [GCC 4.1.0] >>> mycolors = ['red','green','blue'] >>> mycolors.append('black') >>> print mycolors ['red', 'green', 'blue'] But the below result is expected ['red', 'green', 'blue', 'black'] And also same with the dictionary data type. Thanks, Abhinay A: Short Answer That is a known bug. Short answer: Include everything on one line: mycolors.append('black'); print mycolors Use my free software tool, App Engine Console. My code is derived from the shell and I have fixed this bug. Long answer The bug involves the way that state is stored in between every command you type. Web requests are stateless and request/response only; however the shell (and my console app) is supposed to feel like a stream of consciousness as it is at the traditional Python prompt. The implementation is roughly this: Get a request from a browser which includes a line to execute Pull up the specific session which the browser is "in". Basically that is a module similar to __main__ with some variable bindings. Execute the given line of code in that module's context Save state by looping through all variable bindings in the context and... If the variable is hitherto unseen, store its name and value in the datastore If not, ignore it. Here is the bug. You should actually check whether the variable has changed. A: I get similar problems so I would say there is something odd going on. >>> a = 2 >>> a += 3 >>> a 5 >>> b = [2] >>> b += [3] >>> b [2] >>> [2] + [3] [2, 3] >>> class Dave: pass >>> d = Dave() >>> d <__main__.Dave instance at 0x6df2d063e08a98e8> >>> d.a = 1 >>> d.a Traceback (most recent call last): File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get exec compiled in statement_module.__dict__ File "<string>", line 1, in <module> AttributeError: Dave instance has no attribute 'a' It appears this issue has already been reported: Issue 29: Shell - entities are immutable in the shell. Unfortunately, there's response to the logged issue.
is something wrong with Python Shell (Google App)?
Python Shell - shell.appspot.com is acting weird? or am I missing something? Google App Engine/1.3.0 Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26) [GCC 4.1.0] >>> mycolors = ['red','green','blue'] >>> mycolors.append('black') >>> print mycolors ['red', 'green', 'blue'] But the below result is expected ['red', 'green', 'blue', 'black'] And also same with the dictionary data type. Thanks, Abhinay
[ "Short Answer\nThat is a known bug. Short answer:\n\nInclude everything on one line: mycolors.append('black'); print mycolors\nUse my free software tool, App Engine Console. My code is derived from the shell and I have fixed this bug.\n\nLong answer\nThe bug involves the way that state is stored in between every command you type. Web requests are stateless and request/response only; however the shell (and my console app) is supposed to feel like a stream of consciousness as it is at the traditional Python prompt.\nThe implementation is roughly this:\n\nGet a request from a browser which includes a line to execute\nPull up the specific session which the browser is \"in\". Basically that is a module similar to __main__ with some variable bindings.\nExecute the given line of code in that module's context\nSave state by looping through all variable bindings in the context and...\n\n\nIf the variable is hitherto unseen, store its name and value in the datastore\nIf not, ignore it. Here is the bug. You should actually check whether the variable has changed.\n\n\n", "I get similar problems so I would say there is something odd going on.\n>>> a = 2\n>>> a += 3\n>>> a\n5\n>>> b = [2]\n>>> b += [3]\n>>> b\n[2]\n>>> [2] + [3]\n[2, 3]\n>>> class Dave: pass\n>>> d = Dave()\n>>> d\n<__main__.Dave instance at 0x6df2d063e08a98e8>\n>>> d.a = 1\n>>> d.a\nTraceback (most recent call last):\n File \"/base/data/home/apps/shell/1.335852500710379686/shell.py\", line 267, in get\n exec compiled in statement_module.__dict__\n File \"<string>\", line 1, in <module>\nAttributeError: Dave instance has no attribute 'a'\n\nIt appears this issue has already been reported: Issue 29: Shell - entities are immutable in the shell. Unfortunately, there's response to the logged issue.\n" ]
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python", "shell" ]
stackoverflow_0002027658_google_app_engine_python_shell.txt
Q: Interactive Python GUI Python have been really bumpy for me, because the last time I created a GUI client, the client seems to hang when spawning a process, calling a shell script, and calling outside application. This have been my major problem with Python since then, and now I'm in a new project, can someone give me pointers, and a word of advice in order for my GUI python application to still be interactive when spawning another process? A: Simplest (not necessarily "best" in an abstract sense): spawn the subprocess in a separate thread, communicating results back to the main thread via a Queue.Queue instance -- the main thread must periodically check that queue to see if the results have arrived yet, but periodic polling isn't hard to arrange in any event loop. A: Your main GUI thread will freeze if you spawn off a process and wait for it to completely. Often, you can simply use subprocess and poll it now and then for completion rather than waiting for it to finish. This will keep your GUI from freezing.
Interactive Python GUI
Python have been really bumpy for me, because the last time I created a GUI client, the client seems to hang when spawning a process, calling a shell script, and calling outside application. This have been my major problem with Python since then, and now I'm in a new project, can someone give me pointers, and a word of advice in order for my GUI python application to still be interactive when spawning another process?
[ "Simplest (not necessarily \"best\" in an abstract sense): spawn the subprocess in a separate thread, communicating results back to the main thread via a Queue.Queue instance -- the main thread must periodically check that queue to see if the results have arrived yet, but periodic polling isn't hard to arrange in any event loop.\n", "Your main GUI thread will freeze if you spawn off a process and wait for it to completely. Often, you can simply use subprocess and poll it now and then for completion rather than waiting for it to finish. This will keep your GUI from freezing.\n" ]
[ 4, 2 ]
[]
[]
[ "interactive", "pygtk", "python", "spawn", "user_interface" ]
stackoverflow_0002032617_interactive_pygtk_python_spawn_user_interface.txt
Q: Porting python app to silverlight or flash I guess that title is self-explanatory. Is there any such effort been made? Some more info: it's client application (gui intensive) By porting I was thinking of cross-compiling. A: i havent done this but it shouldnt be to difficult to port python o silverlight because you should be able to use IronPython and add clr references to your python code to start using the silverlight assemblies. A: Between the two, porting to Silverlight is going to be much easier. You can target IronPython and focus primarily on changing/replacing the libraries that you've used in your Python app that aren't available in IronPython. "Porting" to Flash would be more reasonably written as "rewriting a Python application in ActionScript." Which, of course, would be easier than a from-scratch implementation, but would be largely a new effort.
Porting python app to silverlight or flash
I guess that title is self-explanatory. Is there any such effort been made? Some more info: it's client application (gui intensive) By porting I was thinking of cross-compiling.
[ "i havent done this but it shouldnt be to difficult to port python o silverlight because you should be able to use IronPython and add clr references to your python code to start using the silverlight assemblies.\n", "Between the two, porting to Silverlight is going to be much easier. You can target IronPython and focus primarily on changing/replacing the libraries that you've used in your Python app that aren't available in IronPython.\n\"Porting\" to Flash would be more reasonably written as \"rewriting a Python application in ActionScript.\" Which, of course, would be easier than a from-scratch implementation, but would be largely a new effort.\n" ]
[ 2, 2 ]
[]
[]
[ "flash", "python", "silverlight" ]
stackoverflow_0002032845_flash_python_silverlight.txt
Q: Concatenation Operator + or , var1 = 'abc' var2 = 'xyz' print('literal' + var1 + var2) # literalabcxyz print('literal', var1, var2) # literal abc xyz ... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest? Thanks A: (You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.) The first, print('literal' + var1 + var2), evaluates an expression and passes a single argument to print. The second, print('literal', var1, var2), just passes three arguments to print. This is almost the same output purely by chance: that's how print works. The second is not doing any concatenation, and is simply outputting each value separated by a space (which is print's default behavior). To be explicit: the plus in the expression is doing concatenation, but the comma is not doing concatenation. Timing: I got the results below; however, I believe this is biased because the strings are so short (e.g. longer strings could reverse the result), and in any case, printing as presenting in the question won't take long (you'll get better performance worrying about many other things instead). Note: Use python -m timeit --help for instructions on how to use timeit. $ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a, b' 100000 loops, best of 3: 7.68 usec per loop $ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a + " " + b' 100000 loops, best of 3: 4.67 usec per loop $ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, " ".join([a, b])' 100000 loops, best of 3: 5.37 usec per loop In particular, notice each code will give the exact same output (it's meaningless to compare if one method gives the wrong results). The StringIO is an easy way to not print to the screen in these tests, but it could be affecting the results too. A: Passing strings as arguments to print joins them with the 'sep' keyword. Default is ' ' (space). Separator keyword is Python 3.x only. Before that the separator is always a space, except in 2.5(?) and up where you can from __future__ import print_function or something like that. >>> print('one', 'two') # default ' ' one two >>> print('one', 'two', sep=' and a ') one and a two >>> ' '.join(['one', 'two']) one two >>> print('one' + 'two') onetwo A: Using a comma gives the print function multiple arguments (which in this case are printed all, seperated by a space. Using the plus will create one argument for print, which is printed in its entirety. I think using the + is best in this case.
Concatenation Operator + or ,
var1 = 'abc' var2 = 'xyz' print('literal' + var1 + var2) # literalabcxyz print('literal', var1, var2) # literal abc xyz ... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest? Thanks
[ "(You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.)\nThe first, print('literal' + var1 + var2), evaluates an expression and passes a single argument to print. The second, print('literal', var1, var2), just passes three arguments to print. This is almost the same output purely by chance: that's how print works. The second is not doing any concatenation, and is simply outputting each value separated by a space (which is print's default behavior).\nTo be explicit: the plus in the expression is doing concatenation, but the comma is not doing concatenation.\n\nTiming: I got the results below; however, I believe this is biased because the strings are so short (e.g. longer strings could reverse the result), and in any case, printing as presenting in the question won't take long (you'll get better performance worrying about many other things instead).\nNote: Use python -m timeit --help for instructions on how to use timeit.\n$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = \"abc\"; b = \"def\"' 'print >>out, a, b'\n100000 loops, best of 3: 7.68 usec per loop\n$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = \"abc\"; b = \"def\"' 'print >>out, a + \" \" + b'\n100000 loops, best of 3: 4.67 usec per loop\n$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = \"abc\"; b = \"def\"' 'print >>out, \" \".join([a, b])'\n100000 loops, best of 3: 5.37 usec per loop\n\nIn particular, notice each code will give the exact same output (it's meaningless to compare if one method gives the wrong results). The StringIO is an easy way to not print to the screen in these tests, but it could be affecting the results too.\n", "Passing strings as arguments to print joins them with the 'sep' keyword. Default is ' ' (space).\nSeparator keyword is Python 3.x only. Before that the separator is always a space, except in 2.5(?) and up where you can from __future__ import print_function or something like that.\n>>> print('one', 'two') # default ' '\none two\n>>> print('one', 'two', sep=' and a ')\none and a two\n>>> ' '.join(['one', 'two'])\none two\n>>> print('one' + 'two')\nonetwo\n\n", "Using a comma gives the print function multiple arguments (which in this case are printed all, seperated by a space. Using the plus will create one argument for print, which is printed in its entirety. \nI think using the + is best in this case.\n" ]
[ 26, 6, 1 ]
[]
[]
[ "concatenation", "python", "python_3.x" ]
stackoverflow_0002033242_concatenation_python_python_3.x.txt
Q: In what circumstances should you serialize data? When should you not? I'm aware that serializing is used to convert data types into a storable format, for purposes such as caching. What I'm more specifically asking is, what are the circumstances in which you should actually decide to store data ( using serialize() in PHP, pickle module in Python, et cetera )? Let's say we had a high traffic website, and in our /blog page we are using static content xml files, a gettext mo file, and dynamically generated content from a database. Example #1: The file we rely on for static content is en/blog.xml: '<content><![CDATA[ <h1>Welcome to my blog!</h1> <p>Lorem ipsum dolor sit amet..</p> ]]></content>' Would we want to serialize this xml file itself and store it in cache? Example #2: We also have a dynamically generated form, normally I would assume I would not serialize anything because it's server-side generated and dynamic, but our form field labels are internationalized and the user requested this page in spanish, therefore we are using a translation class which grabs form field labels stored in mo/csv/xml format. Contents of contact-us.php: <label for="first_name"><?php echo $L->_("First Name");?></label> <input id="first_name" name="first_name" type="text"> The "First Name" message id translation is pulled from the application-level translation file, which we parse and store in an array which resides in our translation class. So it would be ideal for our code to not parse the mo file on every page request, and instead serialize the whole array after parsing the mo, and then rely on the serialized dump of that? Example #3: Let's say on our blog page we're pulling in the 5 most recent blog posts. $posts = BlogClass->sql('SELECT blog_message, blog_author FROM blog_posts LIMIT 5 ORDER BY blog_date DESC'); Would we want to rely on something like memcache and just set a key to the result of the sql statement, would it serialize the results of the query, or? Bonus: If anyone could actually provide specific examples of efficient/practical uses/mis-uses of serialization, that'd be great - something like a multi-page, huge huge form that pulls in database information and stores stuff in sessions, or any examples where you had to rely on serialize.. A: Example 1 Profile. Is it prohibitively costly to generate your content pages? Is it significantly less costly to deserialize your generated content? If both answers are yes, consider it. Example 2 Profile. Is it prohibitively costly to generate your content pages? Is it significantly less costly to deserialize your generated content? If both answers are yes, consider it. Example 3 Profile. Is that query prohibitively expensive? Is it significantly faster to grab the data from memcached? If both answers are yes, consider it. Bonus I never serialize my data just because I can. I need to have a reason to do so, otherwise it's just premature optimization. There are several factors that come into deciding whether this should be done. Performing sorting or other operations on a serialized set of data This will almost always be a bad idea. e.g. if you serialized a resultset from a database, then needed to reorder this set by some field, you're shooting yourself in the foot. Messaging If you need to communicate serialized data to other services/languages then choice of serialization is critical. I avoid serializing using a language specific method if I know or think that other things may need to read it. JSON is often an ideal format for cross language serialization. Updating serialized data You have to be willing to regenerate the serialized data for updates to it's source. It will be prohibitively expensive to do any type of complex updates to the serialized data. Human readability If you need to read it easily, I suggest avoiding language specific formats. I suggest JSON for this. Edit: I just looked again at the query in Example 3. That is an extremely simple query, you're only selecting 2 fields, and ordering by a date field. With a properly indexed table this query should be trivial, and I would not suggest caching something like this into memcached. A: What are the circumstances in which you should actually decide to store data ( using serialize() in PHP, pickle module in Python, et cetera )? That question is easy to answer. The various scenarios don't actually have much relevance. Here's the answer You serialize when you have to. No sooner. Many API's will not accept Python objects. When the API cannot accept a Python object, then you can often provide a string. That's when you serialize. Example. You want to save a Python object on persistent storage. Sadly a file object can't write a Python object. So you serialize. Example. You want to send a Python object to another process. You're using a socket, named pipe or whatever. These are all file objects, and file objects can't write a Python objects. So you serialize. That's when you serialize. XML files are serialized DOM trees. The Python object is a DOM tree. The XML file is one way to serialize the DOM tree. I don't understand this example. Form label strings are strings. They don't need to be serialized. I18N is handled separately from your application. http://docs.python.org/library/i18n.html I don't understand this example. This is a query. You don't serialize anything. You just do the query. The results are (in principle) always changing, so any serialization is the previous result, not the current result, so you just don't. Bonus. Multi-page, huge form? You don't serialize anything. You just update the session in your web framework. The web framework's session manager might serialize the Python object, but that's why you used a framework -- so you wouldn't have to care. Serialization is used to write a Python object to a file. This -- in web applications -- is rare. Mostly, you write to databases using SQL.
In what circumstances should you serialize data? When should you not?
I'm aware that serializing is used to convert data types into a storable format, for purposes such as caching. What I'm more specifically asking is, what are the circumstances in which you should actually decide to store data ( using serialize() in PHP, pickle module in Python, et cetera )? Let's say we had a high traffic website, and in our /blog page we are using static content xml files, a gettext mo file, and dynamically generated content from a database. Example #1: The file we rely on for static content is en/blog.xml: '<content><![CDATA[ <h1>Welcome to my blog!</h1> <p>Lorem ipsum dolor sit amet..</p> ]]></content>' Would we want to serialize this xml file itself and store it in cache? Example #2: We also have a dynamically generated form, normally I would assume I would not serialize anything because it's server-side generated and dynamic, but our form field labels are internationalized and the user requested this page in spanish, therefore we are using a translation class which grabs form field labels stored in mo/csv/xml format. Contents of contact-us.php: <label for="first_name"><?php echo $L->_("First Name");?></label> <input id="first_name" name="first_name" type="text"> The "First Name" message id translation is pulled from the application-level translation file, which we parse and store in an array which resides in our translation class. So it would be ideal for our code to not parse the mo file on every page request, and instead serialize the whole array after parsing the mo, and then rely on the serialized dump of that? Example #3: Let's say on our blog page we're pulling in the 5 most recent blog posts. $posts = BlogClass->sql('SELECT blog_message, blog_author FROM blog_posts LIMIT 5 ORDER BY blog_date DESC'); Would we want to rely on something like memcache and just set a key to the result of the sql statement, would it serialize the results of the query, or? Bonus: If anyone could actually provide specific examples of efficient/practical uses/mis-uses of serialization, that'd be great - something like a multi-page, huge huge form that pulls in database information and stores stuff in sessions, or any examples where you had to rely on serialize..
[ "Example 1\nProfile.\n\nIs it prohibitively costly to generate your content pages?\nIs it significantly less costly to deserialize your generated content?\n\nIf both answers are yes, consider it.\nExample 2\nProfile.\n\nIs it prohibitively costly to generate your content pages?\nIs it significantly less costly to deserialize your generated content?\n\nIf both answers are yes, consider it.\nExample 3\nProfile.\n\nIs that query prohibitively expensive?\nIs it significantly faster to grab the data from memcached?\n\nIf both answers are yes, consider it.\nBonus\nI never serialize my data just because I can. I need to have a reason to do so, otherwise it's just premature optimization. There are several factors that come into deciding whether this should be done.\nPerforming sorting or other operations on a serialized set of data\nThis will almost always be a bad idea. e.g. if you serialized a resultset from a database, then needed to reorder this set by some field, you're shooting yourself in the foot.\nMessaging\nIf you need to communicate serialized data to other services/languages then choice of serialization is critical. I avoid serializing using a language specific method if I know or think that other things may need to read it. JSON is often an ideal format for cross language serialization.\nUpdating serialized data\nYou have to be willing to regenerate the serialized data for updates to it's source. It will be prohibitively expensive to do any type of complex updates to the serialized data.\nHuman readability\nIf you need to read it easily, I suggest avoiding language specific formats. I suggest JSON for this.\nEdit:\nI just looked again at the query in Example 3. That is an extremely simple query, you're only selecting 2 fields, and ordering by a date field. With a properly indexed table this query should be trivial, and I would not suggest caching something like this into memcached. \n", "What are the circumstances in which you should actually decide to store data ( using serialize() in PHP, pickle module in Python, et cetera )?\nThat question is easy to answer. The various scenarios don't actually have much relevance.\nHere's the answer You serialize when you have to. No sooner.\nMany API's will not accept Python objects. When the API cannot accept a Python object, then you can often provide a string. That's when you serialize.\nExample. You want to save a Python object on persistent storage. Sadly a file object can't write a Python object. So you serialize.\nExample. You want to send a Python object to another process. You're using a socket, named pipe or whatever. These are all file objects, and file objects can't write a Python objects. So you serialize.\nThat's when you serialize.\n\nXML files are serialized DOM trees. The Python object is a DOM tree. The XML file is one way to serialize the DOM tree. I don't understand this example.\nForm label strings are strings. They don't need to be serialized. I18N is handled separately from your application. http://docs.python.org/library/i18n.html I don't understand this example.\nThis is a query. You don't serialize anything. You just do the query. The results are (in principle) always changing, so any serialization is the previous result, not the current result, so you just don't.\n\nBonus. Multi-page, huge form? You don't serialize anything. You just update the session in your web framework. The web framework's session manager might serialize the Python object, but that's why you used a framework -- so you wouldn't have to care.\nSerialization is used to write a Python object to a file. This -- in web applications -- is rare. Mostly, you write to databases using SQL.\n" ]
[ 6, 3 ]
[]
[]
[ "php", "python", "serialization" ]
stackoverflow_0002032644_php_python_serialization.txt
Q: running a system command in a python script I have been going through "A byte of Python" to learn the syntax and methods etc... I have just started with a simple backup script (straight from the book): #!/usr/bin/python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['"C:\\My Documents"', 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. # 2. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".format(target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED') Right, it fails. If I run the zip command in the terminal it works fine. I think it fails because the zip_command is never actually run. And I don't know how to run it. Simply typing out zip_command does not work. (I am using python 3.1) A: It would help us if you could format your code as code; select the code parts, and click on the "Code Sample" button in the editor toolbar. The icon looks like "101/010" and if you hold the mouse pointer over it, the yellow "tool tip" box says "Code Sample <pre></pre> Ctrl+K" I just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. So the bold lines are comments. So far so good. Your strings seem to contain backslash characters. You will need to double each backslash, like so: target_dir = 'E:\\Backup' This is because Python treats the backslash specially. It introduces a "backslash escape", which lets you put a quote inside a quoted string: single_quote = '\'' You could also use a Python "raw string", which has much simpler rules for a backslash. A raw string is introduced by r" or r' and terminated by " or ' respectively. examples: # both of these are legal target_dir = r"E:\Backup" target_dir = r'E:\Backup' A: Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? It could be that zip isn't on the path when Python launches the command. A: The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct. Another thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. Especially PATH. Here is a suggested example: set echo Trying to run zip... zip Put those in a batch file called C:\mytest.cmd, and then have your Python code run it: result_code = os.system("C:\\mytest.cmd") print('Result of running mytest was code', result_code) If it works, you will see the environment variables printed out, then it will echo "Trying to run zip...", then if zip runs it will print a message with the version number of zip and how to run it. A: zip command only work in linux not for windows.. thats why it make an error..
running a system command in a python script
I have been going through "A byte of Python" to learn the syntax and methods etc... I have just started with a simple backup script (straight from the book): #!/usr/bin/python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['"C:\\My Documents"', 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. # 2. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".format(target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED') Right, it fails. If I run the zip command in the terminal it works fine. I think it fails because the zip_command is never actually run. And I don't know how to run it. Simply typing out zip_command does not work. (I am using python 3.1)
[ "It would help us if you could format your code as code; select the code parts, and click on the \"Code Sample\" button in the editor toolbar. The icon looks like \"101/010\" and if you hold the mouse pointer over it, the yellow \"tool tip\" box says \"Code Sample <pre></pre> Ctrl+K\"\nI just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. So the bold lines are comments. So far so good.\nYour strings seem to contain backslash characters. You will need to double each backslash, like so:\ntarget_dir = 'E:\\\\Backup'\n\nThis is because Python treats the backslash specially. It introduces a \"backslash escape\", which lets you put a quote inside a quoted string:\nsingle_quote = '\\''\n\nYou could also use a Python \"raw string\", which has much simpler rules for a backslash. A raw string is introduced by r\" or r' and terminated by \" or ' respectively. examples:\n# both of these are legal\ntarget_dir = r\"E:\\Backup\"\ntarget_dir = r'E:\\Backup'\n\n", "Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? It could be that zip isn't on the path when Python launches the command.\n", "The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct.\nAnother thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. Especially PATH.\nHere is a suggested example:\nset\necho Trying to run zip...\nzip\n\nPut those in a batch file called C:\\mytest.cmd, and then have your Python code run it:\nresult_code = os.system(\"C:\\\\mytest.cmd\")\nprint('Result of running mytest was code', result_code)\n\nIf it works, you will see the environment variables printed out, then it will echo \"Trying to run zip...\", then if zip runs it will print a message with the version number of zip and how to run it.\n", "zip command only work in linux not for windows.. thats why it make an error..\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001710967_python.txt
Q: What do I use, CherryPy or Pylons? Hi I'm planning on building a site with social networking features. Which Python framework do you think is more appropriate or you would suggest over the other, CherryPy or Pylons? A: That's a subjective question. I suggest you read carefully each framework's description and choose the one that has the most features fitting your project. Here's an extensive overview of the two frameworks. This should help you choose the right tool for your project. A: As S.Lott said it is vague, so best way would be to toss a coin, and I did head=pylons tails=cherrypy but on toss it came standing up, so django it is. and a django based platorm is pinax, quoted from the site While our initial development was focused around a demo social networking site, Pinax is suitable for a wide variety of websites. We are working on number of editions tailored to intranets, event management, learning management, software project management and more.
What do I use, CherryPy or Pylons?
Hi I'm planning on building a site with social networking features. Which Python framework do you think is more appropriate or you would suggest over the other, CherryPy or Pylons?
[ "That's a subjective question. I suggest you read carefully each framework's description and choose the one that has the most features fitting your project.\nHere's an extensive overview of the two frameworks. This should help you choose the right tool for your project.\n", "As S.Lott said it is vague, so best way would be to toss a coin, and I did\nhead=pylons\ntails=cherrypy\nbut on toss it came standing up, so\ndjango it is.\nand a django based platorm is pinax, quoted from the site\n\nWhile our initial development was\n focused around a demo social\n networking site, Pinax is suitable for\n a wide variety of websites. We are\n working on number of editions tailored\n to intranets, event management,\n learning management, software project\n management and more.\n\n" ]
[ 3, 2 ]
[]
[]
[ "cherrypy", "pylons", "python" ]
stackoverflow_0002033195_cherrypy_pylons_python.txt
Q: _functools module How does this import work, what file does it use? import _functools In python 2.5: import _functools print _functools.__file__ Gives: Traceback (most recent call last): File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module> print _functools.__file__ AttributeError: 'module' object has no attribute '__file__' How can I get the meaning of partial (from _functools import partial) if I can't read C code? A: C-coded modules can be built-in (lacking __file__) or live in a .so or .pyd dynamic library (which their __file__ will indicate) -- that's an implementation detail that you should not care about. If you want to understand how a Python-callable, C-coded function works by studying code, learning to read C is generally best (far less hard than actually productively coding in C;-). However, often you'll find (suggestive, non-authoritative) "sample Python implementations" of C-coded functionality, and you can study those. A particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the pypy project (which does Python implementations coded in Python) -- its sources are browseable here and of course you can download and peruse them on your machine. In particular, this is pypy's _functools.py implementation: """ Supplies the internal functions for functools.py in the standard library """ class partial: """ partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords. """ __slots__ = ['func', 'args', 'keywords'] def __init__(self, func, *args, **keywords): if not callable(func): raise TypeError("the first argument must be callable") self.func = func self.args = args self.keywords = keywords def __call__(self, *fargs, **fkeywords): newkeywords = self.keywords.copy() newkeywords.update(fkeywords) return self.func(*(self.args + fargs), **newkeywords) Pretty trivial to read and understand, I hope! A: please be more clear when asking questions next time. I assume you want this >>> import _functools >>> _functools.__file__ '/usr/lib/python2.6/lib-dynload/_functools.so' A: It is a shared object _functools.so, written in C. I guess, it is imported by the actual functools module. Why are you trying to import from it? Sure, it is possible, however, you can just as well from functools import partial. A: For Python2.6, The _functools module is a builtin. You can see that if you simply type import _functools ; repr(_functools) and hit enter at your interpreter prompt. If you want to see the C source of the module, check out http://hg.python.org/cpython/file/d7e85ddb1336/Modules/_functoolsmodule.c This _functools module doesn't have a __file__ attribute (see next paragraph) since it's compiled into the interpreter. For Python2.5, The _functools module is a standard library module implemented in C and is available at http://hg.python.org/cpython/file/a78381ead4cf/Modules/_functoolsmodule.c if you want to see it. You can see the location from where the module is loaded up by typing import _functools ; print _functools.__file__ at your interpreter prompt A: The behaviour of the functools.partial() function is described in PEP 309 in which it was defined. The although the actual implementations of built-ins are often in C PEP's including this one usually contain example implementations in Python. This example code should be sufficient for you to understand the behaviour of functools.partial(). If there is a specific issue about the C implementation that is concerning you are going to have to read the C code. Or perhaps describe it in your question and someone might know the answer.
_functools module
How does this import work, what file does it use? import _functools In python 2.5: import _functools print _functools.__file__ Gives: Traceback (most recent call last): File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module> print _functools.__file__ AttributeError: 'module' object has no attribute '__file__' How can I get the meaning of partial (from _functools import partial) if I can't read C code?
[ "C-coded modules can be built-in (lacking __file__) or live in a .so or .pyd dynamic library (which their __file__ will indicate) -- that's an implementation detail that you should not care about.\nIf you want to understand how a Python-callable, C-coded function works by studying code, learning to read C is generally best (far less hard than actually productively coding in C;-). However, often you'll find (suggestive, non-authoritative) \"sample Python implementations\" of C-coded functionality, and you can study those.\nA particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the pypy project (which does Python implementations coded in Python) -- its sources are browseable here and of course you can download and peruse them on your machine.\nIn particular, this is pypy's _functools.py implementation:\n\"\"\" Supplies the internal functions for functools.py in the standard library \"\"\"\n\nclass partial:\n \"\"\"\n partial(func, *args, **keywords) - new function with partial application\n of the given arguments and keywords.\n \"\"\"\n __slots__ = ['func', 'args', 'keywords']\n\n def __init__(self, func, *args, **keywords):\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n self.func = func\n self.args = args\n self.keywords = keywords\n\n def __call__(self, *fargs, **fkeywords):\n newkeywords = self.keywords.copy()\n newkeywords.update(fkeywords)\n return self.func(*(self.args + fargs), **newkeywords)\n\nPretty trivial to read and understand, I hope!\n", "please be more clear when asking questions next time. I assume you want this\n>>> import _functools\n>>> _functools.__file__\n'/usr/lib/python2.6/lib-dynload/_functools.so'\n\n", "It is a shared object _functools.so, written in C. I guess, it is imported by the actual functools module. Why are you trying to import from it? Sure, it is possible, however, you can just as well from functools import partial.\n", "For Python2.6, \nThe _functools module is a builtin. You can see that if you simply type import _functools ; repr(_functools) and hit enter at your interpreter prompt.\nIf you want to see the C source of the module, check out http://hg.python.org/cpython/file/d7e85ddb1336/Modules/_functoolsmodule.c\nThis _functools module doesn't have a __file__ attribute (see next paragraph) since it's compiled into the interpreter.\nFor Python2.5, \nThe _functools module is a standard library module implemented in C and is available at http://hg.python.org/cpython/file/a78381ead4cf/Modules/_functoolsmodule.c if you want to see it. You can see the location from where the module is loaded up by typing import _functools ; print _functools.__file__ at your interpreter prompt \n", "The behaviour of the functools.partial() function is described in PEP 309 in which it was defined. The although the actual implementations of built-ins are often in C PEP's including this one usually contain example implementations in Python. \nThis example code should be sufficient for you to understand the behaviour of functools.partial(). If there is a specific issue about the C implementation that is concerning you are going to have to read the C code. Or perhaps describe it in your question and someone might know the answer.\n" ]
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "extension_modules", "python" ]
stackoverflow_0002032677_extension_modules_python.txt
Q: How to access elements of matrices from mat file in python? When load matrices from mat file in python using scipy.io, it makes dictionary where key is name of matrix,and value is 2D array of that matrix. How can i access elements in this array? A: Suppose you have mat = sio.loadmat('a.mat') Then you can see which matrices were loaded by print mat For each key key in the dictionary, you can retrieve the corresponding matrix by my_matrix = mat[key] my_matrix is a 2d array representing the matrix. So to get row 0 of the matrix, you would use my_matrix[0], and to get element(0,0) of the matrix, you would use my_matrix[0][0]. Here's a nice tutorial you can use for other basic functionality. A: Doesn't matrix[x][y] work? A: >>> A = array([ [1,2], [3,4], [5,6]]) >>> A array([[1, 2], [3, 4], [5, 6]]) >>> A[0] array([1, 2]) >>> A[0][0] 1 Here A can be a value in the dict object you have created.
How to access elements of matrices from mat file in python?
When load matrices from mat file in python using scipy.io, it makes dictionary where key is name of matrix,and value is 2D array of that matrix. How can i access elements in this array?
[ "Suppose you have\nmat = sio.loadmat('a.mat')\n\nThen you can see which matrices were loaded by\nprint mat\n\nFor each key key in the dictionary, you can retrieve the corresponding matrix by\nmy_matrix = mat[key]\n\nmy_matrix is a 2d array representing the matrix. So to get row 0 of the matrix, you would use my_matrix[0], and to get element(0,0) of the matrix, you would use my_matrix[0][0].\nHere's a nice tutorial you can use for other basic functionality.\n", "Doesn't\nmatrix[x][y]\n\nwork?\n", ">>> A = array([ [1,2], [3,4], [5,6]])\n>>> A\narray([[1, 2],\n [3, 4],\n [5, 6]])\n>>> A[0]\narray([1, 2])\n>>> A[0][0]\n1\n\nHere A can be a value in the dict object you have created. \n" ]
[ 2, 0, 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0002034053_matlab_python.txt
Q: How to use Python tkSimpleDialog.askstring I want to use the response from an askstring prompt to set a variable. Unfortunately, I have the dilemma that I'm trapped in the loop asking the question or the window refuses to draw because the variable (urltoopen) has no value. The code as it stands: urltoopen = tkSimpleDialog.askstring('Address', 'Where do we get the pictures from?') usock = urllib2.urlopen(urltoopen) data = usock.read() usock.close() A: tkSimpleDialog.askstring returns None if the user clicks Cancel or closes the window (instead of clicking Ok or using the Enter key); you should check for that (what do you want to do if the user chooses to cancel? surely not call urlopen anyway...). Apart from that, you're using the function correctly; I imagine that by "has no value" you mean is None, right? A: root = Tk() try: urltoopen = tkSimpleDialog.askstring('Ask Address', 'Where do we get the pictures from?') usock = urllib2.urlopen(urltoopen) data = usock.read() usock.close() a = data except: sys.exit() works fine. But it does need error handling (as mentioned by Alex).
How to use Python tkSimpleDialog.askstring
I want to use the response from an askstring prompt to set a variable. Unfortunately, I have the dilemma that I'm trapped in the loop asking the question or the window refuses to draw because the variable (urltoopen) has no value. The code as it stands: urltoopen = tkSimpleDialog.askstring('Address', 'Where do we get the pictures from?') usock = urllib2.urlopen(urltoopen) data = usock.read() usock.close()
[ "tkSimpleDialog.askstring returns None if the user clicks Cancel or closes the window (instead of clicking Ok or using the Enter key); you should check for that (what do you want to do if the user chooses to cancel? surely not call urlopen anyway...).\nApart from that, you're using the function correctly; I imagine that by \"has no value\" you mean is None, right?\n", "\nroot = Tk() \n\n\ntry:\n urltoopen = tkSimpleDialog.askstring('Ask Address', 'Where do we get the pictures from?')\n usock = urllib2.urlopen(urltoopen) \n data = usock.read() \n usock.close() \n a = data \nexcept: \n sys.exit() \n\nworks fine. But it does need error handling (as mentioned by Alex).\n" ]
[ 4, 0 ]
[]
[]
[ "python", "tkinter", "user_input" ]
stackoverflow_0002003504_python_tkinter_user_input.txt
Q: Text in tables? I like to organize a lot of information from literature reviews in "tables" (information not unlike product comparisons, but for scientific research), but often the information I enter can contain lines or paragraphs of text and becomes unwieldy in a spreadsheet. I've heard SQL relational tables are often used for this purpose; for data analysis I use Python or R to parse data from a flat text file and enter this into SQLite. Should I just create a "marked up" text file and do the same thing? I wonder what interfaces people use to enter and also view such text-heavy tables? Or I wonder if there is another software that might be suited for this purpose. A: The way you store and retrieve data would depend on what you plan to do with it. Text files have problems with manageability. You can't really take care of a directory tree with thousands and thousands of files. It would be a nightmare to search through them. If you're concurrently updating, you'll have to deal with locks and a slew of other problems. They're not really meant for storing large amounts of data that you're going to mine. Relational databases are fine but you'll have to parse the information into meaningful bits , break it down into relations and put the resultant data into tables for it to make any sense. Dumping all the text (after some preprocessing) into a single column would not be very useful. The upshot of what I'm saying is the SQL databases store 'structured' data which can be queried using the structure. Another think you might consider is to use a document database. There are quite a few out there and while I don't have personal experience, I have listened to a presentation on CouchDB which stores information as JSON documents. You mine the data using scripts that can sort according to some conditions and then get back the sorted documents. If you're dealing with a lot of textual data, this would definitely atleast be worth a shot. Word on the street is that these engines are much more scalable than their relational counterparts.
Text in tables?
I like to organize a lot of information from literature reviews in "tables" (information not unlike product comparisons, but for scientific research), but often the information I enter can contain lines or paragraphs of text and becomes unwieldy in a spreadsheet. I've heard SQL relational tables are often used for this purpose; for data analysis I use Python or R to parse data from a flat text file and enter this into SQLite. Should I just create a "marked up" text file and do the same thing? I wonder what interfaces people use to enter and also view such text-heavy tables? Or I wonder if there is another software that might be suited for this purpose.
[ "The way you store and retrieve data would depend on what you plan to do with it.\nText files have problems with manageability. You can't really take care of a directory tree with thousands and thousands of files. It would be a nightmare to search through them. If you're concurrently updating, you'll have to deal with locks and a slew of other problems. They're not really meant for storing large amounts of data that you're going to mine.\nRelational databases are fine but you'll have to parse the information into meaningful bits , break it down into relations and put the resultant data into tables for it to make any sense. Dumping all the text (after some preprocessing) into a single column would not be very useful. The upshot of what I'm saying is the SQL databases store 'structured' data which can be queried using the structure.\nAnother think you might consider is to use a document database. There are quite a few out there and while I don't have personal experience, I have listened to a presentation on CouchDB which stores information as JSON documents. You mine the data using scripts that can sort according to some conditions and then get back the sorted documents. If you're dealing with a lot of textual data, this would definitely atleast be worth a shot. Word on the street is that these engines are much more scalable than their relational counterparts.\n" ]
[ 4 ]
[]
[]
[ "database", "datatable", "python", "sql" ]
stackoverflow_0002034330_database_datatable_python_sql.txt
Q: Is there any way to load data dynamically into a python datastructure without recreating I have a process that builds a list from a database table and runs real time. Every now and then new data gets added to the database table. Querying data from the table every now and then is cumbersome, and time consuming, and this need to be as real time as possible.What is the right way to approach the problem? The process is as follows list gets build from an SQL Query that takes 2-4 seconds to execute. List is used by Process A to perform some functions Data gets constantly added to the Database Table. We need only the new data to get appended to the list, which will be used real time by the process A. I have not tried writing any code yet, I am still not sure what kind of design it should be. Python is the only language we can use since there are 10,000 lines of Python code already deployed as a part of the system. Can someone help me with the right approach, modules etc? EDIT Process A is a procedure within the program. Pusedo code I am thinking off is something like this def processA(list): while 1: parse file do something def run(): list = generate list from run sql query processA(list) if __name__=="__main__": run() A: Wouldn't it make sense to just query the database again for all the new data that has come since you last queried? Something like key > highest_key_in_list or date > highest_date_in_list rather than loading up the whole thing again. A: This feels a big hackish, but on your initial query create a temp table to hold the results. Add a column to that table that is an incrementing number I'll call id. Add a trigger to the table with data changing that updates your temp table. Check back with the database and query only for records with an id larger than the last element in your initial pull. Since that will be a much faster query, it should get you about as close to real time as you can get. Reusing the a persistent connection may help slightly too. I'd also check that your database is indexed well for this query, 2-4 seconds seems like a long time. Maybe you can also optimize your query a bit. A: Sorry, it is rather difficult to deduce what exactly you want to be done. One point is not quite clear: Is the process (python script?) to be run continously (daemon-like), - in that case, you don't need to store the dataset anywhere if it is relatively small. You can just keep it in memory. periodically (cron job), - in that case you do need a way to serialize the data between every invocation. You can use pickle for that, however I am unsure if unpickling will take less time, than retrieving the whole dataset from the database. The reset depends on your database schema and on the way the data is added/updated. Is it mutated at all after it is inserted? If not, you can only select data "since the last invocation", by using a timestamp field in the table (if it has one) or the identity field (NOT reliable, actually. It is sort of reliable with MySQL, but then again, not quite). If the data might be updated, then you will have to re-read the whole dataset (unless you have a way to select only new/updated entries). As for 2-4 seconds, - there may be many reasons why it takes such time, - are you running queries, that mention unindexed fields? A: If the data is being added to the table in the program, just add it to the list at the same time. If multiple sources are adding to the table, query the table for all records whose primary key is > the last key you retrieved.
Is there any way to load data dynamically into a python datastructure without recreating
I have a process that builds a list from a database table and runs real time. Every now and then new data gets added to the database table. Querying data from the table every now and then is cumbersome, and time consuming, and this need to be as real time as possible.What is the right way to approach the problem? The process is as follows list gets build from an SQL Query that takes 2-4 seconds to execute. List is used by Process A to perform some functions Data gets constantly added to the Database Table. We need only the new data to get appended to the list, which will be used real time by the process A. I have not tried writing any code yet, I am still not sure what kind of design it should be. Python is the only language we can use since there are 10,000 lines of Python code already deployed as a part of the system. Can someone help me with the right approach, modules etc? EDIT Process A is a procedure within the program. Pusedo code I am thinking off is something like this def processA(list): while 1: parse file do something def run(): list = generate list from run sql query processA(list) if __name__=="__main__": run()
[ "Wouldn't it make sense to just query the database again for all the new data that has come since you last queried? Something like key > highest_key_in_list or date > highest_date_in_list rather than loading up the whole thing again.\n", "This feels a big hackish, but on your initial query create a temp table to hold the results. Add a column to that table that is an incrementing number I'll call id. Add a trigger to the table with data changing that updates your temp table. Check back with the database and query only for records with an id larger than the last element in your initial pull. Since that will be a much faster query, it should get you about as close to real time as you can get. Reusing the a persistent connection may help slightly too.\nI'd also check that your database is indexed well for this query, 2-4 seconds seems like a long time. Maybe you can also optimize your query a bit.\n", "Sorry, it is rather difficult to deduce what exactly you want to be done.\nOne point is not quite clear:\nIs the process (python script?) to be run\n\ncontinously (daemon-like), - in that case, you don't need to store the dataset anywhere if it is relatively small. You can just keep it in memory.\nperiodically (cron job), - in that case you do need a way to serialize the data between every invocation. You can use pickle for that, however I am unsure if unpickling will take less time, than retrieving the whole dataset from the database.\n\nThe reset depends on your database schema and on the way the data is added/updated. Is it mutated at all after it is inserted? If not, you can only select data \"since the last invocation\", by using a timestamp field in the table (if it has one) or the identity field (NOT reliable, actually. It is sort of reliable with MySQL, but then again, not quite). \nIf the data might be updated, then you will have to re-read the whole dataset (unless you have a way to select only new/updated entries).\nAs for 2-4 seconds, - there may be many reasons why it takes such time, - are you running queries, that mention unindexed fields?\n", "If the data is being added to the table in the program, just add it to the list at the same time.\nIf multiple sources are adding to the table, query the table for all records whose primary key is > the last key you retrieved.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "dynamic_data", "python", "real_time" ]
stackoverflow_0002034338_dynamic_data_python_real_time.txt
Q: Python CLI to edit Firefox bookmarks? Has anyone done a Python CLI to edit Firefox bookmarks ? My worldview is that of Unix file trees; I want find /re/ in given or all fields in given or all subtrees cd ls with context mv this ../there/ Whether it uses bookamrks.html or places.sqlite is secondary -- whatever's easier. Clarification added: I'd be happy to quit Firefox, edit bookmarks in the CLI, import the new database in Firefox. In otherwords, database locking is a moot point; first let's see code for a rough cut CLI. (Why a text CLI and not a GUI ? CLIs are simpler (for me), and one could easily program e.g. mv old-bookmarks to 2009/same-structure/. Nonetheless links to a really good bookmarker GUI, for Firefox or anything else, would be useful too.) A: Assuming we're talking about Firefox 3 or better, the bookmarks are kept in a SQLite file, places.sqlite in the profile folder. So you need a routine to find the profile folder (depending on your platform) and then you can load the SQLite file. The schema's rich and a bit complicated, but well documented, and of course with Python's SQLite support you can explore it interactively. Of course, Firefox keeps the DB locked when it's running. For read-only access, you can just copy places.sqlite into a temporary file, then open and explore that one; to perform changes as you seem to require, however, it seems best to require the user to quit Firefox (if that's unacceptable, you could explore if Firefox offers a way to ask for its cooperation). Is this the kind of things you had in mind...? A: I don't know about all the features you've mentioned but "Organize bookmars" option in the Bookmarks menu is pretty decent with respect to features.
Python CLI to edit Firefox bookmarks?
Has anyone done a Python CLI to edit Firefox bookmarks ? My worldview is that of Unix file trees; I want find /re/ in given or all fields in given or all subtrees cd ls with context mv this ../there/ Whether it uses bookamrks.html or places.sqlite is secondary -- whatever's easier. Clarification added: I'd be happy to quit Firefox, edit bookmarks in the CLI, import the new database in Firefox. In otherwords, database locking is a moot point; first let's see code for a rough cut CLI. (Why a text CLI and not a GUI ? CLIs are simpler (for me), and one could easily program e.g. mv old-bookmarks to 2009/same-structure/. Nonetheless links to a really good bookmarker GUI, for Firefox or anything else, would be useful too.)
[ "Assuming we're talking about Firefox 3 or better, the bookmarks are kept in a SQLite file, places.sqlite in the profile folder. So you need a routine to find the profile folder (depending on your platform) and then you can load the SQLite file.\nThe schema's rich and a bit complicated, but well documented, and of course with Python's SQLite support you can explore it interactively.\nOf course, Firefox keeps the DB locked when it's running. For read-only access, you can just copy places.sqlite into a temporary file, then open and explore that one; to perform changes as you seem to require, however, it seems best to require the user to quit Firefox (if that's unacceptable, you could explore if Firefox offers a way to ask for its cooperation).\nIs this the kind of things you had in mind...?\n", "I don't know about all the features you've mentioned but \"Organize bookmars\" option in the Bookmarks menu is pretty decent with respect to features.\n" ]
[ 3, 0 ]
[]
[]
[ "bookmarks", "command_line_interface", "firefox", "python" ]
stackoverflow_0002034373_bookmarks_command_line_interface_firefox_python.txt
Q: ttk.Button returns None I am trying to use the invoke method of a ttk.Button, as shown at TkDocs (look at "The Command Callback"), but I keep getting this error: AttributeError: 'NoneType' object has no attribute 'invoke' So, I tried this in the Interactive Shell: ActivePython 3.1.1.2 (ActiveState Software Inc.) based on Python 3.1.1 (r311:74480, Aug 17 2009, 12:30:13) [MSC v.1500 32 bit (Intel)] on win32 >>> from tkinter import * >>> import tkinter.ttk as ttk >>> root = Tk() >>> button = ttk.Button(root, text="Test").grid(row=0, column=0) >>> print(button) None Which shows that ttk.Button returns None. Is ttk.Button meant to return None. And, if so, why does TkDocs say that there is an invoke method? A: No, you're entirely wrong: your code does not show that ttk.Button returns None -- it shows that the grid method on the button object returns None! Don't you see that you're calling .grid on whatever it is that ttk.Button returns (the button object), and it's the result of that grid call that you're assigning to "button"?! So do it right instead...: button = ttk.Button(root, text="Test") button.grid(row=0, column=0) now you can print button and of course the results will be very different!-)
ttk.Button returns None
I am trying to use the invoke method of a ttk.Button, as shown at TkDocs (look at "The Command Callback"), but I keep getting this error: AttributeError: 'NoneType' object has no attribute 'invoke' So, I tried this in the Interactive Shell: ActivePython 3.1.1.2 (ActiveState Software Inc.) based on Python 3.1.1 (r311:74480, Aug 17 2009, 12:30:13) [MSC v.1500 32 bit (Intel)] on win32 >>> from tkinter import * >>> import tkinter.ttk as ttk >>> root = Tk() >>> button = ttk.Button(root, text="Test").grid(row=0, column=0) >>> print(button) None Which shows that ttk.Button returns None. Is ttk.Button meant to return None. And, if so, why does TkDocs say that there is an invoke method?
[ "No, you're entirely wrong: your code does not show that ttk.Button returns None -- it shows that the grid method on the button object returns None! Don't you see that you're calling .grid on whatever it is that ttk.Button returns (the button object), and it's the result of that grid call that you're assigning to \"button\"?!\nSo do it right instead...:\nbutton = ttk.Button(root, text=\"Test\")\nbutton.grid(row=0, column=0)\n\nnow you can print button and of course the results will be very different!-)\n" ]
[ 14 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0002034576_python_tkinter_ttk.txt
Q: Python: Very confused about decorators I thought I understood decorators but not anymore. Do decorators only work when the function is created? I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like @param_checker(['req_param_1', 'req_param_2']) and then if 'req_param_1' and 'req_param_2' aren't in the dictionary, raise a custom Exception subclass. Am I thinking of this all wrong? It would be something like this in the calling code: @param_checker(['req_param_1', 'req_param_2']) def my_decorated_function(params): # do stuff params = {'req_param_1': 'Some Value'} my_decorated_function(params) # exception would be raised here from decorator. A: A decorator is applied immediately after the def statement; the equivalence is: @param_checker(['req_param_1', 'req_param_2']) def my_decorated_function(params): # do stuff is exactly the same thing as: def my_decorated_function(params): # do stuff my_decorated_function = param_checker(['req_param_1', 'req_param_2'])(my_decorated_function) So the job of param_checker is to return a function that takes as its argument the function to be decorated and returns yet another function which does what you require. OK so far? Edit: so, here's one implementation...: import functools def param_checker(reqs): reqs = set(reqs) def middling(f): @functools.wraps(f) def wrapper(params): missing = reqs.difference(params) if missing: raise TypeError('Missing parms: %s' % ', '.join(sorted(missing))) return f(params) return wrapper return middling A: Decorators are only called once on a function, that is, when the def statement is parsed like so: @mydecorator def myfunction(): ... I assume you mean something like that: class param_checker: def __init__(self, l): self.l = l def __call__(self, functionToBeDecorated): def wrapper(*args, **kwargs): if any(necessary not in kwargs["ticket_params"] for necessary in self.l): raise MyCustomException return functionToBeDecorated(*args, **kwargs) return wrapper Please tell me if you don't understand that ;) A: Here's a full example based on @AndiDog's example. Remember any callable can be used as a decorator, it doesn't have to be a class. class MyCustomException(Exception): pass # The decorator - instances of this class are callable as it implements __call__ class param_checker: # In this example l is the parameter you pass to the decorator. # For example, l could be ['req_param_1', 'req_param_2']. def __init__(self, l): self.l = l # This makes the instance callable def __call__(self, functionToBeDecorated): def wrapper(*args, **kwargs): # For the successful call below args = () and # kwargs = {'ticket_params': {'req_param_1': 'param_1', 'req_param_2': 'param_2'}} if "ticket_params" not in kwargs or any(necessary not in kwargs["ticket_params"] for necessary in self.l): # if the ticket params parameter has not been specified, or if # any of the required parameters are not present raise an exception raise MyCustomException return functionToBeDecorated(*args, **kwargs) return wrapper @param_checker(['req_param_1', 'req_param_2']) def myfunction(ticket_params=None): # if the two required params are present this will print print "params ", ticket_params if __name__ == "__main__": try: myfunction() except MyCustomException: print "all required params not supplied" try: myfunction(ticket_params={'req_param_1': 'param_1'}) except MyCustomException: print "all required params not supplied" myfunction(ticket_params={'req_param_1': 'param_1', 'req_param_2': 'param_2'}) A: Check Alex's answer in order to understand python decorators; by the way: 1) what aren't you understanding of decorators? Don't you understand decorators as a general concept, or Python decorators? Beware, the "classical" decorator pattern, java annotations and python decorators are different things. 2) python decorators should always return a function, e.g. in your code the return value of param_checker([...]) should be a function that accepts a function as param (the func to be decorated), and returns a function with the same signature as my_decorated_function. Take a look at the following example; the decorator function is executed just once (when the class is created), while the decorated func is then executed at every call. In this specific example, it then invokes the original func, but that's not a requirement. def decorator(orig_func): print orig_func def decorated(self, a): print "aahahah", orig_func(self, a) return decorated class Example(object): @decorator def do_example(self, a): return 2 * a m = Example() m.do_example(1) 3) you might not be doing the best thing in the way you're using decorators. They should usually be employed when there's some concept which is quite orthogonal to what you're actually programming, and can be reused around - it's essentially the Python way of doing AOP. Your param_checker might not be that orthogonal - if your decorator gets just used once, then it's probably not a good place to use a decorator at all. Your param_checker seems to be the case - it assumes that the decorated func takes a single arg which is a dictionary - are there many funcs in your code with such a signature and behaviour? If the answer is "no", just check for params at the begininng of the func and raise an exception if they're missing. A: This is a good explanation for those asking the same question: # This does nothing. class donothing(object): def __init__(self, func): """ The 'func' argument is the function being decorated because in this case, we're not instantiating the decorator class. Instead we are just using the class object as a callable (a class is always callable as this is how an instance is returned) to use as a decorator, which means that it is being instantiated upon definition of the decorated function and the decorated function is being passed in as an argument to the class's __init__ method. """ self.func = func def __call__(self, *args, **kwargs): """ The __call__ function is called when the decorated function is called because the function has be eaten by the decorator class. Now it's up to the this method to return a call to the original function. The arguments are passed in as args, kwargs to be manipulated. """ # Returns original function call with original arguments. return self.func(*args, **kwargs) @donothing def printer(text): print(text) printer('hello world') # The printer function is now an alias for the donothing instance created, so # the preceding was the same as: # # instance = donothing(printer) # instance('hello world') # # Next example: class checkforkeysinparams(object): def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise TypeError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper # Apply decorator class, passing in the __init__'s 'required' argument. @checkforkeysinparams(['name', 'pass', 'code']) def complex_function(params): # Obviously these three are needed or a KeyError will be raised. print(params['name']) print(params['pass']) print(params['code']) # Create params to pass in. Note, I've commented out one of the required params. params = { 'name': 'John Doe', 'pass': 'OpenSesame', #'code': '1134', } # This call will output: TypeError: Missing from "params" argument: code complex_function(params=params)
Python: Very confused about decorators
I thought I understood decorators but not anymore. Do decorators only work when the function is created? I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like @param_checker(['req_param_1', 'req_param_2']) and then if 'req_param_1' and 'req_param_2' aren't in the dictionary, raise a custom Exception subclass. Am I thinking of this all wrong? It would be something like this in the calling code: @param_checker(['req_param_1', 'req_param_2']) def my_decorated_function(params): # do stuff params = {'req_param_1': 'Some Value'} my_decorated_function(params) # exception would be raised here from decorator.
[ "A decorator is applied immediately after the def statement; the equivalence is:\n@param_checker(['req_param_1', 'req_param_2'])\ndef my_decorated_function(params):\n # do stuff\n\nis exactly the same thing as:\ndef my_decorated_function(params):\n # do stuff\nmy_decorated_function = param_checker(['req_param_1', 'req_param_2'])(my_decorated_function)\n\nSo the job of param_checker is to return a function that takes as its argument the function to be decorated and returns yet another function which does what you require. OK so far?\nEdit: so, here's one implementation...:\nimport functools\n\ndef param_checker(reqs):\n reqs = set(reqs)\n def middling(f):\n @functools.wraps(f)\n def wrapper(params):\n missing = reqs.difference(params)\n if missing:\n raise TypeError('Missing parms: %s' % ', '.join(sorted(missing)))\n return f(params)\n return wrapper\n return middling\n\n", "Decorators are only called once on a function, that is, when the def statement is parsed like so:\n@mydecorator\ndef myfunction(): ...\n\nI assume you mean something like that:\nclass param_checker:\n def __init__(self, l):\n self.l = l\n\n def __call__(self, functionToBeDecorated):\n def wrapper(*args, **kwargs):\n if any(necessary not in kwargs[\"ticket_params\"] for necessary in self.l):\n raise MyCustomException\n return functionToBeDecorated(*args, **kwargs)\n\n return wrapper\n\nPlease tell me if you don't understand that ;)\n", "Here's a full example based on @AndiDog's example. Remember any callable can be used as a decorator, it doesn't have to be a class.\nclass MyCustomException(Exception):\n pass\n\n# The decorator - instances of this class are callable as it implements __call__\nclass param_checker:\n # In this example l is the parameter you pass to the decorator. \n # For example, l could be ['req_param_1', 'req_param_2'].\n def __init__(self, l):\n self.l = l\n\n # This makes the instance callable\n def __call__(self, functionToBeDecorated):\n def wrapper(*args, **kwargs):\n # For the successful call below args = () and\n # kwargs = {'ticket_params': {'req_param_1': 'param_1', 'req_param_2': 'param_2'}}\n if \"ticket_params\" not in kwargs or any(necessary not in kwargs[\"ticket_params\"] for necessary in self.l):\n # if the ticket params parameter has not been specified, or if\n # any of the required parameters are not present raise an exception\n raise MyCustomException\n return functionToBeDecorated(*args, **kwargs)\n return wrapper\n\n@param_checker(['req_param_1', 'req_param_2'])\ndef myfunction(ticket_params=None): \n # if the two required params are present this will print\n print \"params \", ticket_params\n\nif __name__ == \"__main__\":\n try:\n myfunction()\n except MyCustomException:\n print \"all required params not supplied\"\n try:\n myfunction(ticket_params={'req_param_1': 'param_1'})\n except MyCustomException:\n print \"all required params not supplied\"\n myfunction(ticket_params={'req_param_1': 'param_1', 'req_param_2': 'param_2'})\n\n", "Check Alex's answer in order to understand python decorators; by the way:\n1) what aren't you understanding of decorators? Don't you understand decorators as a general concept, or Python decorators? Beware, the \"classical\" decorator pattern, java annotations and python decorators are different things.\n2) python decorators should always return a function, e.g. in your code the return value of param_checker([...]) should be a function that accepts a function as param (the func to be decorated), and returns a function with the same signature as my_decorated_function. Take a look at the following example; the decorator function is executed just once (when the class is created), while the decorated func is then executed at every call. In this specific example, it then invokes the original func, but that's not a requirement.\ndef decorator(orig_func):\n print orig_func\n\n def decorated(self, a):\n print \"aahahah\", orig_func(self, a)\n\n return decorated\n\n\nclass Example(object):\n @decorator\n def do_example(self, a):\n return 2 * a\n\n\nm = Example()\nm.do_example(1)\n\n3) you might not be doing the best thing in the way you're using decorators. They should usually be employed when there's some concept which is quite orthogonal to what you're actually programming, and can be reused around - it's essentially the Python way of doing AOP. Your param_checker might not be that orthogonal - if your decorator gets just used once, then it's probably not a good place to use a decorator at all. Your param_checker seems to be the case - it assumes that the decorated func takes a single arg which is a dictionary - are there many funcs in your code with such a signature and behaviour? If the answer is \"no\", just check for params at the begininng of the func and raise an exception if they're missing.\n", "This is a good explanation for those asking the same question:\n# This does nothing.\n\nclass donothing(object):\n def __init__(self, func):\n \"\"\"\n The 'func' argument is the function being decorated because in this\n case, we're not instantiating the decorator class. Instead we are just\n using the class object as a callable (a class is always callable as this\n is how an instance is returned) to use as a decorator, which means that\n it is being instantiated upon definition of the decorated function and\n the decorated function is being passed in as an argument to the class's\n __init__ method.\n \"\"\"\n self.func = func\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n The __call__ function is called when the decorated function is called\n because the function has be eaten by the decorator class. Now it's up to\n the this method to return a call to the original function. The arguments\n are passed in as args, kwargs to be manipulated.\n \"\"\"\n # Returns original function call with original arguments.\n return self.func(*args, **kwargs)\n\n@donothing\ndef printer(text):\n print(text)\n\nprinter('hello world')\n\n# The printer function is now an alias for the donothing instance created, so\n# the preceding was the same as:\n#\n# instance = donothing(printer)\n# instance('hello world')\n#\n\n\n# Next example:\n\nclass checkforkeysinparams(object):\n def __init__(self, required):\n self.required = set(required)\n\n def __call__(self, params):\n def wrapper(params):\n missing = self.required.difference(params)\n if missing:\n raise TypeError('Missing from \"params\" argument: %s' % ', '.join(sorted(missing)))\n return wrapper\n\n\n# Apply decorator class, passing in the __init__'s 'required' argument.\n\n@checkforkeysinparams(['name', 'pass', 'code'])\ndef complex_function(params):\n # Obviously these three are needed or a KeyError will be raised.\n print(params['name'])\n print(params['pass'])\n print(params['code'])\n\n\n# Create params to pass in. Note, I've commented out one of the required params.\n\nparams = {\n 'name': 'John Doe',\n 'pass': 'OpenSesame',\n #'code': '1134',\n}\n\n# This call will output: TypeError: Missing from \"params\" argument: code\n\ncomplex_function(params=params)\n\n" ]
[ 11, 5, 3, 2, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002031559_decorator_python.txt
Q: cookielib and form authentication woes in Python InstaMapper is a GPS tracking service that updates the device's position more frequently when the device is being tracked live on the InstaMapper webpage. I'd like to have this happen all the time so I thought I'd write a python script to login to my account and access the page periodically. import urllib2, urllib, cookielib cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) params = urllib.urlencode(dict(username_hb='user', password_hb='hunter2')) opener.open('http://www.instamapper.com/fe?action=login', params) if not 'id' in [cookie.name for cookie in cj]: raise ValueError, "Login failed" # try secured page resp = opener.open('http://www.instamapper.com/fe?page=track&device_key=abc') print resp.read() resp.close() The ValueError is raised each time. If I remove this and read the response, the page thinks I have disabled cookies and blocks access to that page. Why isn't cj grabbing the InstaMapper cookie? Are there better ways to make the tracking service think I'm viewing my account constantly? A: action=login is part of the parameters, and should be treated accordingly: params = urllib.urlencode(dict(action='login', username_hb='user', password_hb='hunter2')) opener.open('http://www.instamapper.com/fe', params) (Also, this particular username/password combination is invalid, I assume, that you actually use a valid username and password in your actual code, otherwise the login fails corretly.) A: Have you looked at whether there is a cookie specifically designed to foil your attempts? I suggest using Wireshark or other inspector to see if there is a cookie that changes (via javascript, etc) when you manually log in. (Ethical note: You may be violating the terms of service and incurring much more cost to the company than you are paying for. I used to run a service like this and every additional/unplanned location update was between $0.01 - $0.05 but I'm sure its come down.)
cookielib and form authentication woes in Python
InstaMapper is a GPS tracking service that updates the device's position more frequently when the device is being tracked live on the InstaMapper webpage. I'd like to have this happen all the time so I thought I'd write a python script to login to my account and access the page periodically. import urllib2, urllib, cookielib cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) params = urllib.urlencode(dict(username_hb='user', password_hb='hunter2')) opener.open('http://www.instamapper.com/fe?action=login', params) if not 'id' in [cookie.name for cookie in cj]: raise ValueError, "Login failed" # try secured page resp = opener.open('http://www.instamapper.com/fe?page=track&device_key=abc') print resp.read() resp.close() The ValueError is raised each time. If I remove this and read the response, the page thinks I have disabled cookies and blocks access to that page. Why isn't cj grabbing the InstaMapper cookie? Are there better ways to make the tracking service think I'm viewing my account constantly?
[ "action=login is part of the parameters, and should be treated accordingly:\nparams = urllib.urlencode(dict(action='login', username_hb='user', password_hb='hunter2')) \nopener.open('http://www.instamapper.com/fe', params)\n\n(Also, this particular username/password combination is invalid, I assume, that you actually use a valid username and password in your actual code, otherwise the login fails corretly.)\n", "Have you looked at whether there is a cookie specifically designed to foil your attempts? I suggest using Wireshark or other inspector to see if there is a cookie that changes (via javascript, etc) when you manually log in.\n(Ethical note: You may be violating the terms of service and incurring much more cost to the company than you are paying for. I used to run a service like this and every additional/unplanned location update was between $0.01 - $0.05 but I'm sure its come down.)\n" ]
[ 0, 0 ]
[]
[]
[ "cookielib", "cookies", "gps", "python" ]
stackoverflow_0002033814_cookielib_cookies_gps_python.txt
Q: Optimize function to sort a list of tuples I need to sort a list of tuples by first item in descending order, and then by second item in ascending order. To do this, I have implemented the following function, but I think it could be faster. >>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0]) >>> sorted([(0, 2), (0, 1), (1, 0), (1, 2)], cmp=compare) [(1, 0), (1, 2), (0, 1), (0, 2)] Is it possible to optimize it? See the comparison against the built-in function: >>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)], cmp=compare)', setup='import random; compare=compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0])').timeit(100000) 4.0584850867917339 >>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)])', setup='import random').timeit(100000) 2.6582965153393161 A: For me, it is a little faster to use a key instead of a comparison function, and arguably also easier to read: sorted([(0, 2), (0, 1), (1, 0), (1, 2)], key = lambda x:(-x[0], x[1])) This requires Python 2.4 or newer. A: How does this stack up for you? compare = lambda a, b: cmp(b[0], a[0]) and cmp(a[1],b[1])
Optimize function to sort a list of tuples
I need to sort a list of tuples by first item in descending order, and then by second item in ascending order. To do this, I have implemented the following function, but I think it could be faster. >>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0]) >>> sorted([(0, 2), (0, 1), (1, 0), (1, 2)], cmp=compare) [(1, 0), (1, 2), (0, 1), (0, 2)] Is it possible to optimize it? See the comparison against the built-in function: >>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)], cmp=compare)', setup='import random; compare=compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0])').timeit(100000) 4.0584850867917339 >>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)])', setup='import random').timeit(100000) 2.6582965153393161
[ "For me, it is a little faster to use a key instead of a comparison function, and arguably also easier to read:\nsorted([(0, 2), (0, 1), (1, 0), (1, 2)], key = lambda x:(-x[0], x[1]))\n\nThis requires Python 2.4 or newer.\n", "How does this stack up for you?\ncompare = lambda a, b: cmp(b[0], a[0]) and cmp(a[1],b[1])\n\n" ]
[ 8, 0 ]
[]
[]
[ "optimization", "python", "sorting" ]
stackoverflow_0002034629_optimization_python_sorting.txt
Q: diff for single lines All diff tools I've found are just comparing line by line instead of char by char. Is there any library that gives details on single line strings? Maybe also a percentage difference, though I guess there are separate functions for that? A: This algorithm diffs word-by-word: http://github.com/paulgb/simplediff available in Python and PHP. It can even spit out HTML formatted output using the <ins> and <del> tags. A: I was looking for something similar recently, and came across wdiff. It operates on words, not characters, but is this close to what you're looking for? A: What you could try is to split both strings up character by character into lines and then you can use diff on that. It's a dirty hack, but atleast it should work and is quite easy to implement. Alternately you can split the string up into a list of chars in Python and use difflib. Check Python difflib reference A: You can implement a simple Needleman–Wunsch algorithm. The pseudo code is available on Wikipedia: http://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm
diff for single lines
All diff tools I've found are just comparing line by line instead of char by char. Is there any library that gives details on single line strings? Maybe also a percentage difference, though I guess there are separate functions for that?
[ "This algorithm diffs word-by-word: \nhttp://github.com/paulgb/simplediff\navailable in Python and PHP. It can even spit out HTML formatted output using the <ins> and <del> tags.\n", "I was looking for something similar recently, and came across wdiff. It operates on words, not characters, but is this close to what you're looking for?\n", "What you could try is to split both strings up character by character into lines and then you can use diff on that. It's a dirty hack, but atleast it should work and is quite easy to implement.\nAlternately you can split the string up into a list of chars in Python and use difflib. Check Python difflib reference\n", "You can implement a simple Needleman–Wunsch algorithm. The pseudo code is available on Wikipedia: http://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm\n" ]
[ 5, 4, 3, 3 ]
[]
[]
[ "diff", "python" ]
stackoverflow_0002034727_diff_python.txt
Q: Distributing a python application I have a simple python application where my directory structure is as follows: project/ main.py config.py plugins/ plugin1 plugin2 ... Config.py only loads configuration files, it does not contain any configuration info in itself. I now want to distribute this program, and I thought I'd use setuptools to do it. The file users are expected to use is main.py, so that one clearly goes into /usr/bin and the rest of the files go into /usr/share/project. But there's one problem: I would somehow need to tell main.py to look for config.py in the share directory. But I can't really be sure where exactly the share directory is since that's up to setuptools, right? What's the best practice when distributing Python-based applications? A: setuptools install your package in a location which is reachable from python i.e. you can import it: import project the problem raise when you do relative imports instead of absolute imports. if your main.py imports config.py it works because they live in the same directory. when you move your main.py to another location like /usr/bin or another location present in PATH environment variable, python try to import config.py from sys.path and not from your package dir. the solution is to use absolute import: from project import config now main.py is "movable". another solution, which i prefer, is using automatic script creation offered by setuptools. instead of having your code in a if __name__ == "__main__": # here all your beautiful code statement, put your code in a function (main could be a good name): def main(): # put your code here if __name__ == "__main__": # not needed, just in case... main() now modify your setup.py: setup( # ... entry_points = { "console_scripts": [ # modify script_name with the name you want use from shell # $ script_name [params] "script_name = project.main:main", ], } ) that's all. after an install setuptools will create a wrapper script which is callable from shell and that calls your main function. now main.py can live in your project directory and you don't need anymore to move it in a bin/ directory. note that setuptools automatically puts this script in the bin/ directory relative to the installation prefix. es. python setup.py install --prefix ~/.local install your project package in ~/.local/lib/python<version>/site-packages/<package_name> and your script in ~/.local/bin/<script_name> so be sure that ~/.local/bin is present in your PATH env. more info at: http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation
Distributing a python application
I have a simple python application where my directory structure is as follows: project/ main.py config.py plugins/ plugin1 plugin2 ... Config.py only loads configuration files, it does not contain any configuration info in itself. I now want to distribute this program, and I thought I'd use setuptools to do it. The file users are expected to use is main.py, so that one clearly goes into /usr/bin and the rest of the files go into /usr/share/project. But there's one problem: I would somehow need to tell main.py to look for config.py in the share directory. But I can't really be sure where exactly the share directory is since that's up to setuptools, right? What's the best practice when distributing Python-based applications?
[ "setuptools install your package in a location which is reachable from python i.e. you can import it:\nimport project\n\nthe problem raise when you do relative imports instead of absolute imports. if your main.py imports config.py it works because they live in the same directory. when you move your main.py to another location like /usr/bin or another location present in PATH environment variable, python try to import config.py from sys.path and not from your package dir. the solution is to use absolute import:\nfrom project import config\n\nnow main.py is \"movable\".\nanother solution, which i prefer, is using automatic script creation offered by setuptools.\ninstead of having your code in a\nif __name__ == \"__main__\":\n # here all your beautiful code\n\nstatement, put your code in a function (main could be a good name):\ndef main():\n # put your code here\n\nif __name__ == \"__main__\": # not needed, just in case...\n main()\n\nnow modify your setup.py:\nsetup(\n # ...\n entry_points = {\n \"console_scripts\": [\n # modify script_name with the name you want use from shell\n # $ script_name [params]\n \"script_name = project.main:main\",\n ],\n }\n)\n\nthat's all. after an install setuptools will create a wrapper script which is callable from shell and that calls your main function. now main.py can live in your project directory and you don't need anymore to move it in a bin/ directory. note that setuptools automatically puts this script in the bin/ directory relative to the installation prefix.\nes.\npython setup.py install --prefix ~/.local\n\ninstall your project package in\n~/.local/lib/python<version>/site-packages/<package_name>\n\nand your script in\n~/.local/bin/<script_name>\n\nso be sure that ~/.local/bin is present in your PATH env.\nmore info at: http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation\n" ]
[ 11 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0002034787_python_setuptools.txt
Q: Datastore Design Inquiry I'm creating a Trivia app, and need some help designing my model relationships. This question may get fairly complicated, but I'll try to be concise. Trivia questions will all be part of a particular category. Categories may be a category within another category. If a trivia question is created/removed, I need to make sure that I also update a counter. In this way, I'll be able to see how many questions are in each category, and display that back to users. If a category has 'child' categories, I will need a way of displaying a cumulative counter of all sub-categories. Accurate tallies are fairly important, but not mission critical. I do not mind using sharded counters. My question is, how should I design this so that it will adopt GAE denormalization, and maintain optimization? I was thinking of having a Category class, with a ListProperty in each, which will represent the ancestor tree. It will contain a key to each parent entity in the tree, in order. But, should I also specify a parent when constructing the entities, or is that not needed in this case? I'm thinking that I may have to run my counter updates in transaction, which is why I am considering a parent-child relationship. Or perhaps there is more optimized way of designing my relationships that will still allow me to keep fairly accurate counters of all questions in each category. Thanks in advance for any help. A: I'm not that familiar with Google App Engine, but here are some thoughts. First is to consider if "tags" are more appropriate than category & sub categories. Will their be a rigid 2 level category scheme? Will all items have a main and subcategory assignment? Rather than having a class for each category, have you considered a CategoryList class that would have a incrementCategoryByName(str name) method? The class contain a dictionary of classes without having to have the overhead of a class for each category. A: This isn't as complicated as you might think. Here's a Category class: class Category(db.Model): title = db.StringProperty() subcategories = db.ListProperty(db.Key) quizzes = db.ListProperty(db.Key) def add_sub_category(self, title): new_category = Category(title) new_category.put() self.subcategories.append(new_category) self.put() return new_category By keeping both the subcategories and quizzes that are assocaited with this Category in a ListProperty, getting a count of them is as simple as using the len() operator. You could use it something like this: main_category = Category("Main") main_category.put() sports_category = main_category.add_sub_category("Sports") baseball_category = sports_category.add_sub_category("Baseball") football_category = sports_category.add_sub_category("Football") hockey_category = sports_category.add_sub_category("Hockey") tv_category = main_category.add_sub_category("TV") ...etc...
Datastore Design Inquiry
I'm creating a Trivia app, and need some help designing my model relationships. This question may get fairly complicated, but I'll try to be concise. Trivia questions will all be part of a particular category. Categories may be a category within another category. If a trivia question is created/removed, I need to make sure that I also update a counter. In this way, I'll be able to see how many questions are in each category, and display that back to users. If a category has 'child' categories, I will need a way of displaying a cumulative counter of all sub-categories. Accurate tallies are fairly important, but not mission critical. I do not mind using sharded counters. My question is, how should I design this so that it will adopt GAE denormalization, and maintain optimization? I was thinking of having a Category class, with a ListProperty in each, which will represent the ancestor tree. It will contain a key to each parent entity in the tree, in order. But, should I also specify a parent when constructing the entities, or is that not needed in this case? I'm thinking that I may have to run my counter updates in transaction, which is why I am considering a parent-child relationship. Or perhaps there is more optimized way of designing my relationships that will still allow me to keep fairly accurate counters of all questions in each category. Thanks in advance for any help.
[ "I'm not that familiar with Google App Engine, but here are some thoughts. First is to consider if \"tags\" are more appropriate than category & sub categories. Will their be a rigid 2 level category scheme? Will all items have a main and subcategory assignment? \nRather than having a class for each category, have you considered a CategoryList class that would have a incrementCategoryByName(str name) method? The class contain a dictionary of classes without having to have the overhead of a class for each category.\n", "This isn't as complicated as you might think. Here's a Category class:\nclass Category(db.Model):\n title = db.StringProperty()\n subcategories = db.ListProperty(db.Key)\n quizzes = db.ListProperty(db.Key)\n\n def add_sub_category(self, title):\n new_category = Category(title)\n new_category.put()\n self.subcategories.append(new_category)\n self.put()\n\n return new_category\n\nBy keeping both the subcategories and quizzes that are assocaited with this Category in a ListProperty, getting a count of them is as simple as using the len() operator.\nYou could use it something like this:\nmain_category = Category(\"Main\")\nmain_category.put()\n\nsports_category = main_category.add_sub_category(\"Sports\")\nbaseball_category = sports_category.add_sub_category(\"Baseball\")\nfootball_category = sports_category.add_sub_category(\"Football\")\nhockey_category = sports_category.add_sub_category(\"Hockey\")\n\ntv_category = main_category.add_sub_category(\"TV\")\n\n...etc...\n" ]
[ 0, 0 ]
[]
[]
[ "database_design", "google_app_engine", "python" ]
stackoverflow_0002034584_database_design_google_app_engine_python.txt
Q: Download a webpage and media I need to download a webpage and all its media (like css javascript and images) to make a sort of backup (like firefox does when you click on File -> Save) with python. Is there any library to do that or I shall create my own one? A: It's not exactly Python, but there's a pretty standard *nix utility called wget which you can call from a Python script that will do this.
Download a webpage and media
I need to download a webpage and all its media (like css javascript and images) to make a sort of backup (like firefox does when you click on File -> Save) with python. Is there any library to do that or I shall create my own one?
[ "It's not exactly Python, but there's a pretty standard *nix utility called wget which you can call from a Python script that will do this.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002035324_python.txt
Q: Python: Why does this doc test fail? This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module: class requireparams(object): """ >>> @requireparams(['name', 'pass', 'code']) >>> def complex_function(params): >>> print(params['name']) >>> print(params['pass']) >>> print(params['code']) >>> >>> params = { >>> 'name': 'John Doe', >>> 'pass': 'OpenSesame', >>> #'code': '1134', >>> } >>> >>> complex_function(params) Traceback (most recent call last): ... ValueError: Missing from "params" argument: code """ def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise ValueError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper if __name__ == "__main__": import doctest doctest.testmod() A: doctest requires that you use ... for continuation lines: >>> @requireparams(['name', 'pass', 'code']) ... def complex_function(params): ... print(params['name']) ... print(params['pass']) ... print(params['code']) ... >>> params = { ... 'name': 'John Doe', ... 'pass': 'OpenSesame', ... #'code': '1134', ... } ... >>> complex_function(params) A: Try pasting the code exactly from the python prompt. That means it will contain some ... as well as >>>. Otherwise the doctest parser won't know when there's a multiline expression. On preview: What Greg said. A: Here's my module after I corrected it (it works now): class requiresparams(object): """ Used as a decorator with an iterable passed in, this will look for each item in the iterable given as a key in the params argument of the function being decorated. It was built for a series of PayPal methods that require different params, and AOP was the best way to handle it while staying DRY. >>> @requiresparams(['name', 'pass', 'code']) ... def complex_function(params): ... print(params['name']) ... print(params['pass']) ... print(params['code']) >>> >>> params = { ... 'name': 'John Doe', ... 'pass': 'OpenSesame', ... #'code': '1134', ... } >>> >>> complex_function(params) Traceback (most recent call last): ... ValueError: Missing from "params" argument: code """ def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise ValueError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper if __name__ == "__main__": import doctest doctest.testmod()
Python: Why does this doc test fail?
This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module: class requireparams(object): """ >>> @requireparams(['name', 'pass', 'code']) >>> def complex_function(params): >>> print(params['name']) >>> print(params['pass']) >>> print(params['code']) >>> >>> params = { >>> 'name': 'John Doe', >>> 'pass': 'OpenSesame', >>> #'code': '1134', >>> } >>> >>> complex_function(params) Traceback (most recent call last): ... ValueError: Missing from "params" argument: code """ def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise ValueError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper if __name__ == "__main__": import doctest doctest.testmod()
[ "doctest requires that you use ... for continuation lines:\n>>> @requireparams(['name', 'pass', 'code'])\n... def complex_function(params):\n... print(params['name'])\n... print(params['pass'])\n... print(params['code'])\n...\n>>> params = {\n... 'name': 'John Doe',\n... 'pass': 'OpenSesame',\n... #'code': '1134',\n... }\n...\n>>> complex_function(params)\n\n", "Try pasting the code exactly from the python prompt. That means it will contain some ... as well as >>>. Otherwise the doctest parser won't know when there's a multiline expression.\nOn preview: What Greg said.\n", "Here's my module after I corrected it (it works now):\nclass requiresparams(object):\n \"\"\"\n\n Used as a decorator with an iterable passed in, this will look for each item\n in the iterable given as a key in the params argument of the function being\n decorated. It was built for a series of PayPal methods that require\n different params, and AOP was the best way to handle it while staying DRY.\n\n\n >>> @requiresparams(['name', 'pass', 'code'])\n ... def complex_function(params):\n ... print(params['name'])\n ... print(params['pass'])\n ... print(params['code'])\n >>> \n >>> params = {\n ... 'name': 'John Doe',\n ... 'pass': 'OpenSesame',\n ... #'code': '1134',\n ... }\n >>> \n >>> complex_function(params)\n Traceback (most recent call last):\n ...\n ValueError: Missing from \"params\" argument: code\n \"\"\"\n def __init__(self, required):\n self.required = set(required)\n\n def __call__(self, params):\n def wrapper(params):\n missing = self.required.difference(params)\n if missing:\n raise ValueError('Missing from \"params\" argument: %s' % ', '.join(sorted(missing)))\n return wrapper\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n" ]
[ 7, 1, 0 ]
[]
[]
[ "docstring", "doctest", "python" ]
stackoverflow_0002035406_docstring_doctest_python.txt
Q: Python UDP socket options for multiple & concurrent clients Let me explain a bit the app i'm doing. I'm creating a central UDP (needs to be UDP) server for multiple and concurrent clients that also "talk" between them. I do a check into a dict of known clients addresses and create a client handler thread if "i dont know" the client. Else, the thread receives the data ad does its job. The new thread receives a reference to the socket and the caller address, so they use socket.sendTo with that address and the data. The problem appears when a client closes it's client (Alt+F4) and someone talks to em, cause the socket throws a 10054 error, "Socket connection reset". Not expected in UDP, i think. The "talk" method on the client threads is also between try & except tags but still, is the UDP server "recvfrom" the one that triggers the exception. I am using Python 2.5 (need it for the code) and this socket options: host = "0.0.0.0" port = 10000 UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) UDPSock.bind((host,port)) There are some options that let me do what I wanted or a library that solves this things?. Or If i am doing it wrong... there is a way to do/emulate the same behavior as threaded TCP socket (create a new client handler thread on accept) but with UDP? Thanks for reading ;) A: The 'socket reset' happens because the client sent an ICMP port-unreachable in response to the datagram sent to a socket that wasn't there any more. Perfectly reasonable way to express that in the API, so you're just going to have to handle it. But if you just ignore the exception, the socket should still be working.
Python UDP socket options for multiple & concurrent clients
Let me explain a bit the app i'm doing. I'm creating a central UDP (needs to be UDP) server for multiple and concurrent clients that also "talk" between them. I do a check into a dict of known clients addresses and create a client handler thread if "i dont know" the client. Else, the thread receives the data ad does its job. The new thread receives a reference to the socket and the caller address, so they use socket.sendTo with that address and the data. The problem appears when a client closes it's client (Alt+F4) and someone talks to em, cause the socket throws a 10054 error, "Socket connection reset". Not expected in UDP, i think. The "talk" method on the client threads is also between try & except tags but still, is the UDP server "recvfrom" the one that triggers the exception. I am using Python 2.5 (need it for the code) and this socket options: host = "0.0.0.0" port = 10000 UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) UDPSock.bind((host,port)) There are some options that let me do what I wanted or a library that solves this things?. Or If i am doing it wrong... there is a way to do/emulate the same behavior as threaded TCP socket (create a new client handler thread on accept) but with UDP? Thanks for reading ;)
[ "The 'socket reset' happens because the client sent an ICMP port-unreachable in response to the datagram sent to a socket that wasn't there any more. Perfectly reasonable way to express that in the API, so you're just going to have to handle it. But if you just ignore the exception, the socket should still be working.\n" ]
[ 1 ]
[]
[]
[ "clients", "concurrency", "python", "sockets" ]
stackoverflow_0002035542_clients_concurrency_python_sockets.txt
Q: Python synchronised reading of sorted files I have two groups of files that contain data in CSV format with a common key (Timestamp) - I need to walk through all the records chronologically. Group A: 'Environmental Data' Filenames are in format A_0001.csv, A_0002.csv, etc. Pre-sorted ascending Key is Timestamp, i.e.YYYY-MM-DD HH:MM:SS Contains environmental data in CSV/column format Very large, several GBs worth of data Group B: 'Event Data' Filenames are in format B_0001.csv, B_0002.csv Pre-sorted ascending Key is Timestamp, i.e.YYYY-MM-DD HH:MM:SS Contains event based data in CSV/column format Relatively small compared to Group A files, < 100 MB What is best approach? Pre-merge: Use one of the various recipes out there to merge the files into a single sorted output and then read it for processing Real-time merge: Implement code to 'merge' the files in real-time I will be running lots of iterations of the post-processing side of things. Any thoughts or suggestions? I am using Python. A: im thinking importing it into a db (mysql, sqlite, etc) will give better performance than merging it in script. the db typically has optimized routines for loading csv and the join will be probably be as fast or much faster than merging 2 dicts (one being very large) in python. A: "YYYY-MM-DD HH:MM:SS" can be sorted with a simple ascii compare. How about reusing external merge logic? If the first field is the key then: for entry in os.popen("sort -m -t, -k1,1 file1 file2"): process(entry) A: This is a similar to a relational join. Since your timestamps don't have to match, it's called a non-equijoin. Sort-Merge is one of several popular algorithms. For non-equijoins, it works well. I think this would be what you're called "pre-merge". I don't know what you mean by "merge in real time", but I suspect it's still a simple sort-merge, which is a fine technique, heavily used by real databases. Nested Loops can also work. In this case, you read the smaller table in the outer loop. In the inner loop you find all of the "matching" rows from the larger table. This is effectively a sort-merge, but with an assumption that there will be multiple rows from the big table that will match the small table. This, BTW, will allow you to more properly assign meaning to the relationship between Event Data and Environmental Data. Rather than reading the result of a massive sort merge and trying to determine which kind of record you've got, the nested loops handle that well. Also, you can do "lookups" into the smaller table while reading the larger table. This is hard when you're doing non-equal comparisons because you don't have a proper key to do a simple retrieval from a simple dict. However, you can easily extend dict (override __contains__ and __getitem__) to do range comparisons on a key instead of simple equality tests. A: I would suggest pre-merge. Reading a file takes a lot of processor time. Reading two files, twice as much. Since your program will be dealing with a large input (lots of files, esp in Group A), I think it would be better to get it over with in one file read, and have all your relevant data in that one file. It would also reduce the number of variables and read statements you will need. This will improve the runtime of your algorithm, and I think that's a good enough reason in this scenario to decide to use this approach Hope this helps A: You could read from the files in chunks of, say, 10000 records (or whatever number further profiling tells you to be optimal) and merge on the fly. Possibly using a custom class to encapsulate the IO; the actual records could then be accessed through the generator protocol (__iter__ + next). This would be memory friendly, probably very good in terms of total time to complete the operation and would enable you to produce output incrementally. A sketch: class Foo(object): def __init__(self, env_filenames=[], event_filenames=[]): # open the files etc. def next(self): if self._cache = []: # take care of reading more records else: # return the first record and pop it from the cache # ... other stuff you need ...
Python synchronised reading of sorted files
I have two groups of files that contain data in CSV format with a common key (Timestamp) - I need to walk through all the records chronologically. Group A: 'Environmental Data' Filenames are in format A_0001.csv, A_0002.csv, etc. Pre-sorted ascending Key is Timestamp, i.e.YYYY-MM-DD HH:MM:SS Contains environmental data in CSV/column format Very large, several GBs worth of data Group B: 'Event Data' Filenames are in format B_0001.csv, B_0002.csv Pre-sorted ascending Key is Timestamp, i.e.YYYY-MM-DD HH:MM:SS Contains event based data in CSV/column format Relatively small compared to Group A files, < 100 MB What is best approach? Pre-merge: Use one of the various recipes out there to merge the files into a single sorted output and then read it for processing Real-time merge: Implement code to 'merge' the files in real-time I will be running lots of iterations of the post-processing side of things. Any thoughts or suggestions? I am using Python.
[ "im thinking importing it into a db (mysql, sqlite, etc) will give better performance than merging it in script. the db typically has optimized routines for loading csv and the join will be probably be as fast or much faster than merging 2 dicts (one being very large) in python.\n", "\"YYYY-MM-DD HH:MM:SS\" can be sorted with a simple ascii compare.\nHow about reusing external merge logic? If the first field is the key then:\nfor entry in os.popen(\"sort -m -t, -k1,1 file1 file2\"):\n process(entry)\n\n", "This is a similar to a relational join. Since your timestamps don't have to match, it's called a non-equijoin.\nSort-Merge is one of several popular algorithms. For non-equijoins, it works well. I think this would be what you're called \"pre-merge\". I don't know what you mean by \"merge in real time\", but I suspect it's still a simple sort-merge, which is a fine technique, heavily used by real databases.\nNested Loops can also work. In this case, you read the smaller table in the outer loop. In the inner loop you find all of the \"matching\" rows from the larger table. This is effectively a sort-merge, but with an assumption that there will be multiple rows from the big table that will match the small table. \nThis, BTW, will allow you to more properly assign meaning to the relationship between Event Data and Environmental Data. Rather than reading the result of a massive sort merge and trying to determine which kind of record you've got, the nested loops handle that well. \nAlso, you can do \"lookups\" into the smaller table while reading the larger table. \nThis is hard when you're doing non-equal comparisons because you don't have a proper key to do a simple retrieval from a simple dict. However, you can easily extend dict (override __contains__ and __getitem__) to do range comparisons on a key instead of simple equality tests.\n", "I would suggest pre-merge.\nReading a file takes a lot of processor time. Reading two files, twice as much. Since your program will be dealing with a large input (lots of files, esp in Group A), I think it would be better to get it over with in one file read, and have all your relevant data in that one file. It would also reduce the number of variables and read statements you will need.\nThis will improve the runtime of your algorithm, and I think that's a good enough reason in this scenario to decide to use this approach\nHope this helps\n", "You could read from the files in chunks of, say, 10000 records (or whatever number further profiling tells you to be optimal) and merge on the fly. Possibly using a custom class to encapsulate the IO; the actual records could then be accessed through the generator protocol (__iter__ + next).\nThis would be memory friendly, probably very good in terms of total time to complete the operation and would enable you to produce output incrementally.\nA sketch:\nclass Foo(object):\n\n def __init__(self, env_filenames=[], event_filenames=[]):\n # open the files etc.\n\n def next(self):\n if self._cache = []:\n # take care of reading more records\n else:\n # return the first record and pop it from the cache\n\n # ... other stuff you need ...\n\n" ]
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "file", "merge", "python", "sorting" ]
stackoverflow_0002035285_file_merge_python_sorting.txt
Q: Coming from a Visual C# Express IDE/C# programming background, is there a tutorial for creating python applications? It's very overwhelming coming from something that helps you create applications straight forward to something with somewhat convoluted documentation. Can someone please share a tutorial on how to create a simple Hello World application using Python. No, I don't mean command line. I mean a physical window. I'm trying to learn how to program in Python and so far all I find is command line applications, and I don't really find use for them unless I can visually show off my skills. So, where can I learn some Python GUI development. People have suggested wxWidgets, PyQT, etc. but once again, that means nothing to me, because I know diddly squat about them. I need an up to date tutorial. :S A: Here's a great tutorial for wxPython (my GUI API of choice: extremely powerful, good community/mailing list, and cross-platform (it wraps the native platform's widgets)) http://wiki.wxpython.org/Getting%20Started Installing wxpython can be done through a simple setup.exe : http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.10.1-py26.exe or http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.10.1-py25.exe (depending on python version) Here's a simple hello world, with a simple event bound to the button. import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.StaticText(self, label="hello, world!") button = wx.Button(self, label="press me") sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(text, flag=wx.ALL, border=20) sizer.Add(button, flag=wx.ALL, border=20) self.SetSizer(sizer) self.Layout() self.Show(True) self.Bind(wx.EVT_BUTTON, self.on_button, button) def on_button(self, event): wx.MessageBox("Hey!") if __name__ == "__main__": app = wx.App(False) f = MyFrame() or, an even simpler example: import wx app = wx.PySimpleApp() frame = wx.Frame(None, wx.ID_ANY, "Hello World") frame.Show(True) app.MainLoop() app.MainLoop()
Coming from a Visual C# Express IDE/C# programming background, is there a tutorial for creating python applications?
It's very overwhelming coming from something that helps you create applications straight forward to something with somewhat convoluted documentation. Can someone please share a tutorial on how to create a simple Hello World application using Python. No, I don't mean command line. I mean a physical window. I'm trying to learn how to program in Python and so far all I find is command line applications, and I don't really find use for them unless I can visually show off my skills. So, where can I learn some Python GUI development. People have suggested wxWidgets, PyQT, etc. but once again, that means nothing to me, because I know diddly squat about them. I need an up to date tutorial. :S
[ "Here's a great tutorial for wxPython (my GUI API of choice: extremely powerful, good community/mailing list, and cross-platform (it wraps the native platform's widgets))\nhttp://wiki.wxpython.org/Getting%20Started\nInstalling wxpython can be done through a simple setup.exe :\nhttp://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.10.1-py26.exe or\nhttp://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.10.1-py25.exe\n(depending on python version)\nHere's a simple hello world, with a simple event bound to the button.\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n text = wx.StaticText(self, label=\"hello, world!\")\n button = wx.Button(self, label=\"press me\")\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(text, flag=wx.ALL, border=20)\n sizer.Add(button, flag=wx.ALL, border=20)\n\n self.SetSizer(sizer)\n self.Layout()\n self.Show(True)\n self.Bind(wx.EVT_BUTTON, self.on_button, button)\n\n def on_button(self, event):\n wx.MessageBox(\"Hey!\")\n\nif __name__ == \"__main__\":\n app = wx.App(False)\n f = MyFrame()\n\nor, an even simpler example:\nimport wx\napp = wx.PySimpleApp()\nframe = wx.Frame(None, wx.ID_ANY, \"Hello World\")\nframe.Show(True)\napp.MainLoop()\n app.MainLoop()\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002035599_python.txt
Q: purpose of '"sss".decode("base64").decode("zlib")' ACTIVATE_THIS = """ eJx1UsGOnDAMvecrIlYriDRlKvU20h5aaY+teuilGo1QALO4CwlKAjP8fe1QGGalRoLEefbzs+Mk Sb7NcvRo3iTcoGqwgyy06As+HWSNVciKaBTFywYoJWc7yit2ndBVwEkHkIzKCV0YdQdmkvShs6YH E3IhfjFaaSNLoHxQy2sLJrL0ow98JQmEG/rAYn7OobVGogngBgf0P0hjgwgt7HOUaI5DdBVJkggR 3HwSktaqWcCtgiHIH7qHV+esW2CnkRJ+9R5cQGsikkWEV/J7leVGs9TV4TvcO5QOOrTHYI+xeCjY JR/m9GPDHv2oSZunUokS2A/WBelnvx6tF6LUJO2FjjlH5zU6Q+Kz/9m69LxvSZVSwiOlGnT1rt/A 77j+WDQZ8x9k2mFJetOle88+lc8sJJ/AeerI+fTlQigTfVqJUiXoKaaC3AqmI+KOnivjMLbvBVFU 1JDruuadNGcPmkgiBTnQXUGUDd6IK9JEQ9yPdM96xZP8bieeMRqTuqbxIbbey2DjVUNzRs1rosFS TsLAdS/0fBGNdTGKhuqD7mUmsFlgGjN2eSj1tM3GnjfXwwCmzjhMbR4rLZXXk+Z/6Hp7Pn2+kJ49 jfgLHgI4Jg== """.decode("base64").decode("zlib") my code: import zlib print 'dsss'.decode('base64').decode('zlib')#error Traceback (most recent call last): File "D:\zjm_code\b.py", line 4, in <module> print 'dsss'.decode('base64').decode('zlib') File "D:\Python25\lib\encodings\zlib_codec.py", line 43, in zlib_decode output = zlib.decompress(input) zlib.error: Error -3 while decompressing data: unknown compression method a='dsss'.encode('zlib') print a a.encode('base64') print a a.decode('base64')#error print a a.decode('zlib') print a x\x9cK)..Traceback (most recent call last): File "D:\zjm_code\b.py", line 7, in <module> a.decode('base64') File "D:\Python25\lib\encodings\base64_codec.py", line 42, in base64_decode output = base64.decodestring(input) File "D:\Python25\lib\base64.py", line 321, in decodestring return binascii.a2b_base64(s) binascii.Error: Incorrect padding a='dsss' a=a.encode('zlib') print a a=a.decode('zlib') print a#why can't print 'dsss' x\x9cK).. a='dsss' a=a.encode('zlib') #print a a=a.decode('zlib') print a#its ok i think the 'print a' encode the a with 'uhf-8'. so: #encoding:utf-8 a='dsss' a=a.encode('zlib') print a a=a.decode('utf-8')#but error. a=a.decode('zlib') print a# x\x9cK)..Traceback (most recent call last): File "D:\zjm_code\b.py", line 5, in <module> a=a.decode('utf-8') File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte A: The data in the strings is encoded and compressed binary data. The .decode("base64").decode("zlib") unencodes and decompresses it. The error you got was because 'dsss' decoded from base64 is not valid zlib compressed data. A: What is the purpose of x.decode(”base64”).decode(”zlib”) for x in ("sss", "dsss", random_garbage)? Excuse me, you should know; you are the one who is doing it! Edit after OP's addition of various puzzles Puzzle 1 a='dsss'.encode('zlib') print a a.encode('base64') print a a.decode('base64')#error print a a.decode('zlib') print a Resolution: all 3 statements of the form a.XXcode('encoding') should be a = a.XXcode('encoding') Puzzle 2 a='dsss' a=a.encode('zlib') print a a=a.decode('zlib') print a#why can't print 'dsss' x\x9cK).. But it does print 'dsss': >>> a='dsss' >>> a=a.encode('zlib') >>> print a x£K)..♠ ♦F☺¥ >>> a=a.decode('zlib') >>> print a#why can't print 'dsss' dsss >>> Puzzle 3 """i think the 'print a' encode the a with 'uhf-8'.""" Resolution: You think extremely incorrectly. What follows the print is an expression. There are no such side effects. What do you imagine happens when you do this: print 'start text ' + a + 'end text' ? What do you imagine happens if you do print a twice? Encoding the already-encoded text again? Why don't you stop imagining and try it out? In any case, note that the output of str.encode('zlib') is an str object, not a unicode object: >>> print repr('dsss'.encode('zlib')) 'x\x9cK)..\x06\x00\x04F\x01\xbe' Getting from that to UTF-8 is going to be somewhat difficult ... it would have to be decoded into unicode first -- with what codec? ascii and utf8 are going to have trouble with the '\x9c' and the '\xbe' ... A: .decode('base64') can be called only on a string that's encoded as "base-64, in order to retrieve the byte sequence that was there encoded. Presumably that byte sequence, in the example you bring, was zlib-compressed, and so the .decode('zlib') part decompresses it. Now, for your case: >>> 'dsss'.decode('base64') 'v\xcb,' But 'v\xcv,' is not a zlib-compressed string! And so of course you cannot ask zlib to "decompress" it. Fortunately zlib recognizes the fact (that 'v\xcv,' could not possibly have been produced by applying any of the compression algorithms zlib knows about to any input whatsoever) and so gives you a helpful error message (instead of a random-ish string of bytes, which you might well have gotten if you had randomly supplied a different but equally crazy input string!-) Edit: the error in a.encode('base64') print a a.decode('base64')#error is obviously due to the fact that strings are immutable: just calling a.encode (or any other method) does not alter a, it produces a new string object (and here you're just printing it). In the next snippet, the error is only in the OP's mind: >>> a='dsss' >>> a=a.encode('zlib') >>> print a x?K)..F? >>> a=a.decode('zlib') >>> print a#why can't print 'dsss' dsss >>> that "why can't print" question is truly peculiar, applied to code that does print 'dsss'. Finally, i think the 'print a' encode the a with 'uhf-8'. You think wrongly: there's no such thing as "uhf-8" (you mean "utf-8" maybe?), and anyway print a does not alter a, any more than just calling a.encode does. A: It is the reverse of: original_message.encode('zlib').encode('base64') zlib is a binary compression algorithm. base64 is a text encoding of binary data, which is useful to send binary message through text protocols like SMTP. After 'dsss' was decoded from base64 (the three bytes 76h, CBh, 2Ch), the result was not valid zlib compressed data so it couldn't be decoded. Try printing ACTIVATE_THIS to see the result of the decoding. It turns out to be some Python code.
purpose of '"sss".decode("base64").decode("zlib")'
ACTIVATE_THIS = """ eJx1UsGOnDAMvecrIlYriDRlKvU20h5aaY+teuilGo1QALO4CwlKAjP8fe1QGGalRoLEefbzs+Mk Sb7NcvRo3iTcoGqwgyy06As+HWSNVciKaBTFywYoJWc7yit2ndBVwEkHkIzKCV0YdQdmkvShs6YH E3IhfjFaaSNLoHxQy2sLJrL0ow98JQmEG/rAYn7OobVGogngBgf0P0hjgwgt7HOUaI5DdBVJkggR 3HwSktaqWcCtgiHIH7qHV+esW2CnkRJ+9R5cQGsikkWEV/J7leVGs9TV4TvcO5QOOrTHYI+xeCjY JR/m9GPDHv2oSZunUokS2A/WBelnvx6tF6LUJO2FjjlH5zU6Q+Kz/9m69LxvSZVSwiOlGnT1rt/A 77j+WDQZ8x9k2mFJetOle88+lc8sJJ/AeerI+fTlQigTfVqJUiXoKaaC3AqmI+KOnivjMLbvBVFU 1JDruuadNGcPmkgiBTnQXUGUDd6IK9JEQ9yPdM96xZP8bieeMRqTuqbxIbbey2DjVUNzRs1rosFS TsLAdS/0fBGNdTGKhuqD7mUmsFlgGjN2eSj1tM3GnjfXwwCmzjhMbR4rLZXXk+Z/6Hp7Pn2+kJ49 jfgLHgI4Jg== """.decode("base64").decode("zlib") my code: import zlib print 'dsss'.decode('base64').decode('zlib')#error Traceback (most recent call last): File "D:\zjm_code\b.py", line 4, in <module> print 'dsss'.decode('base64').decode('zlib') File "D:\Python25\lib\encodings\zlib_codec.py", line 43, in zlib_decode output = zlib.decompress(input) zlib.error: Error -3 while decompressing data: unknown compression method a='dsss'.encode('zlib') print a a.encode('base64') print a a.decode('base64')#error print a a.decode('zlib') print a x\x9cK)..Traceback (most recent call last): File "D:\zjm_code\b.py", line 7, in <module> a.decode('base64') File "D:\Python25\lib\encodings\base64_codec.py", line 42, in base64_decode output = base64.decodestring(input) File "D:\Python25\lib\base64.py", line 321, in decodestring return binascii.a2b_base64(s) binascii.Error: Incorrect padding a='dsss' a=a.encode('zlib') print a a=a.decode('zlib') print a#why can't print 'dsss' x\x9cK).. a='dsss' a=a.encode('zlib') #print a a=a.decode('zlib') print a#its ok i think the 'print a' encode the a with 'uhf-8'. so: #encoding:utf-8 a='dsss' a=a.encode('zlib') print a a=a.decode('utf-8')#but error. a=a.decode('zlib') print a# x\x9cK)..Traceback (most recent call last): File "D:\zjm_code\b.py", line 5, in <module> a=a.decode('utf-8') File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte
[ "The data in the strings is encoded and compressed binary data. The .decode(\"base64\").decode(\"zlib\") unencodes and decompresses it.\nThe error you got was because 'dsss' decoded from base64 is not valid zlib compressed data.\n", "What is the purpose of x.decode(”base64”).decode(”zlib”) for x in (\"sss\", \"dsss\", random_garbage)? Excuse me, you should know; you are the one who is doing it!\nEdit after OP's addition of various puzzles\nPuzzle 1\na='dsss'.encode('zlib')\nprint a\na.encode('base64')\nprint a\na.decode('base64')#error\nprint a\na.decode('zlib')\nprint a\n\nResolution: all 3 statements of the form\na.XXcode('encoding')\nshould be\na = a.XXcode('encoding')\nPuzzle 2\na='dsss'\na=a.encode('zlib')\nprint a\na=a.decode('zlib')\nprint a#why can't print 'dsss'\n\nx\\x9cK)..\n\nBut it does print 'dsss':\n>>> a='dsss'\n>>> a=a.encode('zlib')\n>>> print a\nx£K)..♠ ♦F☺¥\n>>> a=a.decode('zlib')\n>>> print a#why can't print 'dsss'\ndsss\n>>>\n\nPuzzle 3\n\"\"\"i think the 'print a' encode the a with 'uhf-8'.\"\"\"\nResolution: You think extremely incorrectly. What follows the print is an expression. There are no such side effects. What do you imagine happens when you do this:\nprint 'start text ' + a + 'end text'\n\n?\nWhat do you imagine happens if you do print a twice? Encoding the already-encoded text again? Why don't you stop imagining and try it out?\nIn any case, note that the output of str.encode('zlib') is an str object, not a unicode object:\n>>> print repr('dsss'.encode('zlib'))\n'x\\x9cK)..\\x06\\x00\\x04F\\x01\\xbe'\n\nGetting from that to UTF-8 is going to be somewhat difficult ... it would have to be decoded into unicode first -- with what codec? ascii and utf8 are going to have trouble with the '\\x9c' and the '\\xbe' ...\n", ".decode('base64') can be called only on a string that's encoded as \"base-64, in order to retrieve the byte sequence that was there encoded. Presumably that byte sequence, in the example you bring, was zlib-compressed, and so the .decode('zlib') part decompresses it.\nNow, for your case:\n>>> 'dsss'.decode('base64')\n'v\\xcb,'\n\nBut 'v\\xcv,' is not a zlib-compressed string! And so of course you cannot ask zlib to \"decompress\" it. Fortunately zlib recognizes the fact (that 'v\\xcv,' could not possibly have been produced by applying any of the compression algorithms zlib knows about to any input whatsoever) and so gives you a helpful error message (instead of a random-ish string of bytes, which you might well have gotten if you had randomly supplied a different but equally crazy input string!-)\nEdit: the error in\na.encode('base64')\nprint a\na.decode('base64')#error\n\nis obviously due to the fact that strings are immutable: just calling a.encode (or any other method) does not alter a, it produces a new string object (and here you're just printing it).\nIn the next snippet, the error is only in the OP's mind:\n>>> a='dsss'\n>>> a=a.encode('zlib')\n>>> print a\nx?K)..F?\n>>> a=a.decode('zlib')\n>>> print a#why can't print 'dsss'\ndsss\n>>> \n\nthat \"why can't print\" question is truly peculiar, applied to code that does print 'dsss'. Finally, \n\ni think the 'print a' encode the a\n with 'uhf-8'.\n\nYou think wrongly: there's no such thing as \"uhf-8\" (you mean \"utf-8\" maybe?), and anyway print a does not alter a, any more than just calling a.encode does.\n", "It is the reverse of:\noriginal_message.encode('zlib').encode('base64')\n\nzlib is a binary compression algorithm. base64 is a text encoding of binary data, which is useful to send binary message through text protocols like SMTP.\nAfter 'dsss' was decoded from base64 (the three bytes 76h, CBh, 2Ch), the result was not valid zlib compressed data so it couldn't be decoded.\nTry printing ACTIVATE_THIS to see the result of the decoding. It turns out to be some Python code.\n" ]
[ 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002035727_python.txt
Q: Good interview questions for a Python/TurboGears web developer? If you were looking to hire a web developer who would primarily be working with TurboGears/Python - what sort of questions should you ask them? A: In addition to the good suggestions in the other answers, something I always like to ask (from anybody who's a candidate to develop anything at all that's related to the web) is: "when a user types www.foo.com on their browser's address bar and hits return, what happens then? Please describe in as much or as little detail as you think best, then we may drill down into some or all parts of the answer". Quite apart from the server-side framework(s) in use, this can tell me a lot about the candidate's understanding of other crucial technologies that they may well end up having to deal with: HTTP and the whole TCP/IP stack below it, DNS, caches of many and sundry sorts (and how they can sometimes be a bother and what can you, the developer, try to do about that...), surface-visible aspects of browser technologies, cookies, HTML and CSS and perhaps some Javascript, ... Yes, everyday technologies we use, such as frameworks, try hard to abstract away from all this (and increase productivity thereby), but Joel Spolsky's Law of Leaky Abstractions applies -- being aware of layers of the stack that you're normally abstracting away from is crucial to real mastery of the software craft. Depending on the details of the position the candidate's interviewing for, deeper drill downs will be appropriate in different areas. For example, describing (at reasonable abstraction level) how the HTTP request would get (through a web server and Turbogears machinery, perhaps by way of WSGI) to your application code, roughly how your code would study the request and prepare a response, how the response would be packaged up and sent back to the requesting browser, may all be items of interest -- depending on what kind of frontend/UI responsibilities the developer in question might have, more about the way the browser will deal with various aspects of the response (including links to style sheets, scripts, images, ...) might also be appropriate. Anybody can "cram" about a specific technology such as a framework, enough, if they're smart enough, to "ace" a "quiz"-style interview. But anybody who's able to ace a more open-ended, discursive interview such as this one, is overwhelmingly likely to have really mastered and understood many of the layers of the relevant stack of technologies and abstractions -- I'd much rather hire somebody with such a thorough, deep-rooted understanding, even if they've never used Turbogears (but rather, say, Django, Wekrzeug and web.py) [they'll be able to cram and get the Turbogears-specific details down pat in a week, tops], than somebody who's committed to memory a stack of Turbogears reference manuals but doesn't really understand HTTP, cookies, TCP/IP... (that lack would take, at least, many months to remedy). A: The best interview questions are the ones where you ask them to solve problems. Here are a few semi-random suggestions (after the FizzBizz test) Python Give them a non-trivial project to implement over a week in the domain where you're working. I applied once to a search firm and they asked me to implement a collaborative filtering system. The areas that are usually confusing are decorators, the type system, metaclasses, perhaps iterators. You could ask them something about these things to probe their depth. TurboGears I Can't suggest much here but you could quiz them on the ORM of their choice (construct some mappers and queries), ask a little bit about validation (I had some trouble getting conditional validation to work with FormEncode). You could also wander a little into how they'd test the app, make sure that it scaled, test it's performance and deploy it. A: Ask him for: Instrospection Model-View-Control design Documenting tools If he know a lot about that, surely know a lot about other issues. A: Don't quiz. Get some real (possibly broken) code from you vcs. Get them to tell you how they would fix it / add a feature. If they can, ask them to bring some samples of previous work.
Good interview questions for a Python/TurboGears web developer?
If you were looking to hire a web developer who would primarily be working with TurboGears/Python - what sort of questions should you ask them?
[ "In addition to the good suggestions in the other answers, something I always like to ask (from anybody who's a candidate to develop anything at all that's related to the web) is: \"when a user types www.foo.com on their browser's address bar and hits return, what happens then? Please describe in as much or as little detail as you think best, then we may drill down into some or all parts of the answer\".\nQuite apart from the server-side framework(s) in use, this can tell me a lot about the candidate's understanding of other crucial technologies that they may well end up having to deal with: HTTP and the whole TCP/IP stack below it, DNS, caches of many and sundry sorts (and how they can sometimes be a bother and what can you, the developer, try to do about that...), surface-visible aspects of browser technologies, cookies, HTML and CSS and perhaps some Javascript, ...\nYes, everyday technologies we use, such as frameworks, try hard to abstract away from all this (and increase productivity thereby), but Joel Spolsky's Law of Leaky Abstractions applies -- being aware of layers of the stack that you're normally abstracting away from is crucial to real mastery of the software craft.\nDepending on the details of the position the candidate's interviewing for, deeper drill downs will be appropriate in different areas. For example, describing (at reasonable abstraction level) how the HTTP request would get (through a web server and Turbogears machinery, perhaps by way of WSGI) to your application code, roughly how your code would study the request and prepare a response, how the response would be packaged up and sent back to the requesting browser, may all be items of interest -- depending on what kind of frontend/UI responsibilities the developer in question might have, more about the way the browser will deal with various aspects of the response (including links to style sheets, scripts, images, ...) might also be appropriate.\nAnybody can \"cram\" about a specific technology such as a framework, enough, if they're smart enough, to \"ace\" a \"quiz\"-style interview. But anybody who's able to ace a more open-ended, discursive interview such as this one, is overwhelmingly likely to have really mastered and understood many of the layers of the relevant stack of technologies and abstractions -- I'd much rather hire somebody with such a thorough, deep-rooted understanding, even if they've never used Turbogears (but rather, say, Django, Wekrzeug and web.py) [they'll be able to cram and get the Turbogears-specific details down pat in a week, tops], than somebody who's committed to memory a stack of Turbogears reference manuals but doesn't really understand HTTP, cookies, TCP/IP... (that lack would take, at least, many months to remedy).\n", "The best interview questions are the ones where you ask them to solve problems.\nHere are a few semi-random suggestions (after the FizzBizz test)\nPython\nGive them a non-trivial project to implement over a week in the domain where you're working. I applied once to a search firm and they asked me to implement a collaborative filtering system. \nThe areas that are usually confusing are decorators, the type system, metaclasses, perhaps iterators. You could ask them something about these things to probe their depth.\nTurboGears\nI Can't suggest much here but you could quiz them on the ORM of their choice (construct some mappers and queries), ask a little bit about validation (I had some trouble getting conditional validation to work with FormEncode). You could also wander a little into how they'd test the app, make sure that it scaled, test it's performance and deploy it. \n", "Ask him for:\n\nInstrospection\nModel-View-Control design\nDocumenting tools\n\nIf he know a lot about that, surely know a lot about other issues.\n", "Don't quiz. Get some real (possibly broken) code from you vcs. Get them to tell you how they would fix it / add a feature.\nIf they can, ask them to bring some samples of previous work.\n" ]
[ 15, 2, 1, 1 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0002034128_python_turbogears.txt
Q: Python: Decorators: How does the following code work? Are the comments in the following code correct? Particularly the "instance =..." one? # This does nothing. class donothing(object): def __init__(self, func): """ The 'func' argument is the function being decorated because in this case, we're not instantiating the decorator class. Instead we are just using the class object as a callable (a class is always callable as this is how an instance is returned) to use as a decorator, which means that it is being instantiated upon definition of the decorated function and the decorated function is being passed in as an argument to the class's __init__ method. """ self.func = func def __call__(self, *args, **kwargs): """ The __call__ function is called when the decorated function is called because the function has be eaten by the decorator class. Now it's up to the this method to return a call to the original function. The arguments are passed in as args, kwargs to be manipulated. """ # Returns original function call with original arguments. return self.func(*args, **kwargs) @donothing def printer(text): print(text) printer('hello world') # The printer function is now an alias for the donothing instance created, so # the preceding was the same as: # # instance = donothing(printer) # instance('hello world') # # Next example: class checkforkeysinparams(object): def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise TypeError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper # Apply decorator class, passing in the __init__'s 'required' argument. @checkforkeysinparams(['name', 'pass', 'code']) def complex_function(params): # Obviously these three are needed or a KeyError will be raised. print(params['name']) print(params['pass']) print(params['code']) # Create params to pass in. Note, I've commented out one of the required params. params = { 'name': 'John Doe', 'pass': 'OpenSesame', #'code': '1134', } # This call will output: TypeError: Missing from "params" argument: code complex_function(params=params) A: Yes perfect description, decorator donothing decorates the function printer and returns a object of class donothing, so yes decorator simply boils down to this x = donothing(func) # donothing is a class not function and you can use it like this, if you wish to avoid @deco syntax. so now x is an object, when you do x(), __call__ of that object is called and there it calls the function which was passed in __init__ edit: Second decorator is wrong , because it only checks the parameter but never calls the function being passed and function being passed to decorator is names params but should be name something like func or better name you can test that it does nothing by passing correct params params = { 'name': 'John Doe', 'pass': 'OpenSesame', 'code': '1134', } complex_function(params=params) it doesn't print the arguments as complex_function is supposed to do. so correct decorator is class checkforkeysinparams(object): def __init__(self, required): self.required = set(required) def __call__(self, func): def wrapper(params): missing = self.required.difference(params) if missing: raise TypeError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) func(params) return wrapper In first example Class is being used as decorator itself, here the object of class checkforkeysinparams is used as deocrator hence function gets passed to __call__ of that object
Python: Decorators: How does the following code work?
Are the comments in the following code correct? Particularly the "instance =..." one? # This does nothing. class donothing(object): def __init__(self, func): """ The 'func' argument is the function being decorated because in this case, we're not instantiating the decorator class. Instead we are just using the class object as a callable (a class is always callable as this is how an instance is returned) to use as a decorator, which means that it is being instantiated upon definition of the decorated function and the decorated function is being passed in as an argument to the class's __init__ method. """ self.func = func def __call__(self, *args, **kwargs): """ The __call__ function is called when the decorated function is called because the function has be eaten by the decorator class. Now it's up to the this method to return a call to the original function. The arguments are passed in as args, kwargs to be manipulated. """ # Returns original function call with original arguments. return self.func(*args, **kwargs) @donothing def printer(text): print(text) printer('hello world') # The printer function is now an alias for the donothing instance created, so # the preceding was the same as: # # instance = donothing(printer) # instance('hello world') # # Next example: class checkforkeysinparams(object): def __init__(self, required): self.required = set(required) def __call__(self, params): def wrapper(params): missing = self.required.difference(params) if missing: raise TypeError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) return wrapper # Apply decorator class, passing in the __init__'s 'required' argument. @checkforkeysinparams(['name', 'pass', 'code']) def complex_function(params): # Obviously these three are needed or a KeyError will be raised. print(params['name']) print(params['pass']) print(params['code']) # Create params to pass in. Note, I've commented out one of the required params. params = { 'name': 'John Doe', 'pass': 'OpenSesame', #'code': '1134', } # This call will output: TypeError: Missing from "params" argument: code complex_function(params=params)
[ "Yes perfect description, decorator donothing decorates the function printer and returns a object of class donothing, so yes decorator simply boils down to this \nx = donothing(func) # donothing is a class not function\n\nand you can use it like this, if you wish to avoid @deco syntax.\nso now x is an object, when you do x(), __call__ of that object is called and there it calls the function which was passed in __init__\nedit:\nSecond decorator is wrong , because it only checks the parameter but never calls the function being passed\nand function being passed to decorator is names params but should be name something like func or better name\nyou can test that it does nothing by passing correct params\nparams = {\n 'name': 'John Doe',\n 'pass': 'OpenSesame',\n 'code': '1134',\n}\ncomplex_function(params=params)\n\nit doesn't print the arguments as complex_function is supposed to do.\nso correct decorator is \nclass checkforkeysinparams(object):\n def __init__(self, required):\n self.required = set(required)\n\n def __call__(self, func):\n def wrapper(params):\n missing = self.required.difference(params)\n if missing:\n raise TypeError('Missing from \"params\" argument: %s' % ', '.join(sorted(missing)))\n\n func(params)\n\n return wrapper\n\nIn first example Class is being used as decorator itself, here the object of class checkforkeysinparams is used as deocrator\nhence function gets passed to __call__ of that object\n" ]
[ 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002036288_decorator_python.txt
Q: Model sys's python implementation pypy has many built-in function use python implementation.example:link but,i can't find model 'sys' implementation. how can i get it. import sys print help(sys) A: The sys module is implemented in C: http://svn.python.org/view/python/trunk/Python/sysmodule.c?view=markup There is no Python source for it, because it's entirely operating system interfaces that cannot be implemented in pure Python. A: Abstraction can only be taken so far, Python strives to be a system/platform independent language and the sys module being what it is has to be platform specific and cannot be implemented in pure python.
Model sys's python implementation
pypy has many built-in function use python implementation.example:link but,i can't find model 'sys' implementation. how can i get it. import sys print help(sys)
[ "The sys module is implemented in C: http://svn.python.org/view/python/trunk/Python/sysmodule.c?view=markup\nThere is no Python source for it, because it's entirely operating system interfaces that cannot be implemented in pure Python.\n", "Abstraction can only be taken so far, Python strives to be a system/platform independent language and the sys module being what it is has to be platform specific and cannot be implemented in pure python.\n" ]
[ 2, 0 ]
[]
[]
[ "model", "pypy", "python" ]
stackoverflow_0002036392_model_pypy_python.txt
Q: Resource scheduling application I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on a job site. We assume the conference room cannot be scheduled for two meetings at once and a worker cannot be on two job sites at the same time. The business logic of the application must not allow a user to "overbook" a resource. What I can't figure out is how to represent the data so that if two or more users operate on the schedule at the same time, and there are conflicts, one of the updates will abort. The only solution I've seen so far is to track time slots for each exclusionary resource. So if the conference room is used on 5 min intervals, and it was scheduled for 9-9:30am, then the corresponding 5 minute time slots for 9-9:30am would all return TRUE, while the unscheduled slots would return FALSE or NULL. The DB transaction would then pull the conference room object out of the store, check all the time slots, and abort if the update conflicted with existing time slots. However, this seems like it will get really big, really fast. Perhaps it could be garbage collected? Also, one of the goals of the design is to support variable granularity, so some objects will get scheduled on a minute to minute basis while others could be on a day to day basis, and this data design does not support that very well. Currently, I am trying to implement this on Google App Engine using Python, but I would be really interested to see some more general solutions to this problem. All I've come up with Googling is scheduling recurring tasks, or algorithms that perform one time operations to automatically build optimized schedules. A: You'll want to track just start and end times for each exclusionary resource. The data storage in your problem is actually the easy part - the hard(er) part is crafting queries to look for conflicts in time intervals. If my logic is correct after being up for 21 hours, the following psuedo-code should check for meeting conflicts. # Set up your proposed meeting proposed.start = <thursday, 1pm> proposed.end = <thursday, 2pm> # Look for meetings that intersect with or straddle proposed meeting conflicts = <SELECT * FROM meeting WHERE meeting.start BETWEEN proposed.start AND proposed.end OR meeting.end BETWEEN proposed.start AND proposed.end OR meeting.start <= proposed.start AND meeting.end >= proposed.end> if conflicts.length > 0: # We have a conflict! A: To automatically optimize a timetable of a school or university (or even other problems) take a look at the following Java tools: TimeFinder, UniTime or Drools Solver The problem with user interaction is not as easiely solved as you explained I think, because there could be other constraint violations as well (timetabling can get a lot more complicated). First, I would only allow timetablers accessing/changing the timetable data. Second, I would create an independent solution for each timetabler and then optimize this solution with the proposed tools above. The solutions then can be stored to the database and the timetabler could use them to further optimize the schedule or to compare to other solutions.
Resource scheduling application
I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on a job site. We assume the conference room cannot be scheduled for two meetings at once and a worker cannot be on two job sites at the same time. The business logic of the application must not allow a user to "overbook" a resource. What I can't figure out is how to represent the data so that if two or more users operate on the schedule at the same time, and there are conflicts, one of the updates will abort. The only solution I've seen so far is to track time slots for each exclusionary resource. So if the conference room is used on 5 min intervals, and it was scheduled for 9-9:30am, then the corresponding 5 minute time slots for 9-9:30am would all return TRUE, while the unscheduled slots would return FALSE or NULL. The DB transaction would then pull the conference room object out of the store, check all the time slots, and abort if the update conflicted with existing time slots. However, this seems like it will get really big, really fast. Perhaps it could be garbage collected? Also, one of the goals of the design is to support variable granularity, so some objects will get scheduled on a minute to minute basis while others could be on a day to day basis, and this data design does not support that very well. Currently, I am trying to implement this on Google App Engine using Python, but I would be really interested to see some more general solutions to this problem. All I've come up with Googling is scheduling recurring tasks, or algorithms that perform one time operations to automatically build optimized schedules.
[ "You'll want to track just start and end times for each exclusionary resource. The data storage in your problem is actually the easy part - the hard(er) part is crafting queries to look for conflicts in time intervals.\nIf my logic is correct after being up for 21 hours, the following psuedo-code should check for meeting conflicts.\n# Set up your proposed meeting\nproposed.start = <thursday, 1pm>\nproposed.end = <thursday, 2pm>\n\n# Look for meetings that intersect with or straddle proposed meeting\nconflicts = <SELECT * FROM meeting WHERE\n meeting.start BETWEEN proposed.start AND proposed.end OR\n meeting.end BETWEEN proposed.start AND proposed.end OR\n meeting.start <= proposed.start AND meeting.end >= proposed.end>\n\n\nif conflicts.length > 0:\n # We have a conflict!\n\n", "To automatically optimize a timetable of a school or university (or even other problems) take a look at the following Java tools: \nTimeFinder, UniTime or Drools Solver\nThe problem with user interaction is not as easiely solved as you explained I think, because there could be other constraint violations as well (timetabling can get a lot more complicated).\nFirst, I would only allow timetablers accessing/changing the timetable data.\nSecond, I would create an independent solution for each timetabler and then optimize this solution with the proposed tools above. The solutions then can be stored to the database and the timetabler could use them to further optimize the schedule or to compare to other solutions.\n" ]
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python", "resources", "schedule", "scheduling" ]
stackoverflow_0001535391_google_app_engine_python_resources_schedule_scheduling.txt
Q: I just installed QT for Windows but I can't find the control toolbox anywhere. Where do I drag controls to a form? I opened a starter application to see how it works but I only see C++ files, nothing in Python. How can I configure QT to work for Python? :S Also, where can I find the visual form? A: For python support see PyQt. I'm not quite sure what you mean by "visual form". If you want a GUI editor try qtcreator A: Qt comes with Qt Designer which you can use to create forms visually (like in Visual Studio). Designer creates XML ".ui" files that are then fed into Qt's UIC tool. That tool then generates C++ header files that define a class with the UI components. This page describes how you can use the UI generated code in your application. PyQt also provides ways to generate Python code from the ".ui" files. Have a look at Designer's online manual, but you should take a look at the examples files too. Qt Creator has the Designer embedded, but it will be difficult to use that one with PyQt.
I just installed QT for Windows but I can't find the control toolbox anywhere. Where do I drag controls to a form?
I opened a starter application to see how it works but I only see C++ files, nothing in Python. How can I configure QT to work for Python? :S Also, where can I find the visual form?
[ "For python support see PyQt.\nI'm not quite sure what you mean by \"visual form\". If you want a GUI editor try qtcreator \n", "Qt comes with Qt Designer which you can use to create forms visually (like in Visual Studio). Designer creates XML \".ui\" files that are then fed into Qt's UIC tool. That tool then generates C++ header files that define a class with the UI components. This page describes how you can use the UI generated code in your application. PyQt also provides ways to generate Python code from the \".ui\" files.\nHave a look at Designer's online manual, but you should take a look at the examples files too. \nQt Creator has the Designer embedded, but it will be difficult to use that one with PyQt.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "qt", "qt4" ]
stackoverflow_0002035459_python_qt_qt4.txt
Q: How to get started building a Mac application I am a Python/web programmer. Now, I would like to transition to building applications for the Mac. Please tell me--what do I have to learn to get started? What books would you recommend? A: Assuming that you included the "python" tag after considering that it will be interpreted as applying to the question and not the questioner, you must be interested in writing Python applications for the Mac, right? After all, you didn't include "web" as one of the tags too. If that's true, I'm not sure what more you need to know already, other than perhaps picking a GUI framework, if you want to write GUI applications. I use wxPython quite successfully for applications which run on OS X (and Windows). Very few Mac-specific issues have cropped up to cause trouble, primarily because both Python and wxPython are remarkably cross-platform. The few that have come up are by and large documented and have known workarounds, or the resolution is fairly simple to find. I've needed no books on the subject, and really know very little about Macs. It really hasn't been a problem so far. A: The programming language of choice for building OS X gui applications is Objective-C with Cocoa, I would recommend that you check out some books on that. There are python bindings for Cocoa but they are not optimal. You should check out previous questions looking for books on Obj-C and Cocoa.
How to get started building a Mac application
I am a Python/web programmer. Now, I would like to transition to building applications for the Mac. Please tell me--what do I have to learn to get started? What books would you recommend?
[ "Assuming that you included the \"python\" tag after considering that it will be interpreted as applying to the question and not the questioner, you must be interested in writing Python applications for the Mac, right? After all, you didn't include \"web\" as one of the tags too.\nIf that's true, I'm not sure what more you need to know already, other than perhaps picking a GUI framework, if you want to write GUI applications.\nI use wxPython quite successfully for applications which run on OS X (and Windows). Very few Mac-specific issues have cropped up to cause trouble, primarily because both Python and wxPython are remarkably cross-platform. The few that have come up are by and large documented and have known workarounds, or the resolution is fairly simple to find.\nI've needed no books on the subject, and really know very little about Macs. It really hasn't been a problem so far.\n", "The programming language of choice for building OS X gui applications is Objective-C with Cocoa, I would recommend that you check out some books on that. There are python bindings for Cocoa but they are not optimal.\nYou should check out previous questions looking for books on Obj-C and Cocoa.\n" ]
[ 3, 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002036844_macos_python.txt
Q: What are the tradeoffs of reusing a cursor vs. creating a new cursor? In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries. def getSomeData(curs): # case 1: pass in a cursor, which is generally curs.execute('select ...') # reused across queries return curs.fetchall() def getSomeData(conn): # case 2: pass in a connection,allocate curs=conn.cursor() # a cursor for this query curs.execute('select ...') return curs.fetchall() Of course, both approaches return the same data. What are the tradeoffs between the two approaches? Is one particularly more or less efficient? Are there any potential pitfalls to reusing a cursor over many queries? A: You can re-use a cx_Oracle cursor as much as you like, no problem. If you're executing thousands of small queries in a small space of time, you might see a slight performance improvement by re-using the cursor, but I doubt it. I will sometimes create new cursors, and other times re-use an existing one, depending on whether it makes the code easier to read and understand. For example, if I have a variety of procedures that need to access the database, I might pass an Oracle connection object around, or a cursor created on that connection. Whatever makes your code more readable and easier to maintain is what I'd go for.
What are the tradeoffs of reusing a cursor vs. creating a new cursor?
In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries. def getSomeData(curs): # case 1: pass in a cursor, which is generally curs.execute('select ...') # reused across queries return curs.fetchall() def getSomeData(conn): # case 2: pass in a connection,allocate curs=conn.cursor() # a cursor for this query curs.execute('select ...') return curs.fetchall() Of course, both approaches return the same data. What are the tradeoffs between the two approaches? Is one particularly more or less efficient? Are there any potential pitfalls to reusing a cursor over many queries?
[ "You can re-use a cx_Oracle cursor as much as you like, no problem. If you're executing thousands of small queries in a small space of time, you might see a slight performance improvement by re-using the cursor, but I doubt it.\nI will sometimes create new cursors, and other times re-use an existing one, depending on whether it makes the code easier to read and understand.\nFor example, if I have a variety of procedures that need to access the database, I might pass an Oracle connection object around, or a cursor created on that connection.\nWhatever makes your code more readable and easier to maintain is what I'd go for.\n" ]
[ 11 ]
[]
[]
[ "cx_oracle", "database", "oracle", "python", "sql" ]
stackoverflow_0002035212_cx_oracle_database_oracle_python_sql.txt
Q: PIP complains when I try to install a module into another virtualenv I have a module installed in the main python install, however, I'd like to install this module into my virtualenv and I'd like it to be portable, how can I do that? I'm getting this error: (v_env)[nubela@nubela-desktop zine-ified]$ pip -E v_env install pyfacebook Requirement already satisfied (use --upgrade to upgrade): pyfacebook in /home/nubela/... A: To force pip installing a package when it's already been detected, you need to use the -I or --ignore-installed flag. In your case, the command would be: pip -E v_env install -I pyfacebook pip will then install it into your virtualenv.
PIP complains when I try to install a module into another virtualenv
I have a module installed in the main python install, however, I'd like to install this module into my virtualenv and I'd like it to be portable, how can I do that? I'm getting this error: (v_env)[nubela@nubela-desktop zine-ified]$ pip -E v_env install pyfacebook Requirement already satisfied (use --upgrade to upgrade): pyfacebook in /home/nubela/...
[ "To force pip installing a package when it's already been detected, you need to use the -I or --ignore-installed flag. In your case, the command would be:\npip -E v_env install -I pyfacebook\n\npip will then install it into your virtualenv.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002036462_python.txt
Q: How to do related questions autopopulate I want to get a related [things/questions] in my app, similar to what StackOverflow does, when you tab out of the Title field. I can think of only one way to do it, which i think might be fast enough Do a search for the title in corpus of titles of all [things], and return first x matches. We can use whatever search is being used for site search. What are other ways o do this, which are fast enough, as this is going to be sent on tabout, so a large server side processing is not feasible for it. I am just looking for the way to do this, but I am using mysql and DJango, so if your answer uses that, all the better. [I cannot think of good tags for it, so please feel free to edit them] A: You're looking at a content-based recommendation algorithm. AFAICT StackOverflow's looks at the tags and the words in the title, and finds questions that share some of these. It can be implemented as a nearest neighbour search in a space where documents are represented as TF-IDF vectors. Implementation-wise, go with any Django search engine that supports stemming, stopwords, non-strict matches, and tf-idf weights. Algorithmic complexity isn't high (just a few index lookups), so it doesn't matter if it's written in Python. If you don't find a search engine doing what you want, leave the stemming and stopwords to the search engine, call the search engine on individual words, and do your own tf-idf scoring with a score that favors similar tags.
How to do related questions autopopulate
I want to get a related [things/questions] in my app, similar to what StackOverflow does, when you tab out of the Title field. I can think of only one way to do it, which i think might be fast enough Do a search for the title in corpus of titles of all [things], and return first x matches. We can use whatever search is being used for site search. What are other ways o do this, which are fast enough, as this is going to be sent on tabout, so a large server side processing is not feasible for it. I am just looking for the way to do this, but I am using mysql and DJango, so if your answer uses that, all the better. [I cannot think of good tags for it, so please feel free to edit them]
[ "You're looking at a content-based recommendation algorithm. AFAICT StackOverflow's looks at the tags and the words in the title, and finds questions that share some of these. It can be implemented as a nearest neighbour search in a space where documents are represented as TF-IDF vectors.\nImplementation-wise, go with any Django search engine that supports stemming, stopwords, non-strict matches, and tf-idf weights. Algorithmic complexity isn't high (just a few index lookups), so it doesn't matter if it's written in Python.\nIf you don't find a search engine doing what you want, leave the stemming and stopwords to the search engine, call the search engine on individual words, and do your own tf-idf scoring with a score that favors similar tags.\n" ]
[ 1 ]
[]
[]
[ "algorithm", "django", "information_retrieval", "python" ]
stackoverflow_0002036688_algorithm_django_information_retrieval_python.txt
Q: Different results from yield vs return I don't really understand how yield statement works in this situation. The problem says that given an expression without parentheses, write a function to generate all possible fully parenthesized (FP) expressions. Say, the input is '1+2+3+4' which should be generated to 5 FP expressions: (1+(2+(3+4))) (1+((2+3)+4)) ((1+2)+(3+4)) ((1+(2+3))+4) (((1+2)+3)+4) My code is as follows. OPS = ('+', '-', '*', '/') def f(expr): """ Generates FP exprs Recursive formula: f(expr1[op]expr2) = (f(expr1) [op] f(expr2)) """ if expr.isdigit(): yield expr # return [expr] # ret = [] first = '' i = 0 while i < len(expr): if expr[i] not in OPS: first += expr[i] i += 1 else: op = expr[i] i += 1 second = expr[i:] firstG, secondG = f(first), f(second) for e in ('(' + e1 + op + e2 + ')' for e1 in firstG for e2 in secondG): yield e # ret.append(e) first += op # return ret If I use return statement (the commented out lines), then the code works as expected. However, when I change to yield statement as the code shows, I only get the first 4 results. If the number of operands of the input expression is increased, then of course more results will be lost. For example, for the input '1+2+3+4+5', I only get 8 instead of 14. I finally figure out the way to make the code work by commenting out the line firstG, secondG = f(first), f(second) and replace the line for e in ('(' + e1 + op + e2 + ')' for e1 in firstG for e2 in secondG): by for e in ('(' + e1 + op + e2 + ')' for e1 in f(first) for e2 in f(second)): That means some 'information' of the generator is lost because of the line firstG, secondG = f(first), f(second) but I can't figure out the real reason. Could you guys give me some ideas? A: The problem is you're iterating over generators instead of lists in the yield version, specifically secondG which is exhausted after one loop. Change the line to this and it works: firstG, secondG = f(first), list(f(second)) Or, you can change your loop: for e in ("(%s%s%s)" % (e1, op, e2) for e1 in f(first) for e2 in f(second)): # new generator object every loop ^^^^^^^^^ The non-yield version works because you return lists, which can be iterated over again, unlike generators. Also note you only iterate over firstG once, so it's not affected. Remember that this: r = [v for a in A for b in B] Is equivalent to: r = [] for a in A: for b in B: r.append(v) Which more clearly shows the repeated loop over B. Another example: def y(): yield 1 yield 2 yield 3 def r(): return [1, 2, 3] vy = y() for v in vy: print v for v in vy: print v print "---" vr = r() for v in vr: print v for v in vr: print v
Different results from yield vs return
I don't really understand how yield statement works in this situation. The problem says that given an expression without parentheses, write a function to generate all possible fully parenthesized (FP) expressions. Say, the input is '1+2+3+4' which should be generated to 5 FP expressions: (1+(2+(3+4))) (1+((2+3)+4)) ((1+2)+(3+4)) ((1+(2+3))+4) (((1+2)+3)+4) My code is as follows. OPS = ('+', '-', '*', '/') def f(expr): """ Generates FP exprs Recursive formula: f(expr1[op]expr2) = (f(expr1) [op] f(expr2)) """ if expr.isdigit(): yield expr # return [expr] # ret = [] first = '' i = 0 while i < len(expr): if expr[i] not in OPS: first += expr[i] i += 1 else: op = expr[i] i += 1 second = expr[i:] firstG, secondG = f(first), f(second) for e in ('(' + e1 + op + e2 + ')' for e1 in firstG for e2 in secondG): yield e # ret.append(e) first += op # return ret If I use return statement (the commented out lines), then the code works as expected. However, when I change to yield statement as the code shows, I only get the first 4 results. If the number of operands of the input expression is increased, then of course more results will be lost. For example, for the input '1+2+3+4+5', I only get 8 instead of 14. I finally figure out the way to make the code work by commenting out the line firstG, secondG = f(first), f(second) and replace the line for e in ('(' + e1 + op + e2 + ')' for e1 in firstG for e2 in secondG): by for e in ('(' + e1 + op + e2 + ')' for e1 in f(first) for e2 in f(second)): That means some 'information' of the generator is lost because of the line firstG, secondG = f(first), f(second) but I can't figure out the real reason. Could you guys give me some ideas?
[ "The problem is you're iterating over generators instead of lists in the yield version, specifically secondG which is exhausted after one loop. Change the line to this and it works:\nfirstG, secondG = f(first), list(f(second))\n\nOr, you can change your loop:\nfor e in (\"(%s%s%s)\" % (e1, op, e2) for e1 in f(first) for e2 in f(second)):\n# new generator object every loop ^^^^^^^^^\n\nThe non-yield version works because you return lists, which can be iterated over again, unlike generators. Also note you only iterate over firstG once, so it's not affected.\nRemember that this:\nr = [v for a in A for b in B]\n\nIs equivalent to:\nr = []\nfor a in A:\n for b in B:\n r.append(v)\n\nWhich more clearly shows the repeated loop over B.\nAnother example:\ndef y():\n yield 1\n yield 2\n yield 3\ndef r():\n return [1, 2, 3]\n\nvy = y()\nfor v in vy:\n print v\nfor v in vy:\n print v\n\nprint \"---\"\n\nvr = r()\nfor v in vr:\n print v\nfor v in vr:\n print v\n\n" ]
[ 4 ]
[]
[]
[ "python", "recursion", "yield" ]
stackoverflow_0002037267_python_recursion_yield.txt
Q: Translating function for finding all partitions of a set from Python to Ruby I have the following python function to recursively find all partitions of a set: def partitions(set_): if not set_: yield [] return for i in xrange(2**len(set_)/2): parts = [set(), set()] for item in set_: parts[i&1].add(item) i >>= 1 for b in partitions(parts[1]): yield [parts[0]]+b for p in partitions(["a", "b", "c", "d"]): print(p) Can someone help me to translate this into ruby? This is what I have so far: def partitions(set) if not set yield [] return end (0...2**set.size/2).each { |i| parts = [Set.new, Set.new] set.each { |item| parts[i&1] << item i >>= 1 } partitions(parts[1]).each { |b| yield [parts[0]] << b } } end p partitions([1, 2, 3, 4].to_set) I get the error "LocalJumpError: no block given". I guess this is because the yield functions work differently in Python and Ruby. A: #!/usr/bin/ruby1.8 def partitions(set) yield [] if set.empty? (0 ... 2 ** set.size / 2).each do |i| parts = [[], []] set.each do |item| parts[i & 1] << item i >>= 1 end partitions(parts[1]) do |b| result = [parts[0]] + b result = result.reject do |e| e.empty? end yield result end end end partitions([1, 2, 3, 4]) do |e| p e end # => [[1, 2, 3, 4]] # => [[2, 3, 4], [1]] # => [[1, 3, 4], [2]] # => [[3, 4], [1, 2]] # => [[3, 4], [2], [1]] # => [[1, 2, 4], [3]] # => [[2, 4], [1, 3]] # => [[2, 4], [3], [1]] # => [[1, 4], [2, 3]] # => [[1, 4], [3], [2]] # => [[4], [1, 2, 3]] # => [[4], [2, 3], [1]] # => [[4], [1, 3], [2]] # => [[4], [3], [1, 2]] # => [[4], [3], [2], [1]] What's different: The guard calls set.empty? instead of (implicitly) testing for set.nil? Leave out the .each when calling partitions Use Array instead of Set Filter empty sets out of the yielded result A: You'll have to think of Ruby's yield like a call to a user-defined operation. def twice yield yield end twice { puts "Hello" } So whenever your code yields a value, a processing function for this element will be called. partitions([1, 2, 3, 4].to_set) { |result| # process result } This code doesn't generate a list at all.
Translating function for finding all partitions of a set from Python to Ruby
I have the following python function to recursively find all partitions of a set: def partitions(set_): if not set_: yield [] return for i in xrange(2**len(set_)/2): parts = [set(), set()] for item in set_: parts[i&1].add(item) i >>= 1 for b in partitions(parts[1]): yield [parts[0]]+b for p in partitions(["a", "b", "c", "d"]): print(p) Can someone help me to translate this into ruby? This is what I have so far: def partitions(set) if not set yield [] return end (0...2**set.size/2).each { |i| parts = [Set.new, Set.new] set.each { |item| parts[i&1] << item i >>= 1 } partitions(parts[1]).each { |b| yield [parts[0]] << b } } end p partitions([1, 2, 3, 4].to_set) I get the error "LocalJumpError: no block given". I guess this is because the yield functions work differently in Python and Ruby.
[ "#!/usr/bin/ruby1.8\n\ndef partitions(set)\n yield [] if set.empty?\n (0 ... 2 ** set.size / 2).each do |i|\n parts = [[], []]\n set.each do |item|\n parts[i & 1] << item\n i >>= 1\n end\n partitions(parts[1]) do |b|\n result = [parts[0]] + b\n result = result.reject do |e|\n e.empty?\n end\n yield result\n end\n end\nend\n\npartitions([1, 2, 3, 4]) do |e|\n p e\nend\n\n# => [[1, 2, 3, 4]]\n# => [[2, 3, 4], [1]]\n# => [[1, 3, 4], [2]]\n# => [[3, 4], [1, 2]]\n# => [[3, 4], [2], [1]]\n# => [[1, 2, 4], [3]]\n# => [[2, 4], [1, 3]]\n# => [[2, 4], [3], [1]]\n# => [[1, 4], [2, 3]]\n# => [[1, 4], [3], [2]]\n# => [[4], [1, 2, 3]]\n# => [[4], [2, 3], [1]]\n# => [[4], [1, 3], [2]]\n# => [[4], [3], [1, 2]]\n# => [[4], [3], [2], [1]]\n\nWhat's different:\n\nThe guard calls set.empty? instead of\n(implicitly) testing for set.nil?\nLeave out the .each when calling\npartitions\nUse Array instead of Set\nFilter empty sets out of the yielded\nresult\n\n", "You'll have to think of Ruby's yield like a call to a user-defined operation.\ndef twice\n yield\n yield\nend\n\ntwice { puts \"Hello\" } \n\nSo whenever your code yields a value, a processing function for this element will be called.\npartitions([1, 2, 3, 4].to_set) { |result| \n # process result\n}\n\nThis code doesn't generate a list at all.\n" ]
[ 4, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0002037327_python_ruby.txt
Q: Problem with sqlalchemy, reflected table and defaults for string fields hmm, is there any reason why sa tries to add Nones to for varchar columns that have defaults set in in database schema ?, it doesnt do that for floats or ints (im using reflection). so when i try to add new row : like u = User() u.foo = 'a' u.bar = 'b' sa issues a query that has a lot more cols with None values assigned to those, and db obviously bards and doesnt perform default substitution. A: What version do you use and what is actual code? Below is a sample code showing that server_default parameter works fine for string fields: from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker metadata = MetaData() Base = declarative_base(metadata=metadata) class Item(Base): __tablename__="items" id = Column(String, primary_key=True) int_val = Column(Integer, nullable=False, server_default='123') str_val = Column(String, nullable=False, server_default='abc') engine = create_engine('sqlite://', echo=True) metadata.create_all(engine) session = sessionmaker(engine)() item = Item(id='foo') session.add(item) session.commit() print item.int_val, item.str_val The output is: <...> <...> INSERT INTO items (id) VALUES (?) <...> ['foo'] <...> 123 abc A: I've found its a bug in sa, this happens only for string fields, they dont get server_default property for some unknow reason, filed a ticket for this already
Problem with sqlalchemy, reflected table and defaults for string fields
hmm, is there any reason why sa tries to add Nones to for varchar columns that have defaults set in in database schema ?, it doesnt do that for floats or ints (im using reflection). so when i try to add new row : like u = User() u.foo = 'a' u.bar = 'b' sa issues a query that has a lot more cols with None values assigned to those, and db obviously bards and doesnt perform default substitution.
[ "What version do you use and what is actual code? Below is a sample code showing that server_default parameter works fine for string fields:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata)\n\nclass Item(Base):\n __tablename__=\"items\"\n id = Column(String, primary_key=True)\n int_val = Column(Integer, nullable=False, server_default='123')\n str_val = Column(String, nullable=False, server_default='abc')\n\nengine = create_engine('sqlite://', echo=True)\nmetadata.create_all(engine)\nsession = sessionmaker(engine)()\n\nitem = Item(id='foo')\nsession.add(item)\nsession.commit()\nprint item.int_val, item.str_val\n\nThe output is:\n<...>\n<...> INSERT INTO items (id) VALUES (?)\n<...> ['foo']\n<...>\n123 abc\n\n", "I've found its a bug in sa, this happens only for string fields, they dont get server_default property for some unknow reason, filed a ticket for this already\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002036996_python_sqlalchemy.txt
Q: How to create Form from a Model which has a ListProperty I am currently using Django forms with the Google App Engine and I have a model which is as follows: class Menu(db.Model): name = db.StringProperty(required=True) is_special = db.BooleanProperty() menu_items = db.ListProperty(MenuItem) I have a MenuForm which is the following: class MenuForm(djangoforms.ModelForm): class Meta: model = Menu exclude = ['added_by','menu_items'] When I run this I get the following error: Exception Type: ValueError Exception Value: Item type MenuItem is not acceptable I want to crate the form and have it omit the menu_items property as for one I don't think there is an in built control for the multiple choice, like a group of check boxes. Either way I cannot understand with this property in the exclude items why it is throwing this error. TIA Andrew A: Your problem comes well before the "create a form" task begins: ListProperty does not allow a list of model entities (although I can't find this clearly documented in the app engine docs, I'm still looking in the docs for a good, clear, unambiguous statement about that). Try changing it into (say) a list of strings, and you'll see everything works (I believe a dropdown is what you get if you don't exclude such a property). Edit: found the spot in the docs where the issue is mentioned, although it's quaintly phrased -- quoting with added emphasis: The list can contain values of any of the value types supported by the datastore. ...point is, you can have in the list objects of any of the value types... not reference ones, i.e., entities that are instances of some model. Could you use a list of key strings, instead...?
How to create Form from a Model which has a ListProperty
I am currently using Django forms with the Google App Engine and I have a model which is as follows: class Menu(db.Model): name = db.StringProperty(required=True) is_special = db.BooleanProperty() menu_items = db.ListProperty(MenuItem) I have a MenuForm which is the following: class MenuForm(djangoforms.ModelForm): class Meta: model = Menu exclude = ['added_by','menu_items'] When I run this I get the following error: Exception Type: ValueError Exception Value: Item type MenuItem is not acceptable I want to crate the form and have it omit the menu_items property as for one I don't think there is an in built control for the multiple choice, like a group of check boxes. Either way I cannot understand with this property in the exclude items why it is throwing this error. TIA Andrew
[ "Your problem comes well before the \"create a form\" task begins: ListProperty does not allow a list of model entities (although I can't find this clearly documented in the app engine docs, I'm still looking in the docs for a good, clear, unambiguous statement about that). Try changing it into (say) a list of strings, and you'll see everything works (I believe a dropdown is what you get if you don't exclude such a property).\nEdit: found the spot in the docs where the issue is mentioned, although it's quaintly phrased -- quoting with added emphasis:\n\nThe list can contain values of any of\n the value types supported by the\n datastore.\n\n...point is, you can have in the list objects of any of the value types... not reference ones, i.e., entities that are instances of some model.\nCould you use a list of key strings, instead...?\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002037591_django_google_app_engine_python.txt
Q: jquery.autocomplete.js - how does autocomplete work? I call the autocomplete jquery with the result of a GET request. The autocomplete function call looks like this: $('#id_project_owner_externally').autocomplete('/pm/contact_autocomplete'); The url /pm/contact_autocomplete returns a list of tuples. The first part of the tuple is the name of the contact and the second part of the tuple is the id of the contact. The corresponding function (part of a django view) looks like this: def iter_results(results): if results: for r in results: yield '%s|%s\n' % (r.first_name, r.id) Now I'm wondering what jquery autocomplete is doing with the first_name + id tuple. Acutally the first_name is put into the input field. But what happens with the id part. This is the important information that I need. Can I tell jquery that the id should be placed into a certain hidden field? link to js source Edit: The solution <script type="text/javascript"><!--// $('#id_project_manager_externally').autocomplete('/pm/contact_autocomplete').result(function(event, item) {$('#id_project_manager_externally_hidden').attr("value", item[1]);});//--></script> A: The plugin docs have this example: var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ]; $("...").autocomplete(data, { formatItem: function(item) { return item.text; } }).result(function(event, item) { location.href = item.url; }); So you basically can have a .result() option that you use to populate a hidden field. e.g. $('#my_hidden_field').val(item.extra_value); A: You need to look into the jquery.autocomplete.js source code, what your python code does is simply return the id and name separated by a hash char, one record per line. The autocomplete javascript handles that output, thus that is the part of the code you need to modify to put the ids into your hidden fields.
jquery.autocomplete.js - how does autocomplete work?
I call the autocomplete jquery with the result of a GET request. The autocomplete function call looks like this: $('#id_project_owner_externally').autocomplete('/pm/contact_autocomplete'); The url /pm/contact_autocomplete returns a list of tuples. The first part of the tuple is the name of the contact and the second part of the tuple is the id of the contact. The corresponding function (part of a django view) looks like this: def iter_results(results): if results: for r in results: yield '%s|%s\n' % (r.first_name, r.id) Now I'm wondering what jquery autocomplete is doing with the first_name + id tuple. Acutally the first_name is put into the input field. But what happens with the id part. This is the important information that I need. Can I tell jquery that the id should be placed into a certain hidden field? link to js source Edit: The solution <script type="text/javascript"><!--// $('#id_project_manager_externally').autocomplete('/pm/contact_autocomplete').result(function(event, item) {$('#id_project_manager_externally_hidden').attr("value", item[1]);});//--></script>
[ "The plugin docs have this example:\nvar data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];\n$(\"...\").autocomplete(data, {\n formatItem: function(item) {\n return item.text;\n }\n}).result(function(event, item) {\n location.href = item.url;\n});\n\nSo you basically can have a .result() option that you use to populate a hidden field.\ne.g. $('#my_hidden_field').val(item.extra_value);\n", "You need to look into the jquery.autocomplete.js source code, what your python code does is simply return the id and name separated by a hash char, one record per line. The autocomplete javascript handles that output, thus that is the part of the code you need to modify to put the ids into your hidden fields.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0002038031_django_jquery_python.txt
Q: Getting output from server side python script Hey, I'm doing this project where we are supposed to connect a javascript client side application/web page on server A with a python server side script on server B. I need to get the output from the python script and store it into a variable but am running into some problems. I was trying to use XMLHttpRequest for this, and even though I managed to establish the connection the return value from the script is always "", an empty string, and it shouldn't be. Does anyone know what the issue might be here and how to solve it? P.S. I've been hinted that it might have something to do with cross-server scripting security or something like that, I'm not sure if that helps. Thanks EDIT: I've changed to jQuery, which seems simpler. Apparently the problem really is teh cross-server (I've managed to get the data if the script is in the same server) security or permissions within the web-browser (Firefox).. Anyone knows a way around this? EDIT2: We managed to solve it using JSON... thanks for the replies anyway! A: It sounds like your XMLHttpRequest is failing because you're trying to do a cross-domain request. You could use a cross-domain solution like JSONP instead. In general, tools like Firebug net panel are really useful for debugging these types of problems--you can use them to tell whether the client is sending a request correctly, and whether the server is responding correctly.
Getting output from server side python script
Hey, I'm doing this project where we are supposed to connect a javascript client side application/web page on server A with a python server side script on server B. I need to get the output from the python script and store it into a variable but am running into some problems. I was trying to use XMLHttpRequest for this, and even though I managed to establish the connection the return value from the script is always "", an empty string, and it shouldn't be. Does anyone know what the issue might be here and how to solve it? P.S. I've been hinted that it might have something to do with cross-server scripting security or something like that, I'm not sure if that helps. Thanks EDIT: I've changed to jQuery, which seems simpler. Apparently the problem really is teh cross-server (I've managed to get the data if the script is in the same server) security or permissions within the web-browser (Firefox).. Anyone knows a way around this? EDIT2: We managed to solve it using JSON... thanks for the replies anyway!
[ "It sounds like your XMLHttpRequest is failing because you're trying to do a cross-domain request. You could use a cross-domain solution like JSONP instead.\nIn general, tools like Firebug net panel are really useful for debugging these types of problems--you can use them to tell whether the client is sending a request correctly, and whether the server is responding correctly.\n" ]
[ 4 ]
[]
[]
[ "javascript", "python", "scripting", "xmlhttprequest" ]
stackoverflow_0002038085_javascript_python_scripting_xmlhttprequest.txt
Q: How to get module variable in function from another module? I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g. # mod1.py mod_var = 1 modify_var() # mod_var modified print mod_var The problem is - I can't reference variable by mod1.mod_var, because I want to use helper function across many modules (helper itself will be defined in other module); it should dynamically 'pick' mod_var from surrounding calling context/scope. Is this possible? How to obtain this? My use case is to enhance defining URL -> view mapping in Django. Those definitions are spread across many sub-modules that define urlpatterns module-level variable. Helper function should pick this variable from the module that calls it and modify it. Avoiding explicitly passing it as argument would be great. Edit: For additional solution - check this answer. Edit2: Wrong solution below! (left for references in comments) Recently I've found another solution (the least magical in my opinion ;)) modify_var() function could be implemented like this: def modify_var(): calling_module = __import__("__main__") calling_module.mod_var = 42 Still, potential profits are arguable. unittest module uses this technique in its main method. A: What you want to do sounds like too much magic. Pass in urlpatterns and be done with it. Explicit is better than implicit. A: It's a truly bad, horrible, and awful idea, which will lead to future maintenance nightmares. However, Python does offer "enough rope to shoot yourself in the foot", if you truly insist: introspection and metaprogramming tools which are mostly intended for debugging purposes, but can be abused to perform the ill-conceived task you so desperately crave. For example, in evil.py: import inspect def modify_var(): callersframe = inspect.stack()[1][0] callersglobals = callersframe.f_globals if 'mod_var' not in callersglobals: raise ValueError, 'calling module has no "mod_var"!' callersglobals['mod_var'] += 1 now say you have two modules, a.py: import evil mod_var = 23 evil.modify_var() print 'a mod_var now:', mod_var and b.py: import evil mod_var = 100 evil.modify_var() print 'b mod_var now:', mod_var you could do: $ python -c'import a; import b' a mod_var now: 24 b mod_var now: 101 However, maintaining this kind of black-magic tricks in the future is going to be a headache, so I'd strongly recommend not doing things this way. A: OK, here's the magic, but again, I recommend not using it: import sys def modify_var(): """Mysteriously change `mod_var` in the caller's context.""" f = sys._getframe(1) f.f_locals['mod_var'] += " (modified)" mod_var = "Hello" modify_var() print mod_var prints: Hello (modified) As a further warning against this technique: _getframe is one of those functions that other implementations of Python don't provide, and the docs include this sentence: "This function should be used for internal and specialized purposes only." A: If you really want to do that then you'll need to import mod1 in either the other module or directly in the function, and then modify it off that import. But don't do that; seasoned programmers will point and laugh.
How to get module variable in function from another module?
I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g. # mod1.py mod_var = 1 modify_var() # mod_var modified print mod_var The problem is - I can't reference variable by mod1.mod_var, because I want to use helper function across many modules (helper itself will be defined in other module); it should dynamically 'pick' mod_var from surrounding calling context/scope. Is this possible? How to obtain this? My use case is to enhance defining URL -> view mapping in Django. Those definitions are spread across many sub-modules that define urlpatterns module-level variable. Helper function should pick this variable from the module that calls it and modify it. Avoiding explicitly passing it as argument would be great. Edit: For additional solution - check this answer. Edit2: Wrong solution below! (left for references in comments) Recently I've found another solution (the least magical in my opinion ;)) modify_var() function could be implemented like this: def modify_var(): calling_module = __import__("__main__") calling_module.mod_var = 42 Still, potential profits are arguable. unittest module uses this technique in its main method.
[ "What you want to do sounds like too much magic. Pass in urlpatterns and be done with it. Explicit is better than implicit.\n", "It's a truly bad, horrible, and awful idea, which will lead to future maintenance nightmares. However, Python does offer \"enough rope to shoot yourself in the foot\", if you truly insist: introspection and metaprogramming tools which are mostly intended for debugging purposes, but can be abused to perform the ill-conceived task you so desperately crave.\nFor example, in evil.py:\nimport inspect\n\ndef modify_var():\n callersframe = inspect.stack()[1][0]\n callersglobals = callersframe.f_globals\n if 'mod_var' not in callersglobals:\n raise ValueError, 'calling module has no \"mod_var\"!'\n callersglobals['mod_var'] += 1\n\nnow say you have two modules, a.py:\nimport evil\n\nmod_var = 23\nevil.modify_var()\nprint 'a mod_var now:', mod_var\n\nand b.py:\nimport evil\n\nmod_var = 100\nevil.modify_var()\nprint 'b mod_var now:', mod_var\n\nyou could do:\n$ python -c'import a; import b'\na mod_var now: 24\nb mod_var now: 101\n\nHowever, maintaining this kind of black-magic tricks in the future is going to be a headache, so I'd strongly recommend not doing things this way.\n", "OK, here's the magic, but again, I recommend not using it:\nimport sys\n\ndef modify_var():\n \"\"\"Mysteriously change `mod_var` in the caller's context.\"\"\"\n f = sys._getframe(1)\n f.f_locals['mod_var'] += \" (modified)\"\n\nmod_var = \"Hello\"\nmodify_var()\nprint mod_var\n\nprints:\nHello (modified)\n\nAs a further warning against this technique: _getframe is one of those functions that other implementations of Python don't provide, and the docs include this sentence: \"This function should be used for internal and specialized purposes only.\"\n", "If you really want to do that then you'll need to import mod1 in either the other module or directly in the function, and then modify it off that import. But don't do that; seasoned programmers will point and laugh.\n" ]
[ 4, 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002038160_django_python.txt
Q: Integration of Python console into a GUI C++ application I'm going to add a python console widget (into a C++ GUI) below some other controls: Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt). Should I run the Python code in a separate thread? I think it's a good approach, because GUI won't be frozen while executing long commands. But on the other hand, shouldn't other controls be disabled to preserve objects' state and avoid conflicts? A: Since you're apparently wanting to embed a Python interpreter to use Python as a scripting language in a what seems to be a Qt application, I suggest you have a look at PythonQt. With the PythonQt module, Python scripts will be able to interact with the GUI of your host application. Unlike PyQt and Qt Jambi, PythonQt is not designed to provide support for developers writing standalone applications. Instead, it provides facilities to embed a Python interpreter and focuses on making it easy to expose parts of the application to Python. If I understood your needs correctly, that's all you need. PyQt and PySide (officially supported by Nokia) aim at accessing Qt features from a Python program by providing bindings. It's possible to embed PyQt in your application (even a Qt application) and your Python scripts will be able to provide their own GUI while interacting with your application scripting API. About thread safety, Qt offers a thread-safe way of posting events, and signal-slot connections across threads. References: Embedding Python into Qt Applications. Notes for embedding python in your C/C++ app EmbedingPyQtTutorial
Integration of Python console into a GUI C++ application
I'm going to add a python console widget (into a C++ GUI) below some other controls: Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt). Should I run the Python code in a separate thread? I think it's a good approach, because GUI won't be frozen while executing long commands. But on the other hand, shouldn't other controls be disabled to preserve objects' state and avoid conflicts?
[ "Since you're apparently wanting to embed a Python interpreter to use Python as a scripting language in a what seems to be a Qt application, I suggest you have a look at PythonQt.\nWith the PythonQt module, Python scripts will be able to interact with the GUI of your host application.\n\nUnlike PyQt and Qt Jambi, PythonQt is not designed to provide support for developers writing standalone applications. Instead, it provides facilities to embed a Python interpreter and focuses on making it easy to expose parts of the application to Python.\n\nIf I understood your needs correctly, that's all you need.\nPyQt and PySide (officially supported by Nokia) aim at accessing Qt features from a Python program by providing bindings.\nIt's possible to embed PyQt in your application (even a Qt application) and your Python scripts will be able to provide their own GUI while interacting with your application scripting API.\nAbout thread safety, Qt offers a thread-safe way of posting events, and signal-slot connections across threads.\nReferences:\n\nEmbedding Python into Qt Applications.\nNotes for embedding python in your C/C++ app\nEmbedingPyQtTutorial\n\n" ]
[ 14 ]
[]
[]
[ "c++", "integration", "multithreading", "python", "user_interface" ]
stackoverflow_0002038247_c++_integration_multithreading_python_user_interface.txt
Q: Sets of instances I'm trying to build a set of instances of an object, however adding instances of certain objects results in a TypeError: unhashable instance. Here is a minimal example: from sets import Set import random from UserDict import DictMixin class Item1(object): pass class Item2(DictMixin): pass item_collection = Set() x = Item1() y = Item2() item_collection.add(x) # this works print item_collection item_collection.add(y) # this does not print item_collection Why does that fail and how can I get a set of instances of an object derived from DictMixin? A: In order to put things into a set, they should be hashable. Tuples for example are hashable whereas lists are not. You can make your object hashable by giving it a __hash__ method that will generate a hash key (a unique identifier for that instance of the class dependent on the data it's holding) for it. Here is an example to trying to add a list into a set. >>> x = [1,2,3] >>> a=set() >>> a.add(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' It looks like your DictMixin class is not hashable. A: Your classes can, if you want, define __hash__ and comparison methods (most importantly __eq__) to be consistent with each other and "stable" -- i.e., the equality of two objects must not vary over the objects' lifetimes, and of course neither must each object's hash value vary over the object's lifetime. The consistency requirement is: a==b must imply hash(a)==hash(b) (the reverse need not hold, and indeed rarely does). So if you're OK with those requirements the simplest implementation would be: class Item2(DictMixin): def __hash__(self): return hash(id(self)) def __eq__(self, x): return x is self def __ne__(self, x): return x is not self as it happens this would also automatically interoperate with your Item1 class, because this is the default implementation of hashing and comparison for classes that don't inherit or define other versions (as you're inheriting a different version of __eq__ from DictMixin unless you override it again). x is self is a faster, more direct, and more concise expression of id(x) == id(self), because that is the meaning of the is operator -- identity of id (i.e., same object). So is the fact that a==b is forced thereby to mean the same thing as a is b a problem for your application? If so, then sets are just not usable for said application and you need to think about some other, completely different data structure (one that's not based on hashing, because without the __eq__ override you can't make hashing work correctly).
Sets of instances
I'm trying to build a set of instances of an object, however adding instances of certain objects results in a TypeError: unhashable instance. Here is a minimal example: from sets import Set import random from UserDict import DictMixin class Item1(object): pass class Item2(DictMixin): pass item_collection = Set() x = Item1() y = Item2() item_collection.add(x) # this works print item_collection item_collection.add(y) # this does not print item_collection Why does that fail and how can I get a set of instances of an object derived from DictMixin?
[ "In order to put things into a set, they should be hashable. Tuples for example are hashable whereas lists are not. You can make your object hashable by giving it a __hash__ method that will generate a hash key (a unique identifier for that instance of the class dependent on the data it's holding) for it. \nHere is an example to trying to add a list into a set.\n>>> x = [1,2,3]\n>>> a=set()\n>>> a.add(x)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unhashable type: 'list'\n\nIt looks like your DictMixin class is not hashable. \n", "Your classes can, if you want, define __hash__ and comparison methods (most importantly __eq__) to be consistent with each other and \"stable\" -- i.e., the equality of two objects must not vary over the objects' lifetimes, and of course neither must each object's hash value vary over the object's lifetime.\nThe consistency requirement is: a==b must imply hash(a)==hash(b) (the reverse need not hold, and indeed rarely does).\nSo if you're OK with those requirements the simplest implementation would be:\nclass Item2(DictMixin):\n def __hash__(self): return hash(id(self))\n def __eq__(self, x): return x is self\n def __ne__(self, x): return x is not self\n\nas it happens this would also automatically interoperate with your Item1 class, because this is the default implementation of hashing and comparison for classes that don't inherit or define other versions (as you're inheriting a different version of __eq__ from DictMixin unless you override it again).\nx is self is a faster, more direct, and more concise expression of id(x) == id(self), because that is the meaning of the is operator -- identity of id (i.e., same object).\nSo is the fact that a==b is forced thereby to mean the same thing as a is b a problem for your application? If so, then sets are just not usable for said application and you need to think about some other, completely different data structure (one that's not based on hashing, because without the __eq__ override you can't make hashing work correctly).\n" ]
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002038010_python.txt
Q: Difficulty getting flup fcgi script to work I'm building a site for a client using django. It's been hosted on shared hosting and mod_wsgi can't be used. In the old year, I got it working using fcgi, but when I got back, it was broken. I have replaced the fcgi script with a simple hello world script: #!/usr/bin/python def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!\n'] try: from flup.server.fcgi import WSGIServer WSGIServer(myapp).run() except: import sys, traceback traceback.print_exc(file=open("errlog.txt","a")) Tested and working on my local server, but on the hosted server, I get this error: <title>FCGI Error</title> A timeout occured while waiting for the script output (in: /usr/www/users/mymemb/). If I look at the error log, I see this: [Wed Jan 6 16:59:37 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" (user mymemb, gid 100) restarted (pid 1057) [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" (pid 1057) terminated by calling exit with status '118' [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds etc ... If I ssh to the server, I can run the script fine, with the following output: mymemb@www81:~/public_html$ ./mymembers.fcgi WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Status: 200 OK Content-Type: text/plain Content-Length: 13 Hello World! How do I fix this? Added info: It seems like the script is not running at all. If I add import x at the top of the script, and run it from ssh, I see that x.pyc gets created. If I rm x.pyc, and then hit the site, x.pyc does not get created. I also noticed that the errors changed from terminated by calling exit with status '118' to terminated by calling exit with status '116' I wish I could find a reference for these exit statuses. A: The exit status 116 and 118 were coming from suexec. By reading the source code, I found that these errors are caused by the file/dir being writable by group or others, which suexec considers as a security issue. Removing write access from group fixed the problem.
Difficulty getting flup fcgi script to work
I'm building a site for a client using django. It's been hosted on shared hosting and mod_wsgi can't be used. In the old year, I got it working using fcgi, but when I got back, it was broken. I have replaced the fcgi script with a simple hello world script: #!/usr/bin/python def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!\n'] try: from flup.server.fcgi import WSGIServer WSGIServer(myapp).run() except: import sys, traceback traceback.print_exc(file=open("errlog.txt","a")) Tested and working on my local server, but on the hosted server, I get this error: <title>FCGI Error</title> A timeout occured while waiting for the script output (in: /usr/www/users/mymemb/). If I look at the error log, I see this: [Wed Jan 6 16:59:37 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" (user mymemb, gid 100) restarted (pid 1057) [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" (pid 1057) terminated by calling exit with status '118' [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds [Wed Jan 6 16:59:38 2010] [warn] FastCGI: (dynamic) server "/usr/www/users/mymemb/mymembers.fcgi" has failed to remain running for 30 seconds given 3 attempts, its restart interval has been backed off to 10 seconds etc ... If I ssh to the server, I can run the script fine, with the following output: mymemb@www81:~/public_html$ ./mymembers.fcgi WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Status: 200 OK Content-Type: text/plain Content-Length: 13 Hello World! How do I fix this? Added info: It seems like the script is not running at all. If I add import x at the top of the script, and run it from ssh, I see that x.pyc gets created. If I rm x.pyc, and then hit the site, x.pyc does not get created. I also noticed that the errors changed from terminated by calling exit with status '118' to terminated by calling exit with status '116' I wish I could find a reference for these exit statuses.
[ "The exit status 116 and 118 were coming from suexec. By reading the source code, I found that these errors are caused by the file/dir being writable by group or others, which suexec considers as a security issue. Removing write access from group fixed the problem.\n" ]
[ 2 ]
[]
[]
[ "django", "fastcgi", "flup", "python" ]
stackoverflow_0002013936_django_fastcgi_flup_python.txt
Q: Implementing tridiagonal matrix algorithm (TDMA) with NumPy I'm implementing TDMA in Python using NumPy. The tridiagonal matrix is stored in three arrays: a = array([...]) b = array([...]) c = array([...]) I'd like to calculate alpha-coefficients efficiently. The algorithm is as follows: # n = size of the given matrix - 1 alpha = zeros(n) alpha[0] = b[0] / c[0] for i in range(n-1): alpha[i+1] = b[i] / (c[i] - a[i] * alpha[i]) However, this is not efficient because of Python's for loop. Want I want is something like this approach: # n = size of the given matrix - 1 alpha = zeros(n) alpha[0] = b[0] / c[0] alpha[1:] = b[1:] / (c[1:] - a[1:] * alpha[:-1]) In this latter case the result is incorrect because NumPy stores the right part of the last expression in a temprorary array and then assigns references to its elements to alpha[1:]. Therefore a[1:] * alpha[:-1] is just an array of zeros. Is there a way to tell NumPy to use values of alpha calculated on previous steps within its internal loop? Thanks. A: If its tridiagonal systems you want to solve there is solve_banded() in numpy.linalg. Not sure if that's what you're looking for. A: Apparently, there is no way to do this in Python without using C or its pythonic variations.
Implementing tridiagonal matrix algorithm (TDMA) with NumPy
I'm implementing TDMA in Python using NumPy. The tridiagonal matrix is stored in three arrays: a = array([...]) b = array([...]) c = array([...]) I'd like to calculate alpha-coefficients efficiently. The algorithm is as follows: # n = size of the given matrix - 1 alpha = zeros(n) alpha[0] = b[0] / c[0] for i in range(n-1): alpha[i+1] = b[i] / (c[i] - a[i] * alpha[i]) However, this is not efficient because of Python's for loop. Want I want is something like this approach: # n = size of the given matrix - 1 alpha = zeros(n) alpha[0] = b[0] / c[0] alpha[1:] = b[1:] / (c[1:] - a[1:] * alpha[:-1]) In this latter case the result is incorrect because NumPy stores the right part of the last expression in a temprorary array and then assigns references to its elements to alpha[1:]. Therefore a[1:] * alpha[:-1] is just an array of zeros. Is there a way to tell NumPy to use values of alpha calculated on previous steps within its internal loop? Thanks.
[ "If its tridiagonal systems you want to solve there is solve_banded() in numpy.linalg. Not sure if that's what you're looking for.\n", "Apparently, there is no way to do this in Python without using C or its pythonic variations.\n" ]
[ 2, 2 ]
[]
[]
[ "numerical_methods", "numpy", "python" ]
stackoverflow_0001929045_numerical_methods_numpy_python.txt
Q: Access scanner from Java or Python (or something else if it's technically motivated) in Linux (but Windows would be nice) I want to write a system for handling important documents in my home. This is the user story for getting a new document: I "Add new document" and am prompted to scan it using my combined printer/scanner. I view the scanned copy to see it's of good enough quality. Which it has. The system tells me to mark it with number N, which I do. I also enter title, document type, description and when the document is no longer needed to be stored (could be never to always keep it). The problem is accessing the scanner. I do not know what the smoothest way is. Ideally it would support "all" scanners through some kind of standard interface. I do not know if that even exists. Should I do this in Java, Python or something else? My primary platform is Linux. But if it worked on Windows too, that would be nice. If I manage to create something useful I'll release it as GPL, so it's for a good cause too. ;-) Thank you for reading! A: Under Linux, the common interface to scanners is SANE. A: The standard interface for scanners is TWAIN. If you google for "java twain" or "python twain", you get plenty of useful-looking stuff, e.g. http://www.programmersheaven.com/2/Java-Twain-image-acquisition http://twainmodule.sourceforge.net/
Access scanner from Java or Python (or something else if it's technically motivated) in Linux (but Windows would be nice)
I want to write a system for handling important documents in my home. This is the user story for getting a new document: I "Add new document" and am prompted to scan it using my combined printer/scanner. I view the scanned copy to see it's of good enough quality. Which it has. The system tells me to mark it with number N, which I do. I also enter title, document type, description and when the document is no longer needed to be stored (could be never to always keep it). The problem is accessing the scanner. I do not know what the smoothest way is. Ideally it would support "all" scanners through some kind of standard interface. I do not know if that even exists. Should I do this in Java, Python or something else? My primary platform is Linux. But if it worked on Windows too, that would be nice. If I manage to create something useful I'll release it as GPL, so it's for a good cause too. ;-) Thank you for reading!
[ "Under Linux, the common interface to scanners is SANE.\n", "The standard interface for scanners is TWAIN. If you google for \"java twain\" or \"python twain\", you get plenty of useful-looking stuff, e.g.\n\nhttp://www.programmersheaven.com/2/Java-Twain-image-acquisition\nhttp://twainmodule.sourceforge.net/\n\n" ]
[ 3, 1 ]
[]
[]
[ "image_scanner", "java", "python" ]
stackoverflow_0002038700_image_scanner_java_python.txt
Q: Listing buildout configuration variables I'd like to find out, exactly what variables are available when using zc.buildout. I can always look at the source, but ideally I'd find a list somewhere, or be able to query buildout to find out what it thinks are the variables available at any one time. Is this possible? A: I found from the buildout docs that bin/buildout annotate was what I was looking for. A: It is not the prettiest list, but you can look at .installed.cfg in your buildout's directory. For every part, it shows which options it knows about. (For some reason several parts are often shown multiple times).
Listing buildout configuration variables
I'd like to find out, exactly what variables are available when using zc.buildout. I can always look at the source, but ideally I'd find a list somewhere, or be able to query buildout to find out what it thinks are the variables available at any one time. Is this possible?
[ "I found from the buildout docs that \nbin/buildout annotate \nwas what I was looking for.\n", "It is not the prettiest list, but you can look at .installed.cfg in your buildout's directory.\nFor every part, it shows which options it knows about. (For some reason several parts are often shown multiple times).\n" ]
[ 14, 1 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0002037290_buildout_python.txt
Q: Python ctypes addressof CFuncType Related to my other question How can I get the address (acctual function pointer) to a CFuncType object? addressof() does not report the correct address. C code: extern "C" _declspec(dllexport) int addr(int (*func)()) { int r = (int)func; return r; } Python code: def test(): return 42 t = CFUNCTYPE(c_int) f = t(test) print addressof(f) print dll.addr(f) Output: 7030864 3411932 trying to call *(7030864) from C causes a crash, but calling *(3411932) works as expected. What's wrong with addressof()? A: cast(f, c_void_p) gets the correct address from within python
Python ctypes addressof CFuncType
Related to my other question How can I get the address (acctual function pointer) to a CFuncType object? addressof() does not report the correct address. C code: extern "C" _declspec(dllexport) int addr(int (*func)()) { int r = (int)func; return r; } Python code: def test(): return 42 t = CFUNCTYPE(c_int) f = t(test) print addressof(f) print dll.addr(f) Output: 7030864 3411932 trying to call *(7030864) from C causes a crash, but calling *(3411932) works as expected. What's wrong with addressof()?
[ "cast(f, c_void_p) gets the correct address from within python\n" ]
[ 7 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0002038839_ctypes_python.txt
Q: How should I convert this long and complex PHP style URL query string to a Django url? I'm converting a small PHP application to Django. One section has a long query string, indicating how a widget is to be displayed. There are a few required parameters and several optional ones. The current urls read like: app.php?id=102030&size=large&auto=0&bw=1&extra=1 The id and size are required, but auto, bw and extra are optional. I use defaults if they're not specified. My first idea was to make a django URL pattern with the required info, id and size: url(r'^/app/(P?<id>)\d+/(P?<size>)\w+$',app.project.views.widget,name='swidget') The optional parameters would then be a query string, like /app/102030/large?auto=0&bw=1&extra=0 Is it a common practice to mix GET parameters with parameters defined in the URL conf in Django? Or should I make it like url(r'^/app/(P?<id>)\d+/(P?<size>)\w+/(P?<auto>)\d/(P?<bw>)\d/(P?<extra>)\d[/]?,'app.project.views.widget,name='swidget') #so it would look like: /app/102030/large/0/1/0/ Any suggestions about best practices or issues to keep in mind with either style are appreciated! A: If you consider that "URL" stands for Uniform Resource Locator, the URL should only indicate the resource being displayed, and any 'configuration' options should be passed as parameters. So, I think your first idea is fine.
How should I convert this long and complex PHP style URL query string to a Django url?
I'm converting a small PHP application to Django. One section has a long query string, indicating how a widget is to be displayed. There are a few required parameters and several optional ones. The current urls read like: app.php?id=102030&size=large&auto=0&bw=1&extra=1 The id and size are required, but auto, bw and extra are optional. I use defaults if they're not specified. My first idea was to make a django URL pattern with the required info, id and size: url(r'^/app/(P?<id>)\d+/(P?<size>)\w+$',app.project.views.widget,name='swidget') The optional parameters would then be a query string, like /app/102030/large?auto=0&bw=1&extra=0 Is it a common practice to mix GET parameters with parameters defined in the URL conf in Django? Or should I make it like url(r'^/app/(P?<id>)\d+/(P?<size>)\w+/(P?<auto>)\d/(P?<bw>)\d/(P?<extra>)\d[/]?,'app.project.views.widget,name='swidget') #so it would look like: /app/102030/large/0/1/0/ Any suggestions about best practices or issues to keep in mind with either style are appreciated!
[ "If you consider that \"URL\" stands for Uniform Resource Locator, the URL should only indicate the resource being displayed, and any 'configuration' options should be passed as parameters. So, I think your first idea is fine.\n" ]
[ 8 ]
[]
[]
[ "django", "python", "url", "url_routing" ]
stackoverflow_0002039054_django_python_url_url_routing.txt
Q: Handling an "Inventory" (complex associations) with django + appengine I'm writing a web application to manage a "game". Here are the models: class Character(db.Model): # Bio name = db.StringProperty() player = db.StringProperty() level = db.IntegerProperty() class Item(db.Model): name = db.StringProperty() description = db.StringProperty() value = db.StringProperty() class Inventory(db.Model): character = db.ReferenceProperty(Character,required=True,collection_name="inventory") item = db.ReferenceProperty(Item,required=True,collection_name="inventory") quantity = db.IntegerProperty() equipped = db.BooleanProperty() I've an Item database, and when I add a character I want to manage its Inventory. I've tried ModelForms but they can't handle this sort of things. My idea is to display the complete Item list, each Item with an associated form quantity,equipped. Something like: Sword : quantity ___ equipped _ Armor : quantity ___ equipped _ But, how to ship additional informations in forms? P.S. I'm sorry that the question is dumb and not general, but I couldn't find the keywords to generalize it.. A: Not sure if I understand you correctly, but if you want to show the Inventory of a Character in a form and place the form of the Character at the same page, you should check out inline formsets the doc Using inline formsets you can do something like this: character= get_object_or_404(Character, pk=character_id) InventoryInlineFormSet = inlineformset_factory(Character, Inventory, max_num=1) classificationformset = ClassificationInlineFormSet(instance=character) Out of this form you can manage your items, for example if you have a ManyToMany Relationship to your Items model you can handle them with ajax-filtered-fields link HTH A: you will want to look at inline formsets. http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
Handling an "Inventory" (complex associations) with django + appengine
I'm writing a web application to manage a "game". Here are the models: class Character(db.Model): # Bio name = db.StringProperty() player = db.StringProperty() level = db.IntegerProperty() class Item(db.Model): name = db.StringProperty() description = db.StringProperty() value = db.StringProperty() class Inventory(db.Model): character = db.ReferenceProperty(Character,required=True,collection_name="inventory") item = db.ReferenceProperty(Item,required=True,collection_name="inventory") quantity = db.IntegerProperty() equipped = db.BooleanProperty() I've an Item database, and when I add a character I want to manage its Inventory. I've tried ModelForms but they can't handle this sort of things. My idea is to display the complete Item list, each Item with an associated form quantity,equipped. Something like: Sword : quantity ___ equipped _ Armor : quantity ___ equipped _ But, how to ship additional informations in forms? P.S. I'm sorry that the question is dumb and not general, but I couldn't find the keywords to generalize it..
[ "Not sure if I understand you correctly, but if you want to show the Inventory of a Character in a form and place the form of the Character at the same page, you should check out inline formsets the doc\nUsing inline formsets you can do something like this:\ncharacter= get_object_or_404(Character, pk=character_id)\nInventoryInlineFormSet = inlineformset_factory(Character, Inventory, max_num=1)\nclassificationformset = ClassificationInlineFormSet(instance=character)\n\nOut of this form you can manage your items, for example if you have a ManyToMany Relationship to your Items model you can handle them with ajax-filtered-fields link\nHTH\n", "you will want to look at inline formsets.\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002038290_django_python.txt
Q: Fractions with decimal precision Is there a pure python implementation of fractions.Fraction that supports longs as numerator and denominator? Unfortunately, exponentiation appears to be coded in to return a float (ack!!!), which should at least support using decimal.Decimal. If there isn't, I suppose I can probably make a copy of the library and try to replace occurrences of float() with something appropriate from Decimal but I'd rather something that's been tested by others before. Here's a code example: base = Fraction.from_decimal(Decimal(1).exp()) a = Fraction(69885L, 53L) x = Fraction(9L, 10L) print base**(-a*x), type(base**(-a*x)) results in 0.0 <type 'float'> where the answer should be a really small decimal. Update: I've got the following work-around for now (assuming, for a**b, that both are fractions; of course, I'll need another function when exp_ is a float or is itself a Decimal): def fracpow(base, exp_): base = Decimal(base.numerator)/Decimal(base.denominator) exp_ = Decimal(exp_.numerator)/Decimal(exp_.denominator) return base**exp_ which gives the answer 4.08569925773896097019795484811E-516. I'd still be interested if there's a better way of doing this without the extra functions (I'm guessing if I work with the Fraction class enough, I'll find other floats working their way into my results). A: "Raise to a power" is not a closed operation over the rationals (differently from the usual four arithmetic operations): there is no rational number r such that r == 2 ** 0.5. Legend has it that Pythagoras (from whose theorem this fact so simply follows) had his disciple Hippasus killed for the horrible crime of proving this; looks like you sympathize wit Pythagoras' alleged reaction;-), given your weird use of "should". Python's fractions are meant to be exact, so inevitably there are case in which raising a fraction to another fraction's power will be absolutely unable to return a fraction as its result; and "should" just cannot be sensibly applied to a mathematical impossibility. So the best you can do is to approximate your desired result, e.g. by getting a result that's not an exact fraction (floats are generally considered sufficient for the purpose) and then further approximating it back with a fraction. Most existing pure-Python implementations (there are many rationals.py files found around the net;-) prefer not to implement a ** operator at all, but of course there's nothing stopping you from making a different design decision in your own implementation!-) A: You can write your own "pow" function for fractions that doesn't use floating-point exponentiation. Is that what you're trying to do? This will raise a fraction to an integer power with falling back to float. def pow( fract, exp ): if exp == 0: return fract elif exp % 2 == 0: t = pow( fract, exp//2 ) return t*t else: return fract*pos( fract, exp-1 )
Fractions with decimal precision
Is there a pure python implementation of fractions.Fraction that supports longs as numerator and denominator? Unfortunately, exponentiation appears to be coded in to return a float (ack!!!), which should at least support using decimal.Decimal. If there isn't, I suppose I can probably make a copy of the library and try to replace occurrences of float() with something appropriate from Decimal but I'd rather something that's been tested by others before. Here's a code example: base = Fraction.from_decimal(Decimal(1).exp()) a = Fraction(69885L, 53L) x = Fraction(9L, 10L) print base**(-a*x), type(base**(-a*x)) results in 0.0 <type 'float'> where the answer should be a really small decimal. Update: I've got the following work-around for now (assuming, for a**b, that both are fractions; of course, I'll need another function when exp_ is a float or is itself a Decimal): def fracpow(base, exp_): base = Decimal(base.numerator)/Decimal(base.denominator) exp_ = Decimal(exp_.numerator)/Decimal(exp_.denominator) return base**exp_ which gives the answer 4.08569925773896097019795484811E-516. I'd still be interested if there's a better way of doing this without the extra functions (I'm guessing if I work with the Fraction class enough, I'll find other floats working their way into my results).
[ "\"Raise to a power\" is not a closed operation over the rationals (differently from the usual four arithmetic operations): there is no rational number r such that r == 2 ** 0.5. Legend has it that Pythagoras (from whose theorem this fact so simply follows) had his disciple Hippasus killed for the horrible crime of proving this; looks like you sympathize wit Pythagoras' alleged reaction;-), given your weird use of \"should\".\nPython's fractions are meant to be exact, so inevitably there are case in which raising a fraction to another fraction's power will be absolutely unable to return a fraction as its result; and \"should\" just cannot be sensibly applied to a mathematical impossibility.\nSo the best you can do is to approximate your desired result, e.g. by getting a result that's not an exact fraction (floats are generally considered sufficient for the purpose) and then further approximating it back with a fraction. Most existing pure-Python implementations (there are many rationals.py files found around the net;-) prefer not to implement a ** operator at all, but of course there's nothing stopping you from making a different design decision in your own implementation!-)\n", "You can write your own \"pow\" function for fractions that doesn't use floating-point exponentiation. Is that what you're trying to do?\nThis will raise a fraction to an integer power with falling back to float.\ndef pow( fract, exp ):\n if exp == 0: \n return fract\n elif exp % 2 == 0:\n t = pow( fract, exp//2 )\n return t*t\n else:\n return fract*pos( fract, exp-1 )\n\n" ]
[ 7, 0 ]
[]
[]
[ "arbitrary_precision", "decimal", "long_integer", "python" ]
stackoverflow_0002039154_arbitrary_precision_decimal_long_integer_python.txt
Q: PyQt + shortcut to trigger a button How do I configure keyboard shortcuts to click specific buttons in a PyQT app? Eg: Ctrl + 1 to click one button while Ctrl + 2 to click the other? A: Use QtGui.QShortcut: you build it with a QKeySequence, and it emits the activated() signal when that key sequence is typed while the shortcut's parent widget has focus (of course, you connect those signals to slots of your choosing, including buttons').
PyQt + shortcut to trigger a button
How do I configure keyboard shortcuts to click specific buttons in a PyQT app? Eg: Ctrl + 1 to click one button while Ctrl + 2 to click the other?
[ "Use QtGui.QShortcut: you build it with a QKeySequence, and it emits the activated() signal when that key sequence is typed while the shortcut's parent widget has focus (of course, you connect those signals to slots of your choosing, including buttons').\n" ]
[ 7 ]
[]
[]
[ "button", "keyboard_shortcuts", "pyqt", "python" ]
stackoverflow_0002039241_button_keyboard_shortcuts_pyqt_python.txt
Q: why 'setprofile' print this import sys def a(): print 'aaa' def profiler(frame, event, arg): print event, frame.f_code.co_name, frame.f_lineno, "->", arg # profiler is activated on the next call, return, or exception sys.setprofile(profiler) a() print call a 5 -> None#what is it aaa return a 6 -> None#what is it return <module> 12 -> None#what is it why print this. A: The profiler function gets called at each profiling event because you called sys.setprofile on it. Each time it's called, it prints a line, because you put an unconditional print statement as its body. Why you did that, is hard for us to tell you, making your "why" questions really, truly peculiar. Profiling events are just calls and returns, per the docs: 'call' A function is called (or some other code block entered). 'return' A function (or other code block) is about to return. 'c_call' A C function is about to be called. This may be an extension function or a built-in. 'c_return' A C function has returned. Here's what I observe (Python 2.5 or 2.6, MacOSX) in a slightly simpler, sharper case: >>> def a(): ... print 'aaa' ... >>> def profiler(frame, event, arg): ... print 'PROF %r %r' % (event, arg) ... >>> sys.setprofile(profiler) PROF 'return' None >>> a() PROF 'call' None PROF 'c_call' <built-in function utf_8_decode> PROF 'c_return' <built-in function utf_8_decode> PROF 'return' (u'a()\n', 4) PROF 'call' None PROF 'call' None aaa PROF 'return' None PROF 'return' None Not sure why you don't see the c_call and c_return cases as you should -- maybe there is no implicit utf-8 conversion for printing in your specific platform (what OS? what level of Python? what IDE if any). A: It seems like maybe you're wondering why arg is None. arg has different meanings for each event. For "return", arg is the value to be returned. For "exception", it's a triple of exception information. See http://docs.python.org/library/sys.html#sys.settrace for more information.
why 'setprofile' print this
import sys def a(): print 'aaa' def profiler(frame, event, arg): print event, frame.f_code.co_name, frame.f_lineno, "->", arg # profiler is activated on the next call, return, or exception sys.setprofile(profiler) a() print call a 5 -> None#what is it aaa return a 6 -> None#what is it return <module> 12 -> None#what is it why print this.
[ "The profiler function gets called at each profiling event because you called sys.setprofile on it.\nEach time it's called, it prints a line, because you put an unconditional print statement as its body. Why you did that, is hard for us to tell you, making your \"why\" questions really, truly peculiar.\nProfiling events are just calls and returns, per the docs:\n\n'call'\n\nA function is called (or some other\n code block entered).\n'return'\n\nA function (or other code block) is\n about to return.\n'c_call'\n\nA C function is about to be called.\n This may be an extension function or a\n built-in.\n'c_return'\n\nA C function has returned.\n\nHere's what I observe (Python 2.5 or 2.6, MacOSX) in a slightly simpler, sharper case:\n>>> def a():\n... print 'aaa'\n... \n>>> def profiler(frame, event, arg):\n... print 'PROF %r %r' % (event, arg)\n... \n>>> sys.setprofile(profiler)\nPROF 'return' None\n>>> a()\nPROF 'call' None\nPROF 'c_call' <built-in function utf_8_decode>\nPROF 'c_return' <built-in function utf_8_decode>\nPROF 'return' (u'a()\\n', 4)\nPROF 'call' None\nPROF 'call' None\naaa\nPROF 'return' None\nPROF 'return' None\n\nNot sure why you don't see the c_call and c_return cases as you should -- maybe there is no implicit utf-8 conversion for printing in your specific platform (what OS? what level of Python? what IDE if any).\n", "It seems like maybe you're wondering why arg is None. arg has different meanings for each event. For \"return\", arg is the value to be returned. For \"exception\", it's a triple of exception information. See http://docs.python.org/library/sys.html#sys.settrace for more information.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0002039336_python_sys.txt
Q: How to upload images using an API Key that gives you permission to upload? [Python source code included] The documentation of the API shows source code on how to accomplish this in Python: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file.png"))] # OR: ("image", "http://example.com/example.jpg"))] c.setopt(c.URL, "http://imgur.com/api/upload.xml") c.setopt(c.HTTPPOST, values) c.perform() c.close() I'd like a bit of guidance on how to do this in C#. For instance, I'm lost on what these "values" would be in C#, how would I even declare them? I'm not familiar with cURL at all, so that might be holding me back from translating a bit. Help me Obi-wan. You're my only hope. /click A: You just need to perform an HTTP POST, e.g. this code with a "parameters" string of key=YOUR_API_KEY&image=http://example.com/example.jpg or the like.
How to upload images using an API Key that gives you permission to upload? [Python source code included]
The documentation of the API shows source code on how to accomplish this in Python: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file.png"))] # OR: ("image", "http://example.com/example.jpg"))] c.setopt(c.URL, "http://imgur.com/api/upload.xml") c.setopt(c.HTTPPOST, values) c.perform() c.close() I'd like a bit of guidance on how to do this in C#. For instance, I'm lost on what these "values" would be in C#, how would I even declare them? I'm not familiar with cURL at all, so that might be holding me back from translating a bit. Help me Obi-wan. You're my only hope. /click
[ "You just need to perform an HTTP POST, e.g. this code with a \"parameters\" string of key=YOUR_API_KEY&image=http://example.com/example.jpg or the like.\n" ]
[ 1 ]
[]
[]
[ "api", "c#", "imgur", "python" ]
stackoverflow_0002039602_api_c#_imgur_python.txt
Q: How do I regex search for weird non-ASCII characters in Python? I'm using the following regular expression basically to search for and delete these characters. invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)') My source code in ASCII encoded, and whenever I try to run the script it spits out: SyntaxError: Non-ASCII character '\xdb' in file ./release.py on line 273, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details If I follow the instructions at the given website, and place utf-8 on the second line encoding, my script doesn't run. Instead it gives me this error: SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xdb in position 0: unexpected end of data How do I get this one regular expression running in an ASCII written script that'd be great. A: You need to find out what encoding your editor is using, and set that per PEP263; or, make things more stable and portable (though alas perhaps a bit less readable) and use escape sequences in your string literal, i.e., use u'(\xdb|\xb2|\xb0|\xb1|\xc9|\xb9|\xcd)' as the parameter to the re.compile call. A: After telling Python that your source file uses UTF-8 encoding, did you actually make sure that your editor is saving the file using UTF-8 encoding? The error you get indicates that your editor is probably not using UTF-8. What text editor are you using? A: \x{c0de} In a regex will match the Unicode character at code point c0de. Python uses PCRE, right? (If it doesn't, it's probably \uC0DE instead...)
How do I regex search for weird non-ASCII characters in Python?
I'm using the following regular expression basically to search for and delete these characters. invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)') My source code in ASCII encoded, and whenever I try to run the script it spits out: SyntaxError: Non-ASCII character '\xdb' in file ./release.py on line 273, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details If I follow the instructions at the given website, and place utf-8 on the second line encoding, my script doesn't run. Instead it gives me this error: SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xdb in position 0: unexpected end of data How do I get this one regular expression running in an ASCII written script that'd be great.
[ "You need to find out what encoding your editor is using, and set that per PEP263; or, make things more stable and portable (though alas perhaps a bit less readable) and use escape sequences in your string literal, i.e., use u'(\\xdb|\\xb2|\\xb0|\\xb1|\\xc9|\\xb9|\\xcd)' as the parameter to the re.compile call.\n", "After telling Python that your source file uses UTF-8 encoding, did you actually make sure that your editor is saving the file using UTF-8 encoding? The error you get indicates that your editor is probably not using UTF-8.\nWhat text editor are you using?\n", "\\x{c0de}\n\nIn a regex will match the Unicode character at code point c0de.\nPython uses PCRE, right? (If it doesn't, it's probably \\uC0DE instead...)\n" ]
[ 3, 1, 0 ]
[]
[]
[ "ascii", "python", "regex", "unicode" ]
stackoverflow_0002039650_ascii_python_regex_unicode.txt
Q: Django instance start under Google App Engine After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the app-engine-patch FAQ that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. Do you agree with this? Do you have any other approach? Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue. Help! A: Yes, long startup times are a caveat of using a framework with a lot of code. There's no way around them, currently, other than using a framework that is lighter-weight (such as the built in webapp framework). Polling your app isn't recommended: It'll use up quota, and doesn't actually guarantee that the real user requests hit the same instance your polling requests did, since apps run on multiple instances. Fortunately, there's a simple solution: Get popular! The more popular your app is, the less frequently instances need restarting, and the smaller a proportion of users it affects. A: I respect what you are trying to do, but this sounds a little like pre-mature optimization to me. The py+django patch you are discussing is recommended by Google until they upgrade to "real" django so I can't imagine it's all that bad. It's also not that hard to test the performance of what you are talking about, so I suggest you do that and run a few metrics on it first before making your final decision. That way you'll have some math to back it up when someone else starts complaining ;) A: They also mention in the FAQ that using a zipped version of Django will help the load time, although I'm guessing it might still be long. As for your original question, I'd agree with others that polling your app is probably not a good idea because it likely won't solve your problem because Google may distribute your requests across many machines, etc, etc. A: Also, it seems to me (but Nick can correct me here if I'm wrong) that if you use the built in Django (.97 or 1.0) the loading is less of a problem. Logically, I'd say they keep the built-in libs in memory for everyone, or share that cached code between instances. But I don't know for sure. A: See Takashi Matsuo's comparisons. Basically, for simplest app-engine-patch that does almost nothing, he claims about ~1s versus ~350ms for webapp+Django templates. It feels like longer than 1s for our app, but Takashi just tried the very simplest app he could think of.
Django instance start under Google App Engine
After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the app-engine-patch FAQ that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. Do you agree with this? Do you have any other approach? Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue. Help!
[ "Yes, long startup times are a caveat of using a framework with a lot of code. There's no way around them, currently, other than using a framework that is lighter-weight (such as the built in webapp framework).\nPolling your app isn't recommended: It'll use up quota, and doesn't actually guarantee that the real user requests hit the same instance your polling requests did, since apps run on multiple instances.\nFortunately, there's a simple solution: Get popular! The more popular your app is, the less frequently instances need restarting, and the smaller a proportion of users it affects.\n", "I respect what you are trying to do, but this sounds a little like pre-mature optimization to me. The py+django patch you are discussing is recommended by Google until they upgrade to \"real\" django so I can't imagine it's all that bad. It's also not that hard to test the performance of what you are talking about, so I suggest you do that and run a few metrics on it first before making your final decision. That way you'll have some math to back it up when someone else starts complaining ;)\n", "They also mention in the FAQ that using a zipped version of Django will help the load time, although I'm guessing it might still be long. As for your original question, I'd agree with others that polling your app is probably not a good idea because it likely won't solve your problem because Google may distribute your requests across many machines, etc, etc.\n", "Also, it seems to me (but Nick can correct me here if I'm wrong) that if you use the built in Django (.97 or 1.0) the loading is less of a problem. Logically, I'd say they keep the built-in libs in memory for everyone, or share that cached code between instances. But I don't know for sure.\n", "See Takashi Matsuo's comparisons. Basically, for simplest app-engine-patch that does almost nothing, he claims about ~1s versus ~350ms for webapp+Django templates.\nIt feels like longer than 1s for our app, but Takashi just tried the very simplest app he could think of.\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "app_engine_patch", "django", "google_app_engine", "google_app_engine_patch", "python" ]
stackoverflow_0001481942_app_engine_patch_django_google_app_engine_google_app_engine_patch_python.txt
Q: How do I make these Perl regexs Python compatible? I have these two lines in an old Perl script. When I write the Python equivalent I get all sorts of errors like valueerror: invalid \x escape, and stuff about encoding. $line =~ s/[^\x{8}-\x{7B}]/ /ig; $line =~ s/(Û|²|°|±|É|¹|Í)/ /g; What do I need to do to get them working in Python? A: I'm not too great with Perl regex but I think I may have solved it: invalid_range = re.compile(r'[^\x08-\x7B]', re.I) invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)') line = re.sub(invalid_range , '', line) line = re.sub(invalid_unicode, '', line) A: For encoding issues, if you want to put Unicode characters in your source directly, you'll need to make sure the Python interpreter knows what your file encoding is. See: Python docs—Encoding Declarations PEP 263 PEP 3120
How do I make these Perl regexs Python compatible?
I have these two lines in an old Perl script. When I write the Python equivalent I get all sorts of errors like valueerror: invalid \x escape, and stuff about encoding. $line =~ s/[^\x{8}-\x{7B}]/ /ig; $line =~ s/(Û|²|°|±|É|¹|Í)/ /g; What do I need to do to get them working in Python?
[ "I'm not too great with Perl regex but I think I may have solved it:\ninvalid_range = re.compile(r'[^\\x08-\\x7B]', re.I)\ninvalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)')\nline = re.sub(invalid_range , '', line)\nline = re.sub(invalid_unicode, '', line)\n\n", "For encoding issues, if you want to put Unicode characters in your source directly, you'll need to make sure the Python interpreter knows what your file encoding is. See:\n\nPython docs—Encoding Declarations\nPEP 263\nPEP 3120\n\n" ]
[ 1, 0 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0002039100_perl_python_regex.txt
Q: media conversion library I am building a mobile website were users can upload/download videos, and I need a library that can convert the media files from mpeg, 3gp, mov depending on what the user wants to download. Do you happen to know a a library that can do this? A: You should not only search for Library to do this, if you are using linux you can find an application that do this for you with CLI support,then using that application cli you can change your format; $result=shell_exec('application_name [parameters] input-file output-file') for example you can use ffmpeg $result=shell_exec('ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg') A: ffdshow is a great lib for that. libavcodec to be more precise. A: Use FFmpeg gem in Ruby, it's really cool and easy to use. A: Or if you want something to use directly from Java, try Xuggler, a Java-based interface to FFmpeg.
media conversion library
I am building a mobile website were users can upload/download videos, and I need a library that can convert the media files from mpeg, 3gp, mov depending on what the user wants to download. Do you happen to know a a library that can do this?
[ "You should not only search for Library to do this, if you are using linux you can find an application that do this for you with CLI support,then using that application cli you can change your format;\n$result=shell_exec('application_name [parameters] input-file output-file')\n\nfor example you can use ffmpeg\n$result=shell_exec('ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg')\n\n", "ffdshow is a great lib for that. \nlibavcodec to be more precise.\n", "Use FFmpeg gem in Ruby, it's really cool and easy to use.\n", "Or if you want something to use directly from Java, try Xuggler, a Java-based interface to FFmpeg.\n" ]
[ 2, 1, 1, 0 ]
[ "Take a look at FFmpeg. You could use as a command line tool.\n", "In the past, I ran VLC from the command-line and used it to do my conversions (it's free, supports nearly all audio and video formats, and works on many different platforms). If you have VLC installed on the server, you can access it this way using any language that has a system() command or equivalent.\n" ]
[ -1, -1 ]
[ ".net", "java", "php", "python", "ruby" ]
stackoverflow_0001999641_.net_java_php_python_ruby.txt
Q: Python: Why can't I get my decorator to work? This works now for those new to this question: class ensureparams(object): """ Used as a decorator with an iterable passed in, this will look for each item in the iterable given as a key in the params argument of the function being decorated. It was built for a series of PayPal methods that require different params, and AOP was the best way to handle it while staying DRY. >>> @ensureparams(['name', 'pass', 'code']) ... def complex_function(params): ... print(params['name']) ... print(params['pass']) ... print(params['code']) >>> >>> params = { ... 'name': 'John Doe', ... 'pass': 'OpenSesame', ... #'code': '1134', ... } >>> >>> complex_function(params=params) Traceback (most recent call last): ... ValueError: Missing from "params" dictionary in "complex_function": code """ def __init__(self, required): self.required = set(required) def __call__(self, func): def wrapper(*args, **kwargs): if not kwargs.get('params', None): raise KeyError('"params" kwarg required for {0}'.format(func.__name__)) missing = self.required.difference(kwargs['params']) if missing: raise ValueError('Missing from "params" dictionary in "{0}": {1}'.format(func.__name__, ', '.join(sorted(missing)))) return func(*args, **kwargs) return wrapper if __name__ == "__main__": import doctest doctest.testmod() A: def wrapper(params): means you're only going to accept one argument -- and so of course calls with (self, params) just won't work. You need to be able to accept either one or two arguments, e.g., at the very least (if you don't need to support calls w/named args): def wrapper(one, two=None): if two is None: params = one else: params = two # and the rest as above You can get much more complex / sophisticated in order to also accept named arguments, but this is much simpler and still "mostly works";-). A: Decorators normally look like this: def wrapper(*args, **kargs): # Pull what you need out of the argument lists and do stuff with it func(*args, **kargs) Then they work with any function passed to them, not just functions with a specific number of arguments or with specific keyword arguments. In this specific case, you may want to do some introspection on the func passed to __call__ to find out if it's a one or two argument function and to make sure the last argument is called 'params'. Then just write wrapper like this: def wrapper(*args): params = args[-1] missing = self.required.difference(params) if missing: raise ValueError('Missing from "params" argument: %s' % ', '.join(sorted(missing))) func(params) A: What I did was add *args, **kwargs, and just check for the keys that are required within the 'params' argument via kwargs['params'] after checking that kwargs params exists. Here's the new version (which works perfectly): class requiresparams(object): """ Used as a decorator with an iterable passed in, this will look for each item in the iterable given as a key in the params argument of the function being decorated. It was built for a series of PayPal methods that require different params, and AOP was the best way to handle it while staying DRY. >>> @requiresparams(['name', 'pass', 'code']) ... def complex_function(params): ... print(params['name']) ... print(params['pass']) ... print(params['code']) >>> >>> params = { ... 'name': 'John Doe', ... 'pass': 'OpenSesame', ... #'code': '1134', ... } >>> >>> complex_function(params=params) Traceback (most recent call last): ... ValueError: Missing from "params" dictionary: code """ def __init__(self, required): self.required = set(required) def __call__(self, func): def wrapper(*args, **kwargs): if not kwargs.get('params', None): raise KeyError('"params" kwarg required for {0}'.format(func.__name__)) missing = self.required.difference(kwargs['params']) if missing: raise ValueError('Missing from "params" dictionary: %s' % ', '.join(sorted(missing))) return func(*args, **kwargs) return wrapper if __name__ == "__main__": import doctest doctest.testmod()
Python: Why can't I get my decorator to work?
This works now for those new to this question: class ensureparams(object): """ Used as a decorator with an iterable passed in, this will look for each item in the iterable given as a key in the params argument of the function being decorated. It was built for a series of PayPal methods that require different params, and AOP was the best way to handle it while staying DRY. >>> @ensureparams(['name', 'pass', 'code']) ... def complex_function(params): ... print(params['name']) ... print(params['pass']) ... print(params['code']) >>> >>> params = { ... 'name': 'John Doe', ... 'pass': 'OpenSesame', ... #'code': '1134', ... } >>> >>> complex_function(params=params) Traceback (most recent call last): ... ValueError: Missing from "params" dictionary in "complex_function": code """ def __init__(self, required): self.required = set(required) def __call__(self, func): def wrapper(*args, **kwargs): if not kwargs.get('params', None): raise KeyError('"params" kwarg required for {0}'.format(func.__name__)) missing = self.required.difference(kwargs['params']) if missing: raise ValueError('Missing from "params" dictionary in "{0}": {1}'.format(func.__name__, ', '.join(sorted(missing)))) return func(*args, **kwargs) return wrapper if __name__ == "__main__": import doctest doctest.testmod()
[ "def wrapper(params): means you're only going to accept one argument -- and so of course calls with (self, params) just won't work. You need to be able to accept either one or two arguments, e.g., at the very least (if you don't need to support calls w/named args):\ndef wrapper(one, two=None):\n if two is None: params = one\n else: params = two\n # and the rest as above\n\nYou can get much more complex / sophisticated in order to also accept named arguments, but this is much simpler and still \"mostly works\";-).\n", "Decorators normally look like this:\ndef wrapper(*args, **kargs):\n # Pull what you need out of the argument lists and do stuff with it\n func(*args, **kargs)\n\nThen they work with any function passed to them, not just functions with a specific number of arguments or with specific keyword arguments. In this specific case, you may want to do some introspection on the func passed to __call__ to find out if it's a one or two argument function and to make sure the last argument is called 'params'. Then just write wrapper like this:\ndef wrapper(*args):\n params = args[-1]\n missing = self.required.difference(params)\n if missing:\n raise ValueError('Missing from \"params\" argument: %s' % ', '.join(sorted(missing)))\n func(params)\n\n", "What I did was add *args, **kwargs, and just check for the keys that are required within the 'params' argument via kwargs['params'] after checking that kwargs params exists.\nHere's the new version (which works perfectly):\nclass requiresparams(object):\n \"\"\"\n\n Used as a decorator with an iterable passed in, this will look for each item\n in the iterable given as a key in the params argument of the function being\n decorated. It was built for a series of PayPal methods that require\n different params, and AOP was the best way to handle it while staying DRY.\n\n\n >>> @requiresparams(['name', 'pass', 'code'])\n ... def complex_function(params):\n ... print(params['name'])\n ... print(params['pass'])\n ... print(params['code'])\n >>> \n >>> params = {\n ... 'name': 'John Doe',\n ... 'pass': 'OpenSesame',\n ... #'code': '1134',\n ... }\n >>> \n >>> complex_function(params=params)\n Traceback (most recent call last):\n ...\n ValueError: Missing from \"params\" dictionary: code\n \"\"\"\n def __init__(self, required):\n self.required = set(required)\n\n def __call__(self, func):\n def wrapper(*args, **kwargs):\n if not kwargs.get('params', None):\n raise KeyError('\"params\" kwarg required for {0}'.format(func.__name__))\n missing = self.required.difference(kwargs['params'])\n if missing:\n raise ValueError('Missing from \"params\" dictionary: %s' % ', '.join(sorted(missing)))\n return func(*args, **kwargs)\n return wrapper\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n" ]
[ 2, 2, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002039699_decorator_python.txt
Q: Django One-To-Many Models The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model? class Vuln(models.Model): pub_date = models.DateTimeField("Publication Date") short_description = models.CharField("Description", max_length=70) reference_urls = models.ForeignKey(Url, unique=True, blank=True, verbose_name="Reference URLs") vendor = models.ForeignKey(Vendor, verbose_name="Vendor") class Url(models.Model): url = models.URLField("URL", max_length=200) The Admin application gives a 'select' box for the reference URLs, which isn't what I want. When I add a new vulnerability object, all of the existing URLs that have been entered show up in that dropdown, which is again unnatural. I feel like this should behave very similar to how a blog comment would, ie. the comment applies to a single blog entry and none other and that one blog entry may have many comments. How do I express this in a Django model? A: It should be more like this: class Vuln(models.Model): pub_date = models.DateTimeField("Publication Date") short_description = models.CharField("Description", max_length=70) vendor = models.ForeignKey(Vendor, verbose_name="Vendor") class Url(models.Model): url = models.URLField("URL", max_length=200) vulnerability = models.ForeignKey(Vuln) If you're saying each Url talks about a specific vulnerability, then there is your relation in the Django DBM :) As for the vendor field, you simply add another class, much like Class Vuln. For example: class Vendor(models.Model): field_names_go_here = models.TextField(max_length=70) short_description = models.CharField("Description", max_length=70) Hope this helps! Regards, Alex
Django One-To-Many Models
The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model? class Vuln(models.Model): pub_date = models.DateTimeField("Publication Date") short_description = models.CharField("Description", max_length=70) reference_urls = models.ForeignKey(Url, unique=True, blank=True, verbose_name="Reference URLs") vendor = models.ForeignKey(Vendor, verbose_name="Vendor") class Url(models.Model): url = models.URLField("URL", max_length=200) The Admin application gives a 'select' box for the reference URLs, which isn't what I want. When I add a new vulnerability object, all of the existing URLs that have been entered show up in that dropdown, which is again unnatural. I feel like this should behave very similar to how a blog comment would, ie. the comment applies to a single blog entry and none other and that one blog entry may have many comments. How do I express this in a Django model?
[ "It should be more like this:\nclass Vuln(models.Model): \n pub_date = models.DateTimeField(\"Publication Date\") \n short_description = models.CharField(\"Description\", max_length=70)\n vendor = models.ForeignKey(Vendor, verbose_name=\"Vendor\") \n\nclass Url(models.Model): \n url = models.URLField(\"URL\", max_length=200)\n vulnerability = models.ForeignKey(Vuln)\n\nIf you're saying each Url talks about a specific vulnerability, then there is your relation in the Django DBM :)\nAs for the vendor field, you simply add another class, much like Class Vuln. For example:\nclass Vendor(models.Model): \n field_names_go_here = models.TextField(max_length=70)\n short_description = models.CharField(\"Description\", max_length=70)\n\nHope this helps!\nRegards, Alex\n" ]
[ 23 ]
[]
[]
[ "django", "model", "one_to_many", "python" ]
stackoverflow_0002039958_django_model_one_to_many_python.txt
Q: Model form is crashing on a foreign key in django So I'm trying to create a new feed within the Admin page and its crashing with the error IntegrityError: lifestream_feed.lifestream_id may not be NULL, form['lifestream'] is set but form.instance.lifestream is not. form.fields even shows that lifestream is a django.forms.models.ModelChoiceField Here is the code: class FeedCreationForm(forms.ModelForm): class Meta: model = Feed exclude = ['name', 'domain', 'fetchable'] def parse_feed(self, feed_url): feed = feedparser.parse(feed_url) # Does the feed have errors if feed['bozo']: if feed['feed'].has_key("links"): for link in feed['feed']['links']: if link["type"] == "application/rss+xml": feed = self.parse_feed(link['href']) if not feed['bozo']: return feed else: return feed return None def clean(self): """ Checks to make sure a feed url is valid and gets the feed title and domain. """ feed_url = self.cleaned_data.get('url') if not feed_url: # Feed url was not validated by the field validator return feed = self.parse_feed(feed_url) if feed: feed_url = feed['url'] self.cleaned_data['url'] = feed_url else: # the feed was not parsed correctly. import logging self._errors['url'] = ErrorList(["This is not a valid feed: %s" % feed['bozo_exception']]) logging.error(feed['bozo_exception']) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return # Check if the feed has a title field feed_info = feed.get('feed') if not feed_info.get('title'): self._errors['url'] = ErrorList(["This is not a valid feed: The feed is empty"]) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return self.cleaned_data['name'] = feed_info['title'] self.instance.name = self.cleaned_data['name'] self.cleaned_data['domain'] = get_url_domain(feed_url) self.instance.domain = self.cleaned_data['domain'] return self.cleaned_data class FeedAdmin(admin.ModelAdmin): list_display = ('name', 'lifestream', 'domain', 'fetchable') list_filter = ('domain', 'lifestream') actions = ['make_fetchable', 'make_unfetchable'] add_form = FeedCreationForm model = Feed def make_unfetchable(self, request, queryset): queryset.update(fetchable=False) make_unfetchable.short_description = _(u"Mark as unfetchable") def make_fetchable(self, request, queryset): queryset.update(fetchable=True) make_fetchable.short_description = _(u"Mark as fetchable") def add_view(self, request): if not self.has_change_permission(request): raise PermissionDenied if request.method == 'POST': form = self.add_form(request.POST) if form.is_valid(): new_feed = form.save() msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_feed} self.log_addition(request, new_feed) if "_addanother" in request.POST: request.user.message_set.create(message=msg) return HttpResponseRedirect(request.path) elif '_popup' in request.REQUEST: return self.response_add(request, new_feed) else: request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below.")) # TODO: use reversed url return HttpResponseRedirect('../%s/' % new_feed.id) else: form = self.add_form() return render_to_response('admin/lifestream/feed/ add_form.html', { 'title': _('Add feed'), 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_add_permission': True, 'has_delete_permission': False, 'has_change_permission': True, 'has_file_field': False, 'has_absolute_url': False, 'auto_populated_fields': (), 'opts': self.model._meta, 'save_as': False, #'username_help_text': self.model._meta.get_field ('username').help_text, 'root_path': self.admin_site.root_path, 'app_label': self.model._meta.app_label, }, context_instance=template.RequestContext(request)) def queryset(self, request): return self.model.objects.feeds() admin.site.register(Feed, FeedAdmin) class Lifestream(models.Model): """ A lifestream. Lifestreams can be created per user. """ site = models.ForeignKey(Site, verbose_name=_(u"site")) user = models.ForeignKey(User, verbose_name=_(u"user")) slug = models.SlugField(_("slug"), help_text=_('Slug for use in urls (Autopopulated from the title).'), blank=True) title = models.CharField(_("title"), max_length=255) def __unicode__(self): return self.title class FeedManager(models.Manager): ''' Query only normal feeds. ''' def feeds(self): return super(FeedManager, self).get_query_set() def fetchable(self): return self.feeds().filter(fetchable=True) class Feed(models.Model): '''A feed for gathering data.''' lifestream = models.ForeignKey(Lifestream, verbose_name=_ ('lifestream')) name = models.CharField(_("feed name"), max_length=255) url = models.URLField(_("feed url"), help_text=_("Must be a valid url."), verify_exists=True, max_length=1000) domain = models.CharField(_("feed domain"), max_length=255) fetchable = models.BooleanField(_("fetchable"), default=True) # The feed plugin name used to process the incoming feed data. plugin_class_name = models.CharField(_("plugin name"), max_length=255, null=True, blank=True, choices=getattr(settings, "PLUGINS", PLUGINS)) objects = FeedManager() def __unicode__(self): return self.name Its not returning the empty returns, its reaching the return self.cleaned_data: -> return self.cleaned_data (Pdb) list 85 self.cleaned_data['name'] = feed_info['title'] 86 self.instance.name = self.cleaned_data['name'] 87 self.cleaned_data['domain'] = get_url_domain(feed_url) 88 self.instance.domain = self.cleaned_data['domain'] 89 90 -> return self.cleaned_data 91 92 class FeedAdmin(admin.ModelAdmin): 93 list_display = ('name', 'lifestream', 'domain', 'fetchable') 94 list_filter = ('domain', 'lifestream') 95 actions = ['make_fetchable', 'make_unfetchable'] (Pdb) self.cleaned_data {'url': u'http://twitter.com/statuses/user_timeline/6166742.rss', 'domain': u'twitter.com', 'lifestream': <Lifestream: Social>, 'name': u'Twitter / sontek', 'plugin_class_name': u'lifestream.plugins.twitter.TwitterPlugin'} A: I believe the problem is in your clean() method. The general clean() method (as opposed to field specific clean methods like clean_domain()) must return the cleaned_data dictionary (minus any fields which do not validate), and you have at least 3 returns in your clean method that do not return anything. See here A: Turns out this is a bug in HEAD of django
Model form is crashing on a foreign key in django
So I'm trying to create a new feed within the Admin page and its crashing with the error IntegrityError: lifestream_feed.lifestream_id may not be NULL, form['lifestream'] is set but form.instance.lifestream is not. form.fields even shows that lifestream is a django.forms.models.ModelChoiceField Here is the code: class FeedCreationForm(forms.ModelForm): class Meta: model = Feed exclude = ['name', 'domain', 'fetchable'] def parse_feed(self, feed_url): feed = feedparser.parse(feed_url) # Does the feed have errors if feed['bozo']: if feed['feed'].has_key("links"): for link in feed['feed']['links']: if link["type"] == "application/rss+xml": feed = self.parse_feed(link['href']) if not feed['bozo']: return feed else: return feed return None def clean(self): """ Checks to make sure a feed url is valid and gets the feed title and domain. """ feed_url = self.cleaned_data.get('url') if not feed_url: # Feed url was not validated by the field validator return feed = self.parse_feed(feed_url) if feed: feed_url = feed['url'] self.cleaned_data['url'] = feed_url else: # the feed was not parsed correctly. import logging self._errors['url'] = ErrorList(["This is not a valid feed: %s" % feed['bozo_exception']]) logging.error(feed['bozo_exception']) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return # Check if the feed has a title field feed_info = feed.get('feed') if not feed_info.get('title'): self._errors['url'] = ErrorList(["This is not a valid feed: The feed is empty"]) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return self.cleaned_data['name'] = feed_info['title'] self.instance.name = self.cleaned_data['name'] self.cleaned_data['domain'] = get_url_domain(feed_url) self.instance.domain = self.cleaned_data['domain'] return self.cleaned_data class FeedAdmin(admin.ModelAdmin): list_display = ('name', 'lifestream', 'domain', 'fetchable') list_filter = ('domain', 'lifestream') actions = ['make_fetchable', 'make_unfetchable'] add_form = FeedCreationForm model = Feed def make_unfetchable(self, request, queryset): queryset.update(fetchable=False) make_unfetchable.short_description = _(u"Mark as unfetchable") def make_fetchable(self, request, queryset): queryset.update(fetchable=True) make_fetchable.short_description = _(u"Mark as fetchable") def add_view(self, request): if not self.has_change_permission(request): raise PermissionDenied if request.method == 'POST': form = self.add_form(request.POST) if form.is_valid(): new_feed = form.save() msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_feed} self.log_addition(request, new_feed) if "_addanother" in request.POST: request.user.message_set.create(message=msg) return HttpResponseRedirect(request.path) elif '_popup' in request.REQUEST: return self.response_add(request, new_feed) else: request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below.")) # TODO: use reversed url return HttpResponseRedirect('../%s/' % new_feed.id) else: form = self.add_form() return render_to_response('admin/lifestream/feed/ add_form.html', { 'title': _('Add feed'), 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_add_permission': True, 'has_delete_permission': False, 'has_change_permission': True, 'has_file_field': False, 'has_absolute_url': False, 'auto_populated_fields': (), 'opts': self.model._meta, 'save_as': False, #'username_help_text': self.model._meta.get_field ('username').help_text, 'root_path': self.admin_site.root_path, 'app_label': self.model._meta.app_label, }, context_instance=template.RequestContext(request)) def queryset(self, request): return self.model.objects.feeds() admin.site.register(Feed, FeedAdmin) class Lifestream(models.Model): """ A lifestream. Lifestreams can be created per user. """ site = models.ForeignKey(Site, verbose_name=_(u"site")) user = models.ForeignKey(User, verbose_name=_(u"user")) slug = models.SlugField(_("slug"), help_text=_('Slug for use in urls (Autopopulated from the title).'), blank=True) title = models.CharField(_("title"), max_length=255) def __unicode__(self): return self.title class FeedManager(models.Manager): ''' Query only normal feeds. ''' def feeds(self): return super(FeedManager, self).get_query_set() def fetchable(self): return self.feeds().filter(fetchable=True) class Feed(models.Model): '''A feed for gathering data.''' lifestream = models.ForeignKey(Lifestream, verbose_name=_ ('lifestream')) name = models.CharField(_("feed name"), max_length=255) url = models.URLField(_("feed url"), help_text=_("Must be a valid url."), verify_exists=True, max_length=1000) domain = models.CharField(_("feed domain"), max_length=255) fetchable = models.BooleanField(_("fetchable"), default=True) # The feed plugin name used to process the incoming feed data. plugin_class_name = models.CharField(_("plugin name"), max_length=255, null=True, blank=True, choices=getattr(settings, "PLUGINS", PLUGINS)) objects = FeedManager() def __unicode__(self): return self.name Its not returning the empty returns, its reaching the return self.cleaned_data: -> return self.cleaned_data (Pdb) list 85 self.cleaned_data['name'] = feed_info['title'] 86 self.instance.name = self.cleaned_data['name'] 87 self.cleaned_data['domain'] = get_url_domain(feed_url) 88 self.instance.domain = self.cleaned_data['domain'] 89 90 -> return self.cleaned_data 91 92 class FeedAdmin(admin.ModelAdmin): 93 list_display = ('name', 'lifestream', 'domain', 'fetchable') 94 list_filter = ('domain', 'lifestream') 95 actions = ['make_fetchable', 'make_unfetchable'] (Pdb) self.cleaned_data {'url': u'http://twitter.com/statuses/user_timeline/6166742.rss', 'domain': u'twitter.com', 'lifestream': <Lifestream: Social>, 'name': u'Twitter / sontek', 'plugin_class_name': u'lifestream.plugins.twitter.TwitterPlugin'}
[ "I believe the problem is in your clean() method.\nThe general clean() method (as opposed to field specific clean methods like clean_domain()) must return the cleaned_data dictionary (minus any fields which do not validate), and you have at least 3 returns in your clean method that do not return anything.\nSee here\n", "Turns out this is a bug in HEAD of django\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0002038621_django_django_forms_django_models_python.txt
Q: Sorting datetime objects while ignoring the year? I have a list of birthdays stored in datetime objects. How would one go about sorting these in Python using only the month and day arguments? For example, [ datetime.datetime(1983, 1, 1, 0, 0) datetime.datetime(1996, 1, 13, 0 ,0) datetime.datetime(1976, 2, 6, 0, 0) ... ] Thanks! :) A: You can use month and day to create a value that can be used for sorting: birthdays.sort(key = lambda d: (d.month, d.day)) A: l.sort(key = lambda x: x.timetuple()[1:3]) A: If the dates are stored as strings—you say they aren't, although it looks like they are—you might use dateutil's parser: >>> from dateutil.parser import parse >>> from pprint import pprint >>> bd = ['February 6, 1976','January 13, 1996','January 1, 1983'] >>> bd = [parse(i) for i in bd] >>> pprint(bd) [datetime.datetime(1976, 2, 6, 0, 0), datetime.datetime(1996, 1, 13, 0, 0), datetime.datetime(1983, 1, 1, 0, 0)] >>> bd.sort(key = lambda d: (d.month, d.day)) # from sth's answer >>> pprint(bd) [datetime.datetime(1983, 1, 1, 0, 0), datetime.datetime(1996, 1, 13, 0, 0), datetime.datetime(1976, 2, 6, 0, 0)] If your dates are in different formats, you might give fuzzy parsing a shot: >>> bd = [parse(i,fuzzy=True) for i in bd] # replace line 4 above with this line
Sorting datetime objects while ignoring the year?
I have a list of birthdays stored in datetime objects. How would one go about sorting these in Python using only the month and day arguments? For example, [ datetime.datetime(1983, 1, 1, 0, 0) datetime.datetime(1996, 1, 13, 0 ,0) datetime.datetime(1976, 2, 6, 0, 0) ... ] Thanks! :)
[ "You can use month and day to create a value that can be used for sorting:\nbirthdays.sort(key = lambda d: (d.month, d.day))\n\n", "l.sort(key = lambda x: x.timetuple()[1:3])\n\n", "If the dates are stored as strings—you say they aren't, although it looks like they are—you might use dateutil's parser:\n>>> from dateutil.parser import parse\n>>> from pprint import pprint\n>>> bd = ['February 6, 1976','January 13, 1996','January 1, 1983']\n>>> bd = [parse(i) for i in bd]\n>>> pprint(bd)\n[datetime.datetime(1976, 2, 6, 0, 0), \n datetime.datetime(1996, 1, 13, 0, 0), \n datetime.datetime(1983, 1, 1, 0, 0)]\n>>> bd.sort(key = lambda d: (d.month, d.day)) # from sth's answer\n>>> pprint(bd)\n[datetime.datetime(1983, 1, 1, 0, 0),\n datetime.datetime(1996, 1, 13, 0, 0),\n datetime.datetime(1976, 2, 6, 0, 0)]\n\nIf your dates are in different formats, you might give fuzzy parsing a shot:\n>>> bd = [parse(i,fuzzy=True) for i in bd] # replace line 4 above with this line\n\n" ]
[ 13, 7, 3 ]
[]
[]
[ "datetime", "python", "sorting" ]
stackoverflow_0002040038_datetime_python_sorting.txt
Q: Python JPype integration I am using JPype The following is the code i am trying to use from jpype import * startJVM("C:\Program Files\Java\jdk1.6.0_14\jre\bin\client\jvm.dll","-ea") java.lang.System.out.println("hai") shutdownJVM() It is giving error in the execution of the println statement java.lang.System.out.println("hai") File "<stdin>", line 1 java.lang.System.out.println("hai") ^ SyntaxError: invalid syntax
Python JPype integration
I am using JPype The following is the code i am trying to use from jpype import * startJVM("C:\Program Files\Java\jdk1.6.0_14\jre\bin\client\jvm.dll","-ea") java.lang.System.out.println("hai") shutdownJVM() It is giving error in the execution of the println statement java.lang.System.out.println("hai") File "<stdin>", line 1 java.lang.System.out.println("hai") ^ SyntaxError: invalid syntax
[]
[]
[ "Firstly, are all the dependencies setup correctly? Java, Python, JPype etc?\nYou are trying to execute one of the first examples in the documentation.\nThe sample they provide in the docs are:\nfrom jpype import * \nstartJVM(\"d:/tools/j2sdk/jre/bin/client/jvm.dll\", \"-ea\") \njava.lang.System.out.println(\"hello world\") \nshutdownJVM()\n\nOne of the main differences is that you are using \\ as a path separator. As per the docs, maybe try a /.\n", "Looks like you might just be missing a semicolon (;)\n" ]
[ -1, -2 ]
[ "java", "jpype", "python" ]
stackoverflow_0002040104_java_jpype_python.txt
Q: Install Plone egg as a Python module on Windows I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buildout would allow me to easily add Grufspaces (collective.groupspace.roles etc) as a Product. I have downloaded the egg files separately (roles, workflow, mail, content) and placed them in a directory structure like so: collective/ __init__.py groupspace/ __init__.py content/... roles/... workflow/… mail/... What I thought I could do is add this "collective" folder to [plone directory]/Zope/lib/python as a Python module. The idea being once its added I can restart Plone/Zope and it will automatically pick it up and make it available within Plone as a Python Module. Unfortunately it has not worked as of yet. If I am going about this the wrong way I welcome any suggestion to try this a different way. A: Did you check GrufSpaces' INSTALL.TXT? From there: Unpack it into your Zope Products Folder For Plone, the easiest way is probably to unpack it the top level products folder. See also http://plone.org/documentation/kb/third-party-products/installing, section "Installing Zope 2-style Products Without Buildout". A: If you are trying to install GrufSpaces 2.0 then you should consider upgrading to Plone 3.3 (see the install requirements) Placing the collective.* packages to [plone directory]/Zope/lib/python should work. But these packages are not compatible with Plone 3.1. Here is the example of ImportError that I get when using collective.groupspace.roles with Plone 3.1: File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/roles.py", line 23, in ? from plone.app.workflow import PloneMessageFactory as _ zope.configuration.xmlconfig.ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/etc/site.zcml", line 15.2-15.23 ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/Products/GrufSpaces/configure.zcml", line 17.4-17.53 ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/configure.zcml", line 7.4-7.34 ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/configure.zcml", line 5.4-10.10 ImportError: cannot import name PloneMessageFactory Besides collective.* packages you have to download GrufSpaces product from SVN (download link at plone.org doesn't work for me) and place it in Products folder. A: No advice specific to GruffSpaces as I've never used it but it sounds like you may be under the mistaken impression that you need Plone 3.2+ for buildout. This is incorrect. Buildout works just fine with Plone 3.1.2. I've also done buildouts for Plone 2.5.5 and even one for Plone 2.1 (although this last one was a bit tricky because the required python for that version doesn't do buildout). So if you prefer the buildout route, just do it. Although upgrading your Plone is probably still good advice.
Install Plone egg as a Python module on Windows
I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buildout would allow me to easily add Grufspaces (collective.groupspace.roles etc) as a Product. I have downloaded the egg files separately (roles, workflow, mail, content) and placed them in a directory structure like so: collective/ __init__.py groupspace/ __init__.py content/... roles/... workflow/… mail/... What I thought I could do is add this "collective" folder to [plone directory]/Zope/lib/python as a Python module. The idea being once its added I can restart Plone/Zope and it will automatically pick it up and make it available within Plone as a Python Module. Unfortunately it has not worked as of yet. If I am going about this the wrong way I welcome any suggestion to try this a different way.
[ "Did you check GrufSpaces' INSTALL.TXT? From there:\n\nUnpack it into your Zope Products Folder\n\nFor Plone, the easiest way is probably to unpack it the top level products folder.\nSee also http://plone.org/documentation/kb/third-party-products/installing, section \"Installing Zope 2-style Products Without Buildout\".\n", "If you are trying to install GrufSpaces 2.0 then you should consider upgrading to Plone 3.3 (see the install requirements)\nPlacing the collective.* packages to [plone directory]/Zope/lib/python should work. But these packages are not compatible with Plone 3.1. Here is the example of ImportError that I get when using collective.groupspace.roles with Plone 3.1:\n File \"/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/roles.py\", line 23, in ?\n from plone.app.workflow import PloneMessageFactory as _\nzope.configuration.xmlconfig.ZopeXMLConfigurationError: File \"/home/andrey/tmp/zope/instance/etc/site.zcml\", line 15.2-15.23\n ZopeXMLConfigurationError: File \"/home/andrey/tmp/zope/instance/Products/GrufSpaces/configure.zcml\", line 17.4-17.53\n ZopeXMLConfigurationError: File \"/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/configure.zcml\", line 7.4-7.34\n ZopeXMLConfigurationError: File \"/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/configure.zcml\", line 5.4-10.10\n ImportError: cannot import name PloneMessageFactory\n\nBesides collective.* packages you have to download GrufSpaces product from SVN (download link at plone.org doesn't work for me) and place it in Products folder.\n", "No advice specific to GruffSpaces as I've never used it but it sounds like you may be under the mistaken impression that you need Plone 3.2+ for buildout. This is incorrect. Buildout works just fine with Plone 3.1.2. I've also done buildouts for Plone 2.5.5 and even one for Plone 2.1 (although this last one was a bit tricky because the required python for that version doesn't do buildout).\nSo if you prefer the buildout route, just do it. Although upgrading your Plone is probably still good advice.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "plone", "plone_3.x", "python", "zope" ]
stackoverflow_0002029826_plone_plone_3.x_python_zope.txt
Q: Implementing USZipCodeField and USStateField in django I'm looking to implement a zipcode field in django using the form objects from localflavor, but not quite getting them to work. I want to have a zipcode field in a form (or ModelForm in my case), but the fields never validate as a zipcode when calling _get_errors() on the form object. The way I'm implementing it seems right to me but is apparently wrong, does anyone know what the right way to do this might be? I have a ModelForm that I want to use zipcode (and also USStateField) in: from django.contrib.localflavor.us.forms import USStateField from django.contrib.localflavor.us.forms import USZipCodeField class FooForm(ModelForm): class Meta: model = Bar fields = ('address', #This form uses a subset of fields from the model 'address_apt', 'address_city', 'address_state', 'address_zip', 'home_phone', 'mobile_phone') widgets= { 'address_zip' : USZipCodeField(), 'address_state' : USStateField(), } The ModelForm 'FooForm' links to a model that looks like: from django.contrib.localflavor.us import models as usmodels class Bar(models.Model): db_table = 'BAR' address = models.CharField(max_length=255) address_apt = models.CharField(max_length=40, blank=True) address_city = models.CharField(max_length=90) address_state = usmodels.USStateField() address_zip = models.CharField(max_length=15) home_phone = usmodels.PhoneNumberField( ) mobile_phone = usmodels.PhoneNumberField( ) #... There are more fields in the model... But if I create an instance of the form and run it's validation, it never cares about the form level validation, only the model level validation: foo_instance = FooForm(request.POST) #Let's assume request.POST looks like: #<QueryDict: {u'address_city': [u'asdf'], u'mobile_phone': [u'asdf'], u'address_state': [u'California'], u'home_phone': [u'asdf'], [u'1'], u'address': [u'123 foo'], u'address_zip': [u'asdf']}> foo_instance._get_errors() Yields: <ul class="errorlist"> <li>mobile_phone<ul class="errorlist"> <li>Phone numbers must be in XXX-XXX-XXXX format.</li></ul> </li><li>home_phone<ul class="errorlist"> <li>Phone numbers must be in XXX-XXX-XXXX format.</li></ul> </li></ul> I need to be able to call validation on the populated form object and have it tell me that the zipcode is formated improperly if so. Doing something wrong, just don't know what atm. A: Using widgets declaratively has literally only just been added to the trunk SVN version in the last day or so. If you're using an older checkout, or a released version, it won't work - you'll need to go back to the old way of doing it, by overriding the field declarations at the top level of the form.
Implementing USZipCodeField and USStateField in django
I'm looking to implement a zipcode field in django using the form objects from localflavor, but not quite getting them to work. I want to have a zipcode field in a form (or ModelForm in my case), but the fields never validate as a zipcode when calling _get_errors() on the form object. The way I'm implementing it seems right to me but is apparently wrong, does anyone know what the right way to do this might be? I have a ModelForm that I want to use zipcode (and also USStateField) in: from django.contrib.localflavor.us.forms import USStateField from django.contrib.localflavor.us.forms import USZipCodeField class FooForm(ModelForm): class Meta: model = Bar fields = ('address', #This form uses a subset of fields from the model 'address_apt', 'address_city', 'address_state', 'address_zip', 'home_phone', 'mobile_phone') widgets= { 'address_zip' : USZipCodeField(), 'address_state' : USStateField(), } The ModelForm 'FooForm' links to a model that looks like: from django.contrib.localflavor.us import models as usmodels class Bar(models.Model): db_table = 'BAR' address = models.CharField(max_length=255) address_apt = models.CharField(max_length=40, blank=True) address_city = models.CharField(max_length=90) address_state = usmodels.USStateField() address_zip = models.CharField(max_length=15) home_phone = usmodels.PhoneNumberField( ) mobile_phone = usmodels.PhoneNumberField( ) #... There are more fields in the model... But if I create an instance of the form and run it's validation, it never cares about the form level validation, only the model level validation: foo_instance = FooForm(request.POST) #Let's assume request.POST looks like: #<QueryDict: {u'address_city': [u'asdf'], u'mobile_phone': [u'asdf'], u'address_state': [u'California'], u'home_phone': [u'asdf'], [u'1'], u'address': [u'123 foo'], u'address_zip': [u'asdf']}> foo_instance._get_errors() Yields: <ul class="errorlist"> <li>mobile_phone<ul class="errorlist"> <li>Phone numbers must be in XXX-XXX-XXXX format.</li></ul> </li><li>home_phone<ul class="errorlist"> <li>Phone numbers must be in XXX-XXX-XXXX format.</li></ul> </li></ul> I need to be able to call validation on the populated form object and have it tell me that the zipcode is formated improperly if so. Doing something wrong, just don't know what atm.
[ "Using widgets declaratively has literally only just been added to the trunk SVN version in the last day or so. If you're using an older checkout, or a released version, it won't work - you'll need to go back to the old way of doing it, by overriding the field declarations at the top level of the form.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "localization", "python" ]
stackoverflow_0002039762_django_django_forms_django_models_localization_python.txt
Q: If I use QT For Windows, will my application run great on Linux/Mac/Windows? I'm under the impressions that Python runs in the Triforce smoothly. A program that runs in Windows will run in Linux. Is this sentiment correct? Having said that, if I create my application in QT For Windows, will it run flawlessly in Linux/Mac as well? Thanks. A: Yes. No. Maybe. See also: Java and "write once, run anywhere". Filesystem layout, external utilities, anything you might do with things like dock icons, character encoding behaviors, these and more are areas you might run into some trouble. Using Qt and Python, and strenuously avoiding anything that seems tied to Windows-specific libraries or behaviors whenever possible will make running the application on Mac and Linux much easier, but for any non-trivial application, the first time someone tries it, it will blow up in their face. But through careful choice of frameworks and libraries, making the application work cross-platform will be much more like bug fixing than traditional "porting". A: As other posters mentioned, the key issue is making sure you never touch a different non-Qt non-cross-platform API. Or really even a different non-Qt crossplatform API, if you use Qt you kind of need to commit to it, it's a comprehensive framework and for the most part sticking with Qt is easier than going to anything else. There's some nice advantages as the basic primitives in your program will work the same way all over the place. (i.e. a QString in your networking code will be the same as a QString in your interface code.) Portability-wise, if you stay within the API Qt provides you, it should work on multiple platforms. There will be areas where you may need to call some Qt functions which provide specific cross-platform tweaks more important to some platforms than others (e.g. dock icons) and you won't immediately have a polished application on all three platforms. But in general, you should remain very close to an application that compiles and runs on all three. (Try to use qmake or a similar build system too, as the build process for Qt applications varies depending on the platform. Different flags, etc.) There's some odd issues that come up when you mix Qt with other APIs like OpenGL, in particular the way windows locks GL contexts differs from the way OS X and Linux does, so if you intend to use OpenGL with multiple threads, try to periodically compile on the other platforms to make sure nothing is completely busted. This will also quickly point out areas where you might have inadvertently used a non-cross-platform system API. I've used Qt with a team to build a multi-threaded 3-d multiplayer real-time networked game (read: non-trivial application that fully utilized many many areas of Qt) and we were nothing but blown away by the effectiveness of Qt's ability to support multiple platforms. (We developed on OS X while targeting Windows and I regularly made sure it still ran on Linux as well.) We encountered only a few platform specific bugs, almost all of which arose from the use of non-Qt APIs such as OpenGL. (Which should really tell you something, that OpenGL was more of a struggle to use cross platform than Qt was.) At the end of the experience we were pleased at how little time we needed to spend dealing with platform-specific bugs. It was surprising how well we could make a GUI app for windows given almost none of the team actually used it as a primary development platform through the project. But do test early and often. I don't think your approach of writing an entire application and then testing is a good idea. It's possible with Qt, but unlikely if you don't have experience writing portable code and/or are new to Qt. A: Yes. The code that you write using Qt will work on Windows, Mac, Linux/X11, embedded Linux, Windows CE and Symbian without any change. You can take a look here. A: Generally - as long as you don't use code that is not covered by Qt classes - yes. I have several time just recompiled applications I wrote in Linux(64bit) under Windows, and the other way arround. It works for me every time. Depends on your needs, you might also find compiler problems, but I am sure you will know how to work around them. Other people mentioned some issues you should look for, just read the other posts in the question. A: It might run well, but it will take some testing, and of course Qt only handles the GUI portability, not the myriad of other things that might cause portability problems. Qt apps generally don't fit in very well on MacOS because they don't have Applescript support by default and don't necessarily have the right keybindings. But if you do the work to fix those issues, they work, but not nicely. On the Mac, it's far better to build a native UI. If this is an in-house app, Qt is probably OK, but if it's for sale, you won't make many sales and will create yourself some support hassles. A: As the others said, everything which is done using Qt-Functionality will most likely run quite flawlessly, WHEN you dont use platform specific functionality of qt. There isnt that much (most of it has to do with window-manager stuff) , but some things might not work on other systems. But such things are surely mentiond in the documentation of Qt. Still there are things which cant be done using Qt, so you will have to do that yourself using plain Python... Yeah "Python" itself is platform-independent (well it should), but there are lots of other things involved ... well mainly the OS. And how the OS reacts you will plainly have to findout yourself by testing the application on all target OS. Recently i wrote an quite simple GUI-application, while it ran flawlessy on Windows, it didnt run on Linux, because on Linux Python interpreted files encoded in unicode differently than on Windows. Additionally a small script which should return the hostname of the machine, which it did on Windows, only returned "localhost" on Linux, which was obviously not what i wanted.
If I use QT For Windows, will my application run great on Linux/Mac/Windows?
I'm under the impressions that Python runs in the Triforce smoothly. A program that runs in Windows will run in Linux. Is this sentiment correct? Having said that, if I create my application in QT For Windows, will it run flawlessly in Linux/Mac as well? Thanks.
[ "Yes. No. Maybe. See also: Java and \"write once, run anywhere\".\nFilesystem layout, external utilities, anything you might do with things like dock icons, character encoding behaviors, these and more are areas you might run into some trouble.\nUsing Qt and Python, and strenuously avoiding anything that seems tied to Windows-specific libraries or behaviors whenever possible will make running the application on Mac and Linux much easier, but for any non-trivial application, the first time someone tries it, it will blow up in their face.\nBut through careful choice of frameworks and libraries, making the application work cross-platform will be much more like bug fixing than traditional \"porting\".\n", "As other posters mentioned, the key issue is making sure you never touch a different non-Qt non-cross-platform API. Or really even a different non-Qt crossplatform API, if you use Qt you kind of need to commit to it, it's a comprehensive framework and for the most part sticking with Qt is easier than going to anything else. There's some nice advantages as the basic primitives in your program will work the same way all over the place. (i.e. a QString in your networking code will be the same as a QString in your interface code.) Portability-wise, if you stay within the API Qt provides you, it should work on multiple platforms.\nThere will be areas where you may need to call some Qt functions which provide specific cross-platform tweaks more important to some platforms than others (e.g. dock icons) and you won't immediately have a polished application on all three platforms. But in general, you should remain very close to an application that compiles and runs on all three. (Try to use qmake or a similar build system too, as the build process for Qt applications varies depending on the platform. Different flags, etc.)\nThere's some odd issues that come up when you mix Qt with other APIs like OpenGL, in particular the way windows locks GL contexts differs from the way OS X and Linux does, so if you intend to use OpenGL with multiple threads, try to periodically compile on the other platforms to make sure nothing is completely busted. This will also quickly point out areas where you might have inadvertently used a non-cross-platform system API.\nI've used Qt with a team to build a multi-threaded 3-d multiplayer real-time networked game (read: non-trivial application that fully utilized many many areas of Qt) and we were nothing but blown away by the effectiveness of Qt's ability to support multiple platforms. (We developed on OS X while targeting Windows and I regularly made sure it still ran on Linux as well.) We encountered only a few platform specific bugs, almost all of which arose from the use of non-Qt APIs such as OpenGL. (Which should really tell you something, that OpenGL was more of a struggle to use cross platform than Qt was.)\nAt the end of the experience we were pleased at how little time we needed to spend dealing with platform-specific bugs. It was surprising how well we could make a GUI app for windows given almost none of the team actually used it as a primary development platform through the project.\nBut do test early and often. I don't think your approach of writing an entire application and then testing is a good idea. It's possible with Qt, but unlikely if you don't have experience writing portable code and/or are new to Qt.\n", "Yes. The code that you write using Qt will work on Windows, Mac, Linux/X11, embedded Linux, Windows CE and Symbian without any change.\nYou can take a look here.\n", "Generally - as long as you don't use code that is not covered by Qt classes - yes.\nI have several time just recompiled applications I wrote in Linux(64bit) under Windows, and the other way arround. It works for me every time.\nDepends on your needs, you might also find compiler problems, but I am sure you will know how to work around them. Other people mentioned some issues you should look for, just read the other posts in the question.\n", "It might run well, but it will take some testing, and of course Qt only handles the GUI portability, not the myriad of other things that might cause portability problems.\nQt apps generally don't fit in very well on MacOS because they don't have Applescript support by default and don't necessarily have the right keybindings. But if you do the work to fix those issues, they work, but not nicely. On the Mac, it's far better to build a native UI. If this is an in-house app, Qt is probably OK, but if it's for sale, you won't make many sales and will create yourself some support hassles.\n", "As the others said, everything which is done using Qt-Functionality will most likely run quite flawlessly, WHEN you dont use platform specific functionality of qt.\nThere isnt that much (most of it has to do with window-manager stuff) , but some things might not work on other systems. \nBut such things are surely mentiond in the documentation of Qt.\nStill there are things which cant be done using Qt, so you will have to do that yourself using plain Python...\nYeah \"Python\" itself is platform-independent (well it should), but there are lots of other things involved ... well mainly the OS.\nAnd how the OS reacts you will plainly have to findout yourself by testing the application on all target OS.\nRecently i wrote an quite simple GUI-application, while it ran flawlessy on Windows, it didnt run on Linux, because on Linux Python interpreted files encoded in unicode differently than on Windows.\nAdditionally a small script which should return the hostname of the machine, which it did on Windows, only returned \"localhost\" on Linux, which was obviously not what i wanted.\n" ]
[ 8, 5, 2, 1, 0, 0 ]
[]
[]
[ "cross_platform", "python", "qt" ]
stackoverflow_0002035249_cross_platform_python_qt.txt
Q: Why is Ruby more suitable for Rails than Python? Python and Ruby are usually considered to be close cousins (though with quite different historical baggage) with similar expressiveness and power. But some have argued that the immense success of the Rails framework really has a great deal to do with the language it is built on: Ruby itself. So why would Ruby be more suitable for such a framework than Python? A: There are probably two major differences: Ruby has elegant, anonymous closures. Rails uses them to good effect. Here's an example: class WeblogController < ActionController::Base def index @posts = Post.find :all respond_to do |format| format.html format.xml { render :xml => @posts.to_xml } format.rss { render :action => "feed.rxml" } end end end Anonymous closures/lambdas make it easier to emulate new language features that would take blocks. In Python, closures exist, but they must be named in order to be used. So instead of being able to use closures to emulate new language features, you're forced to be explicit about the fact that you're using a closure. Ruby has cleaner, easier to use metaprogramming. This is used extensively in Rails, primarily because of how easy it is to use. To be specific, in Ruby, you can execute arbitrary code in the context of the class. The following snippets are equivalent: class Foo def self.make_hello_method class_eval do def hello puts "HELLO" end end end end class Bar < Foo # snippet 1 make_hello_method end class Bar < Foo; end # snippet 2 Bar.make_hello_method In both cases, you can then do: Bar.new.hello which will print "HELLO". The class_eval method also takes a String, so it's possible to create methods on the fly, as a class is being created, that have differing semantics based on the parameters that are passed in. It is, in fact, possible to do this sort of metaprogramming in Python (and other languages, too), but Ruby has a leg up because metaprogramming isn't a special style of programming. It flows from the fact that in Ruby, everything is an object and all lines of code are directly executed. As a result, Classes are themselves objects, class bodies have a self pointing at the Class, and you can call methods on the class as you are creating one. This is to large degree responsible for the degree of declarativeness possible in Rails, and the ease by which we are able to implement new declarative features that look like keywords or new block language features. A: Those who have argued that the immense success of the Rails framework really has a great deal to do with the language it is built on are (IMO) mistaken. That success probably owes more to clever and sustained marketing than to any technical prowess. Django arguably does a better job in many areas (e.g. the built-in kick-ass admin) without the need for any features of Ruby. I'm not dissing Ruby at all, just standing up for Python! A: The python community believes that doing things the most simple and straight forward way possible is the highest form of elegance. The ruby community believes doing things in clever ways that allow for cool code is the highest form of elegance. Rails is all about if you follow certain conventions, loads of other things magically happen for you. That jives really well with the ruby way of looking at the world, but doesn't really follow the python way. A: Personally, I find ruby to be superior to python in many ways that comprise what I'd call 'consistent expressiveness'. For example, in ruby, join is a method on the array object which outputs a string, so you get something like this: numlist = [1,2,3,4] #=> [1, 2, 3, 4] numlist.join(',') #=> "1,2,3,4" In python, join is a method on the string object but which throws an error if you pass it something other than a string as the thing to join, so the same construct is something like: numlist = [1,2,3,4] numlist #=> [1, 2, 3, 4] ",".join([str(i) for i in numlist]) #=> '1,2,3,4' There are a lot of these little kinds of differences that add up over time. Also, I cannot think of a better way to introduce invisible logic errors than to make whitespace significant. A: Is this debate a new "vim versus emacs" debate? I am a Python/Django programmer and thus far I've never found a problem in that language/framework that would lead me to switch to Ruby/Rails. I can imagine that it would be the same if I were experienced with Ruby/Rails. Both have similar philosophy and do the job in a fast and elegant way. The better choice is what you already know. A: The real answer is neither Python or Ruby are better/worse candidates for a web framework. If you want objectivity you need to write some code in both and see which fits your personal preference best, including community. Most people who argue for one or other have either never used the other language seriously or are 'voting' for their personal preference. I would guess most people settle on which ever they come in to contact with first because it teaches them something new (MVC, testing, generators etc.) or does something better (plugins, templating etc). I used to develop with PHP and came in to contact with RubyOnRails. If I had have known about MVC before finding Rails I would more than likely never left PHP behind. But once I started using Ruby I enjoyed the syntax, features etc. If I had have found Python and one of its MVC frameworks first I would more than likely be praising that language instead! A: Python has a whole host of Rails-like frameworks. There are so many that a joke goes that during the typical talk at PyCon at least one web framework will see the light. The argument that Rubys meta programming would make it better suited is IMO incorrect. You don't need metaprogramming for frameworks like this. So I think we can conclude that Ruby are not better (and likely neither worse) than Python in this respect. A: Because Rails is developed to take advantage of Rubys feature set. A similarly gormless question would be "Why is Python more suitable for Django than Ruby is?". A: I suppose we should not discuss the language features per se but rather the accents the respective communities make on the language features. For example, in Python, re-opening a class is perfectly possible but it is not common; in Ruby, however, re-opening a class is something of the daily practice. this allows for a quick and straightforward customization of the framework to the current requirement and renders Ruby more favorable for Rails-like frameworks than any other dynamic language. Hence my answer: common use of re-opening classes. A: Some have said that the type of metaprogramming required to make ActiveRecord (a key component of rails) possible is easier and more natural to do in ruby than in python - I do not know python yet;), so i cannot personally confirm this statement. I have used rails briefly, and its use of catchalls/interceptors and dynamic evaluation/code injection does allow you to operate at a much higher level of abstraction than some of the other frameworks (before its time). I have little to no experience with Python's framework - but i've heard it's equally capable - and that the python community does a great job supporting and fostering pythonic endeavors. A: I think that the syntax is cleaner and Ruby, for me at least, is just a lot more "enjoyable"- as subjective as that is!
Why is Ruby more suitable for Rails than Python?
Python and Ruby are usually considered to be close cousins (though with quite different historical baggage) with similar expressiveness and power. But some have argued that the immense success of the Rails framework really has a great deal to do with the language it is built on: Ruby itself. So why would Ruby be more suitable for such a framework than Python?
[ "There are probably two major differences:\nRuby has elegant, anonymous closures.\nRails uses them to good effect. Here's an example:\nclass WeblogController < ActionController::Base\n def index\n @posts = Post.find :all\n respond_to do |format|\n format.html\n format.xml { render :xml => @posts.to_xml }\n format.rss { render :action => \"feed.rxml\" }\n end\n end\nend\n\nAnonymous closures/lambdas make it easier to emulate new language features that would take blocks. In Python, closures exist, but they must be named in order to be used. So instead of being able to use closures to emulate new language features, you're forced to be explicit about the fact that you're using a closure.\nRuby has cleaner, easier to use metaprogramming.\nThis is used extensively in Rails, primarily because of how easy it is to use. To be specific, in Ruby, you can execute arbitrary code in the context of the class. The following snippets are equivalent:\nclass Foo\n def self.make_hello_method\n class_eval do\n def hello\n puts \"HELLO\"\n end\n end\n end\nend\n\nclass Bar < Foo # snippet 1\n make_hello_method\nend\n\nclass Bar < Foo; end # snippet 2\nBar.make_hello_method\n\nIn both cases, you can then do:\nBar.new.hello \n\nwhich will print \"HELLO\". The class_eval method also takes a String, so it's possible to create methods on the fly, as a class is being created, that have differing semantics based on the parameters that are passed in.\nIt is, in fact, possible to do this sort of metaprogramming in Python (and other languages, too), but Ruby has a leg up because metaprogramming isn't a special style of programming. It flows from the fact that in Ruby, everything is an object and all lines of code are directly executed. As a result, Classes are themselves objects, class bodies have a self pointing at the Class, and you can call methods on the class as you are creating one.\nThis is to large degree responsible for the degree of declarativeness possible in Rails, and the ease by which we are able to implement new declarative features that look like keywords or new block language features.\n", "Those who have argued that\n\nthe immense success of the Rails\n framework really has a great deal to\n do with the language it is built on\n\nare (IMO) mistaken. That success probably owes more to clever and sustained marketing than to any technical prowess. Django arguably does a better job in many areas (e.g. the built-in kick-ass admin) without the need for any features of Ruby. I'm not dissing Ruby at all, just standing up for Python!\n", "The python community believes that doing things the most simple and straight forward way possible is the highest form of elegance. The ruby community believes doing things in clever ways that allow for cool code is the highest form of elegance. \nRails is all about if you follow certain conventions, loads of other things magically happen for you. That jives really well with the ruby way of looking at the world, but doesn't really follow the python way. \n", "Personally, I find ruby to be superior to python in many ways that comprise what I'd call 'consistent expressiveness'. For example, in ruby, join is a method on the array object which outputs a string, so you get something like this:\nnumlist = [1,2,3,4]\n#=> [1, 2, 3, 4]\nnumlist.join(',')\n#=> \"1,2,3,4\"\n\nIn python, join is a method on the string object but which throws an error if you pass it something other than a string as the thing to join, so the same construct is something like:\nnumlist = [1,2,3,4]\nnumlist\n#=> [1, 2, 3, 4]\n\",\".join([str(i) for i in numlist])\n#=> '1,2,3,4'\n\nThere are a lot of these little kinds of differences that add up over time.\nAlso, I cannot think of a better way to introduce invisible logic errors than to make whitespace significant.\n", "Is this debate a new \"vim versus emacs\" debate?\nI am a Python/Django programmer and thus far I've never found a problem in that language/framework that would lead me to switch to Ruby/Rails.\nI can imagine that it would be the same if I were experienced with Ruby/Rails.\nBoth have similar philosophy and do the job in a fast and elegant way. The better choice is what you already know.\n", "The real answer is neither Python or Ruby are better/worse candidates for a web framework. If you want objectivity you need to write some code in both and see which fits your personal preference best, including community. \nMost people who argue for one or other have either never used the other language seriously or are 'voting' for their personal preference.\nI would guess most people settle on which ever they come in to contact with first because it teaches them something new (MVC, testing, generators etc.) or does something better (plugins, templating etc). I used to develop with PHP and came in to contact with RubyOnRails. If I had have known about MVC before finding Rails I would more than likely never left PHP behind. But once I started using Ruby I enjoyed the syntax, features etc.\nIf I had have found Python and one of its MVC frameworks first I would more than likely be praising that language instead!\n", "Python has a whole host of Rails-like frameworks. There are so many that a joke goes that during the typical talk at PyCon at least one web framework will see the light.\nThe argument that Rubys meta programming would make it better suited is IMO incorrect. You don't need metaprogramming for frameworks like this.\nSo I think we can conclude that Ruby are not better (and likely neither worse) than Python in this respect.\n", "Because Rails is developed to take advantage of Rubys feature set. \nA similarly gormless question would be \"Why is Python more suitable for Django than Ruby is?\".\n", "I suppose we should not discuss the language features per se but rather the accents the respective communities make on the language features. For example, in Python, re-opening a class is perfectly possible but it is not common; in Ruby, however, re-opening a class is something of the daily practice. this allows for a quick and straightforward customization of the framework to the current requirement and renders Ruby more favorable for Rails-like frameworks than any other dynamic language.\nHence my answer: common use of re-opening classes.\n", "Some have said that the type of metaprogramming required to make ActiveRecord (a key component of rails) possible is easier and more natural to do in ruby than in python - I do not know python yet;), so i cannot personally confirm this statement.\nI have used rails briefly, and its use of catchalls/interceptors and dynamic evaluation/code injection does allow you to operate at a much higher level of abstraction than some of the other frameworks (before its time). I have little to no experience with Python's framework - but i've heard it's equally capable - and that the python community does a great job supporting and fostering pythonic endeavors.\n", "I think that the syntax is cleaner and Ruby, for me at least, is just a lot more \"enjoyable\"- as subjective as that is!\n" ]
[ 172, 58, 54, 26, 26, 15, 11, 8, 4, 1, 1 ]
[ "Two answers : \na. Because rails was written for ruby. \nb. For the same reason C more suitable for Linux than Ruby\n", "All of this is TOTALLY \"IMHO\"\nIn Ruby there is ONE web-application framework, so it is the only framework that is advertised for that language.\nPython has had several since inception, just to name a few: Zope, Twisted, Django, TurboGears (it itself a mix of other framework components), Pylons (a kinda-clone of the Rails framework), and so on. None of them are python-community-wide supported as \"THE one to use\" so all the \"groundswell\" is spread over several projects.\nRails has the community size solely, or at least in the vast majority, because of Rails.\nBoth Python and Ruby are perfectly capable of doing the job as a web applications framework. Use the one YOU (and your potential development team) like and can align on.\n" ]
[ -2, -6 ]
[ "python", "ruby", "ruby_on_rails", "web_frameworks" ]
stackoverflow_0001099305_python_ruby_ruby_on_rails_web_frameworks.txt
Q: How does one do async ajax calls using cherrypy? I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database. I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy? A: If you are using CherryPy 3.2.0-rc1 then you can use the decorators @json_in and @json_out (see here). Thus: @cherrypy.expose @tools.json_in(on = True) @tools.json_out(on = True) def json_test(self): return { 'message':'Hello, world!' } will return JSON to the browser, e.g. $(document).ready(function() { $.getJSON('/json_test', function(data) { alert(data.message); } } You need to remember that CherryPy expects JSON posts to have a content type of application/json, to do that with jQuery, either use $.ajax and manaully set contentType or you can use the following convenience function: $.postJSON = function(url, data, callback) { $.ajaxSetup({ scriptCharset:"utf-8", contentType:"application/json; charset=utf-8" }); $.post(url, $.toJSON(data), callback, "json"); } This function uses the jquery-json plugin, but you could use a different method to convert to JSON. A: The same way you would do them using any other webserver - by getting your javascript to call a URL which is handled by the server-side application.
How does one do async ajax calls using cherrypy?
I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database. I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy?
[ "If you are using CherryPy 3.2.0-rc1 then you can use the decorators @json_in and @json_out (see here).\nThus:\n@cherrypy.expose\n@tools.json_in(on = True)\n@tools.json_out(on = True)\ndef json_test(self):\n return { 'message':'Hello, world!' }\n\nwill return JSON to the browser, e.g.\n$(document).ready(function() {\n $.getJSON('/json_test', function(data) {\n alert(data.message);\n }\n}\n\nYou need to remember that CherryPy expects JSON posts to have a content type of application/json, to do that with jQuery, either use $.ajax and manaully set contentType or you can use the following convenience function: \n$.postJSON = function(url, data, callback) {\n $.ajaxSetup({ scriptCharset:\"utf-8\", \n contentType:\"application/json; charset=utf-8\" });\n $.post(url, $.toJSON(data), callback, \"json\");\n}\n\nThis function uses the jquery-json plugin, but you could use a different method to convert to JSON.\n", "The same way you would do them using any other webserver - by getting your javascript to call a URL which is handled by the server-side application.\n" ]
[ 9, 2 ]
[]
[]
[ "ajax", "asynchronous", "cherrypy", "jquery", "python" ]
stackoverflow_0002015065_ajax_asynchronous_cherrypy_jquery_python.txt
Q: Index of item in list when only part of the item is known This is a follow-up on a previous question of mine regarding searching in lists of lists I have a list with pairs of values as lists in it. [['a',5], ['b',3], ['c',2] ] I know the first element of each pair but I don't know the second (it's the result of a calculation and stored in the list with the first element. I sorted the list in descending order of the calculated item. I want to know in which position each of the items is, which would normally be: list.index('a') if I didn't have the numbers there. Is there a way to get the index number without knowing the entirety of the element? Something like: list.index(['a',?]) where ? is a wildcard? Or should I just create a new list from the ordered one with just the first item in order to get it's index? A: [x[0] for x in list].index('a') But if you are running this code several times, you might want to save the list of x[0]'s. A: There's a similar solution to that of Ofris D = dict([ [x[1][0], x[0] ] for x in list(enumerate(L)) ]) D['a'] #returns 0 But another nice feature is that if you tweak this a little you can pull out your original values D = dict([ [x[1][0], (x[0], x[1][1] ) ] for x in list(enumerate(L)) ]) D['a'][0] #returns 0 D['a'][1] #returns 5 A: A simple, flexible one line version: [i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a'] # returns [0, 2] [i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a'][0] # returns 0 You could wrap it in a function, replace item[0] == 'a' with a call to an arbitrary predicate (like in my original answer; that's where it's flexible) etc. The second version above will throw an exception if no item is found, so wrap it in try/except; the first one will return an empty list. If you prefer a separate function for the job, check out the one below... It has the benefit of only consuming as much of your iterable as needed to find an appropriate item. Original answer: This will allow you to find the index of the first item possessing any property you can think of, though you'll need to express it as a function (a lambda x: x[0] == 'a' suffices in your example case): def index_by(pred, iterable): i = 0 found = False for item in iterable: if pred(item): found = True break i += 1 return i if found else None Call like so: index_by(lambda x: x[0] == 'a', [('b', 1), ('a', 5)]) # returns 1 to obtain the zero-based index of the first item in the iterable which satisfies the given predicate. (In other words, the first item in the iterable passed in as the second argument for which the function passed in as the first argument returns a true value.) If the iterable does not contain an element satisfying the predicate, None is returned. A: You already have the original list from which you know the first elements. List call it orig_list. Get the element's index from the original list and use that index in the new list to retrieve. >>> orig_list = ['a','b','c'] >>> calc_list = [['a',5], ['b',3], ['c',2] ] >>> calc_list[orig_list.index('a')] ['a',5] A: The code below will get the indexes of all items in the list that match the pattern ['a', ?]: >>> l = [['a',5], ['b',3], ['c',2], ['a',8]] >>> indexes = [l.index(x) for x in l if x[0] == 'a'] >>> print indexes [0, 3]
Index of item in list when only part of the item is known
This is a follow-up on a previous question of mine regarding searching in lists of lists I have a list with pairs of values as lists in it. [['a',5], ['b',3], ['c',2] ] I know the first element of each pair but I don't know the second (it's the result of a calculation and stored in the list with the first element. I sorted the list in descending order of the calculated item. I want to know in which position each of the items is, which would normally be: list.index('a') if I didn't have the numbers there. Is there a way to get the index number without knowing the entirety of the element? Something like: list.index(['a',?]) where ? is a wildcard? Or should I just create a new list from the ordered one with just the first item in order to get it's index?
[ "[x[0] for x in list].index('a')\n\nBut if you are running this code several times, you might want to save the list of x[0]'s.\n", "There's a similar solution to that of Ofris\nD = dict([ [x[1][0], x[0] ] for x in list(enumerate(L)) ])\nD['a']\n#returns 0\n\nBut another nice feature is that if you tweak this a little you can pull out your original values\nD = dict([ [x[1][0], (x[0], x[1][1] ) ] for x in list(enumerate(L)) ])\nD['a'][0]\n#returns 0\nD['a'][1]\n#returns 5\n\n", "A simple, flexible one line version:\n[i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a']\n# returns [0, 2]\n\n[i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a'][0]\n# returns 0\n\nYou could wrap it in a function, replace item[0] == 'a' with a call to an arbitrary predicate (like in my original answer; that's where it's flexible) etc. The second version above will throw an exception if no item is found, so wrap it in try/except; the first one will return an empty list.\n\nIf you prefer a separate function for the job, check out the one below... It has the benefit of only consuming as much of your iterable as needed to find an appropriate item.\nOriginal answer:\nThis will allow you to find the index of the first item possessing any property you can think of, though you'll need to express it as a function (a lambda x: x[0] == 'a' suffices in your example case):\ndef index_by(pred, iterable):\n i = 0\n found = False\n for item in iterable:\n if pred(item):\n found = True\n break\n i += 1\n return i if found else None\n\nCall like so:\nindex_by(lambda x: x[0] == 'a', [('b', 1), ('a', 5)]) # returns 1\n\nto obtain the zero-based index of the first item in the iterable which satisfies the given predicate. (In other words, the first item in the iterable passed in as the second argument for which the function passed in as the first argument returns a true value.)\nIf the iterable does not contain an element satisfying the predicate, None is returned.\n", "You already have the original list from which you know the first elements. List call it orig_list. Get the element's index from the original list and use that index in the new list to retrieve.\n>>> orig_list = ['a','b','c']\n>>> calc_list = [['a',5], ['b',3], ['c',2] ]\n\n>>> calc_list[orig_list.index('a')]\n['a',5]\n\n", "The code below will get the indexes of all items in the list that match the pattern ['a', ?]:\n>>> l = [['a',5], ['b',3], ['c',2], ['a',8]]\n>>> indexes = [l.index(x) for x in l if x[0] == 'a']\n>>> print indexes\n[0, 3]\n\n" ]
[ 5, 4, 2, 2, 1 ]
[]
[]
[ "indexing", "list", "python", "search" ]
stackoverflow_0002040298_indexing_list_python_search.txt
Q: OS/X mimetype handler I'd like to write a small script that implements RFC4709 for OS/X. I started off by creating an application bundle that registers the application/xml+davmount mimetype and launches a simple python script. It doesn't make a lot of sense to me to make this a .app bundle, because the application is very short-lived, and it also doesn't seem like the best idea to get people to install it into /Applications As a complete newbie in anything related to programming OS/X, what would be the best way to implement this RFC effectively, with the ultimate endgoals allowing users to click a link with the application/xml+davmount mimetype, which then automatically mounts the share (after asking for username and password). A: Make it a .app bundle, installed in Applications/Utilities (or really, anywhere). Bundles are the right thing on OS X. But if you really don't want to install it in Applications, how about somewhere under /Library or ~/Library, using a package rather than a drop in app. But I know I'd prefer the .app version... easier to uninstall.
OS/X mimetype handler
I'd like to write a small script that implements RFC4709 for OS/X. I started off by creating an application bundle that registers the application/xml+davmount mimetype and launches a simple python script. It doesn't make a lot of sense to me to make this a .app bundle, because the application is very short-lived, and it also doesn't seem like the best idea to get people to install it into /Applications As a complete newbie in anything related to programming OS/X, what would be the best way to implement this RFC effectively, with the ultimate endgoals allowing users to click a link with the application/xml+davmount mimetype, which then automatically mounts the share (after asking for username and password).
[ "Make it a .app bundle, installed in Applications/Utilities (or really, anywhere). Bundles are the right thing on OS X. But if you really don't want to install it in Applications, how about somewhere under /Library or ~/Library, using a package rather than a drop in app. But I know I'd prefer the .app version... easier to uninstall.\n" ]
[ 1 ]
[]
[]
[ "macos", "mime_types", "python", "webdav" ]
stackoverflow_0002040633_macos_mime_types_python_webdav.txt
Q: Using object id as a hash for objects in Python Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change. This occurred to me while looking at Sets of instances and I'm wondering if it's wise. A: Yes, as long as you also define __eq__ (and presumably __ne__!-) consistently with that. IOW, it's fine, as long as you're fine with a==b meaning exactly the same as a is b!-) A: For most Python classes this is the default behaviour. The unhashable ones are unhashable for a good reason: they are mutable collections. For collections it is practical to have the equality relation (as defined by __eq__()) based on equality of their contents. This, and the requirement for __hash__() to be consisent with equality, would of course make the __hash__() mutable, which would be horrible for collections containing such objects. So you can do this but it costs you the content-based equality relation.
Using object id as a hash for objects in Python
Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change. This occurred to me while looking at Sets of instances and I'm wondering if it's wise.
[ "Yes, as long as you also define __eq__ (and presumably __ne__!-) consistently with that. IOW, it's fine, as long as you're fine with a==b meaning exactly the same as a is b!-)\n", "For most Python classes this is the default behaviour. The unhashable ones are unhashable for a good reason: they are mutable collections. \nFor collections it is practical to have the equality relation (as defined by __eq__()) based on equality of their contents. This, and the requirement for __hash__() to be consisent with equality, would of course make the __hash__() mutable, which would be horrible for collections containing such objects.\nSo you can do this but it costs you the content-based equality relation.\n" ]
[ 14, 7 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0002040101_hash_python.txt
Q: Best way to start, stop and send parameters to separate Python script from C++ application? I try to explain the situation: I have a QT application written in C++ and QT. This QT application starts a separate console C++ application that runs in the background. These two communicate using perhaps sockets, don't know yet. Console C++ application needs to start and stop my gnuradio python script. Also it needs to send parameters to it. Once started, this gnuradio script runs independedly in infinite loop sending information to either the console or the QT application using sockets perhaps. My console application needs to stop this gnuradio script from running when the order is given by the QT application. The question is how can I stop this separate python script from my C++ console application ? Also is there anything I could do to make this more simple ? Regards, Spitz A: Sockets, or you could use DBUS python, and DBUS c++, if you want to be all free-desktopy :D A: Spawn python script as a new process using fork() and execv(). execv() (or any other function of the exec family) lets you pass arguments to the Python script. Use the child process ID to send a kill signal when you are done with the Python script. A: For your C++ program, you may wanna take a look here : http://www.codeproject.com/KB/cpp/kill_process.aspx Its gives you the basic code for creating and killing an external process. Remember that launching a python script means calling the python bin and giving the script as first argument. The communication between your C++ app and the python script can be made via a named pipe http://en.wikipedia.org/wiki/Named_pipe but DBUS can work too. My advice is : 1) start your C++ app from your QT app using QT's goodness. You can have these two communicate via standard I/O redirection (depending or what you really wanan do) 2) start your python script from your C++ following the example given above. And those two communicate via DBUS/Socket/Pipes. Should do the trick
Best way to start, stop and send parameters to separate Python script from C++ application?
I try to explain the situation: I have a QT application written in C++ and QT. This QT application starts a separate console C++ application that runs in the background. These two communicate using perhaps sockets, don't know yet. Console C++ application needs to start and stop my gnuradio python script. Also it needs to send parameters to it. Once started, this gnuradio script runs independedly in infinite loop sending information to either the console or the QT application using sockets perhaps. My console application needs to stop this gnuradio script from running when the order is given by the QT application. The question is how can I stop this separate python script from my C++ console application ? Also is there anything I could do to make this more simple ? Regards, Spitz
[ "Sockets, or you could use DBUS python, and DBUS c++, if you want to be all free-desktopy :D\n", "Spawn python script as a new process using fork() and execv(). execv() (or any other function of the exec family) lets you pass arguments to the Python script. Use the child process ID to send a kill signal when you are done with the Python script.\n", "For your C++ program, you may wanna take a look here :\nhttp://www.codeproject.com/KB/cpp/kill_process.aspx\nIts gives you the basic code for creating and killing an external process. Remember that launching a python script means calling the python bin and giving the script as first argument.\nThe communication between your C++ app and the python script can be made via a named pipe\nhttp://en.wikipedia.org/wiki/Named_pipe\nbut DBUS can work too.\nMy advice is :\n1) start your C++ app from your QT app using QT's goodness. You can have these two communicate via standard I/O redirection (depending or what you really wanan do)\n2) start your python script from your C++ following the example given above. And those two communicate via DBUS/Socket/Pipes.\nShould do the trick \n" ]
[ 2, 2, 0 ]
[]
[]
[ "c++", "gnuradio", "python", "qt" ]
stackoverflow_0002040769_c++_gnuradio_python_qt.txt
Q: AppEngine/Python, query database and send multiple images to the client as a response to a single get request I am working on a social-network type of application on App Engine, and would like to send multiple images to the client based on a single get request. In particular, when a client loads a page, they should see all images that are associated with their account. I am using python on the server side, and would like to use Javascript/JQuery on the client side to decode/display the received images. The difficulty is that I would like to only perform a single query on the server side (ie. query for all images associated with a single user) and send all of the images resulting from the query to the client as a single unit, which will then be broken up into the individual images. Ideally, I would like to use something similar to JSON, but while JSON appears to allow multiple "objects" to be sent as a JSON response, it does not appear to have the ability to allow multiple images (or binary files) to be sent as a JSON response. Is there another way that I should be looking at this problem, or perhaps a different technology that I should be considering that might allow me to send multiple images to the client, in response to a single get request? Thank you and Kind Regards Alexander A: The App Engine part isn't much of a problem (as long as the number of images and total size doesn't exceed GAE's limits), but the user's browser is unlikely to know what to do in order to receive multiple payloads per GET request -- that's just not how the web works. I guess you could concatenate all the blobs/bytestreams (together with metadata needed for the client to reconstruct them) and send that (it will still have to be a separate payload from the HTML / CSS / Javascript that you're also sending), as long as you can cajole Javascript into separating the megablob into the needed images again (but for that part you should open a separate question and tag it Javascript, as Python has little to do with it, and GAE nothing at all). I would instead suggest just accepting the fact that the browser (presumably via ajax, as you mention in tags) will be sending multiple requests, just as it does to every other webpage on the WWW, and focus on optimizing the serving side -- the requests will be very close in time, so you should just use memcache to keep the yet-unsent images to avoid multiple fetch-from-storage requests in your GAE app. A: As an improvement to Alex's answer, there's no need to use memcache: Simply do a keys-only query to get a list of keys of images you want to send to the client, then use db.get() to fetch the image corresponding to the required key for each image request. This requires roughly the same amount of effort as a single regular query. A: Trying to send all of the images in one request means that you will be fighting very hard against some of the fundamental assumptions of the web and browser technology. If you don't have a really, really compelling reason to do this, you should consider delivering one image per request. That already works now, no sweat, no effort, no wheels reinvented. I can't think of a sensible way to do what you ask, but I can tell you that you are asking for pain in trying to implement the solution that you are describing. A: Send the client URLs for all the images in one hit, and deal with it on the client. That fits with the design of the protocol, and still lets you only make one query. The client might, if you're lucky, be able to stream those back in its next request, but the neat thing is that it'll work (eventually) even if it can't reuse the connection for some reason (usually a busted proxy in the way).
AppEngine/Python, query database and send multiple images to the client as a response to a single get request
I am working on a social-network type of application on App Engine, and would like to send multiple images to the client based on a single get request. In particular, when a client loads a page, they should see all images that are associated with their account. I am using python on the server side, and would like to use Javascript/JQuery on the client side to decode/display the received images. The difficulty is that I would like to only perform a single query on the server side (ie. query for all images associated with a single user) and send all of the images resulting from the query to the client as a single unit, which will then be broken up into the individual images. Ideally, I would like to use something similar to JSON, but while JSON appears to allow multiple "objects" to be sent as a JSON response, it does not appear to have the ability to allow multiple images (or binary files) to be sent as a JSON response. Is there another way that I should be looking at this problem, or perhaps a different technology that I should be considering that might allow me to send multiple images to the client, in response to a single get request? Thank you and Kind Regards Alexander
[ "The App Engine part isn't much of a problem (as long as the number of images and total size doesn't exceed GAE's limits), but the user's browser is unlikely to know what to do in order to receive multiple payloads per GET request -- that's just not how the web works. I guess you could concatenate all the blobs/bytestreams (together with metadata needed for the client to reconstruct them) and send that (it will still have to be a separate payload from the HTML / CSS / Javascript that you're also sending), as long as you can cajole Javascript into separating the megablob into the needed images again (but for that part you should open a separate question and tag it Javascript, as Python has little to do with it, and GAE nothing at all).\nI would instead suggest just accepting the fact that the browser (presumably via ajax, as you mention in tags) will be sending multiple requests, just as it does to every other webpage on the WWW, and focus on optimizing the serving side -- the requests will be very close in time, so you should just use memcache to keep the yet-unsent images to avoid multiple fetch-from-storage requests in your GAE app.\n", "As an improvement to Alex's answer, there's no need to use memcache: Simply do a keys-only query to get a list of keys of images you want to send to the client, then use db.get() to fetch the image corresponding to the required key for each image request. This requires roughly the same amount of effort as a single regular query.\n", "Trying to send all of the images in one request means that you will be fighting very hard against some of the fundamental assumptions of the web and browser technology. If you don't have a really, really compelling reason to do this, you should consider delivering one image per request. That already works now, no sweat, no effort, no wheels reinvented.\nI can't think of a sensible way to do what you ask, but I can tell you that you are asking for pain in trying to implement the solution that you are describing.\n", "Send the client URLs for all the images in one hit, and deal with it on the client. That fits with the design of the protocol, and still lets you only make one query. The client might, if you're lucky, be able to stream those back in its next request, but the neat thing is that it'll work (eventually) even if it can't reuse the connection for some reason (usually a busted proxy in the way).\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "image", "python" ]
stackoverflow_0002003630_ajax_google_app_engine_image_python.txt
Q: How do I get PyFacebook working with the Google App Engine Patch? I've tried to follow the advice of this question: Facebook, Django, and Google App Engine, however I've run into a number of problems. The first is that from facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't have that method. If I change it to import facebook.djangofb and @facebook.djangofb.require_login(), it works. Any ideas that's going on there? Then, even with that, I experience the same problem as in this question: app-engine-patch and pyFacebook not working. It seems like a lot of people have done this, so is there a good example of how to combine PyFacebook and App Engine Patch? A: For your first question: from facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't have that method. If I change it to import facebook.djangofb and @facebook.djangofb.require_login(), it works. Well, seems like require_login is on facebook.djangofb not on facebook.djangofb.facebook. So you can do: import facebook.djangofb @facebook.djangofb.require_login() ... or from facebook import djangofb @djangofb.require_login() ... or from facebook.djangofb import require_login @require_login() ... For the second question, did you try the answer of the other question (not using require_login at all, using request.fb.check_session(request) instead)? What do you get?
How do I get PyFacebook working with the Google App Engine Patch?
I've tried to follow the advice of this question: Facebook, Django, and Google App Engine, however I've run into a number of problems. The first is that from facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't have that method. If I change it to import facebook.djangofb and @facebook.djangofb.require_login(), it works. Any ideas that's going on there? Then, even with that, I experience the same problem as in this question: app-engine-patch and pyFacebook not working. It seems like a lot of people have done this, so is there a good example of how to combine PyFacebook and App Engine Patch?
[ "For your first question:\n\nfrom facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't have that method. If I change it to import facebook.djangofb and @facebook.djangofb.require_login(), it works.\n\nWell, seems like require_login is on facebook.djangofb not on facebook.djangofb.facebook.\nSo you can do:\nimport facebook.djangofb\n@facebook.djangofb.require_login()\n...\n\nor\nfrom facebook import djangofb\n@djangofb.require_login()\n...\n\nor\nfrom facebook.djangofb import require_login\n@require_login()\n...\n\nFor the second question, did you try the answer of the other question (not using require_login at all, using request.fb.check_session(request) instead)? What do you get?\n" ]
[ 4 ]
[]
[]
[ "app_engine_patch", "django", "facebook", "google_app_engine", "python" ]
stackoverflow_0002039653_app_engine_patch_django_facebook_google_app_engine_python.txt
Q: How to make phone calls using Python? I'm writting a small python program to send voice file to other telephone. The phone is connected to pc over usb. How to make phone calls using Python? A: I think the smart way is to leave it a professional Voice/IP app such as ribbit or Twilio. I would personally recommend twilio which has Python libraries A: Micromedia Jericho is a commercial product running on Ms Windows which has this capability. It manages several types of modems and make possible to send wav file over a phone call. It also support "Text to speech" converting a text to a wave file. It has a C API that can be accessed by Python thanks to ctypes. I don't know if it can be a solution for you. I hope it helps A: You could probably use the pyusb library.
How to make phone calls using Python?
I'm writting a small python program to send voice file to other telephone. The phone is connected to pc over usb. How to make phone calls using Python?
[ "I think the smart way is to leave it a professional Voice/IP app such as ribbit or Twilio. I would personally recommend twilio which has Python libraries\n", "Micromedia Jericho is a commercial product running on Ms Windows which has this capability. It manages several types of modems and make possible to send wav file over a phone call. It also support \"Text to speech\" converting a text to a wave file.\nIt has a C API that can be accessed by Python thanks to ctypes.\nI don't know if it can be a solution for you.\nI hope it helps \n", "You could probably use the pyusb library.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "usb", "voice" ]
stackoverflow_0002041352_python_usb_voice.txt
Q: What is The Pythonic Way for writing matching algorithm I have this piece of code (should be self-explanatory; if not, just ask): for tr in completed_taskrevs: found = False for nr in completion_noterevs: if tr.description in nr.body: completion_noterevs.remove(nr) found = True break assert found How can I make it more pythonic? A: Try this: for tr in compleded_taskrevs: try: nrs = (nr for nr in completion_noterevs if tr.description in nr.body) completion_noterevs.remove(nrs.next()) except StopIteration: raise ValueError('Some error') EDIT: Devin is right. Assertion is not the way to go, better to use a standard exception. A: Using assert/AssertionError is probably wrong here, I'd say. It's useful for "debugging assertions", which is to say, to make sure your code is sane. It's not useful as a way to raise an error when you get invalid data, for many reasons, the most interesting of which is probably that assert isn't even guaranteed to be executed-- if your code is compiled with any optimization settings, it won't be. And heck, even if this is a debugging thing, I'd still use raise-- it's more readable, and it'll always happen, no matter when or why the data is wrong. So to make it more "pythonic", I would remove the assert and replace it with something nicer. As it happens, such a nicer thing exists, and it's the raise statement. Further, I would replace the clumsy value set/check with the else clause of loops, which is executed when the loop is exhausted (or, for while loops, when the condition becomes false). So if you break, the else clause is not executed. for tr in completed_taskrevs: for nr in completion_noterevs: if tr.description in nr.body: completion_noterevs.remove(nr) break else: raise ValueError("description not found"); # or whatever exception would be appropriate Other than this, I probably wouldn't change anything. A: The list generator below could return you all items nr that are valid tr.description in nr.body however it's hard to simplify your algorithm as it has quite a few branches. I would just say go with the algorithm you have as long as it does what you want. [nr for tr in completed_taskrevs for nr in completion_noterevs if tr.description in nr.body]
What is The Pythonic Way for writing matching algorithm
I have this piece of code (should be self-explanatory; if not, just ask): for tr in completed_taskrevs: found = False for nr in completion_noterevs: if tr.description in nr.body: completion_noterevs.remove(nr) found = True break assert found How can I make it more pythonic?
[ "Try this:\nfor tr in compleded_taskrevs:\n try:\n nrs = (nr for nr in completion_noterevs if tr.description in nr.body)\n completion_noterevs.remove(nrs.next())\n except StopIteration:\n raise ValueError('Some error')\n\nEDIT:\nDevin is right. Assertion is not the way to go, better to use a standard exception.\n", "Using assert/AssertionError is probably wrong here, I'd say. It's useful for \"debugging assertions\", which is to say, to make sure your code is sane. It's not useful as a way to raise an error when you get invalid data, for many reasons, the most interesting of which is probably that assert isn't even guaranteed to be executed-- if your code is compiled with any optimization settings, it won't be. And heck, even if this is a debugging thing, I'd still use raise-- it's more readable, and it'll always happen, no matter when or why the data is wrong.\nSo to make it more \"pythonic\", I would remove the assert and replace it with something nicer. As it happens, such a nicer thing exists, and it's the raise statement. Further, I would replace the clumsy value set/check with the else clause of loops, which is executed when the loop is exhausted (or, for while loops, when the condition becomes false). So if you break, the else clause is not executed.\nfor tr in completed_taskrevs:\n for nr in completion_noterevs:\n if tr.description in nr.body:\n completion_noterevs.remove(nr)\n break\n else:\n raise ValueError(\"description not found\"); # or whatever exception would be appropriate\n\nOther than this, I probably wouldn't change anything.\n", "The list generator below could return you all items nr that are valid tr.description in nr.body however it's hard to simplify your algorithm as it has quite a few branches. I would just say go with the algorithm you have as long as it does what you want.\n[nr for tr in completed_taskrevs for nr in completion_noterevs if tr.description in nr.body]\n\n" ]
[ 8, 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002041378_python.txt