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: Multiple inheritance in django. Problem with constructors I have a model like this: class Person(models.Model,Subject): name = .. The class Subject is not supposed to be in the Database so, it doesn't extends from models.Model: class Subject: def __init__(self,**kargs): _observers = [] my problem is that the constructor of Subject is never called, so i've tried adding this to the class Person: def __init__(self): super(Person,self).__init__() but now i have an error saying that init takes 1 arguments but 7 are given, and the only thing i'm doing is >>> Person.objects.get(pk=1) now i'm lost =S do you have any idea how the constructor of person should be? BTW: i'm using django 1.1 and python 2.6 A: First of all, use new-style classes (ones that inherit from object). Second, read about how python's super behaves in multiple inheritance scenarios: http://fuhm.net/super-harmful/ There is also a nice talk covering it: http://europythonvideos.blip.tv/file/4000758/ A: You can use Django's post_init signal. It's invoked after the model is instantiated, and is passed the instance that was created.
Multiple inheritance in django. Problem with constructors
I have a model like this: class Person(models.Model,Subject): name = .. The class Subject is not supposed to be in the Database so, it doesn't extends from models.Model: class Subject: def __init__(self,**kargs): _observers = [] my problem is that the constructor of Subject is never called, so i've tried adding this to the class Person: def __init__(self): super(Person,self).__init__() but now i have an error saying that init takes 1 arguments but 7 are given, and the only thing i'm doing is >>> Person.objects.get(pk=1) now i'm lost =S do you have any idea how the constructor of person should be? BTW: i'm using django 1.1 and python 2.6
[ "First of all, use new-style classes (ones that inherit from object). Second, read about how python's super behaves in multiple inheritance scenarios: http://fuhm.net/super-harmful/\nThere is also a nice talk covering it: http://europythonvideos.blip.tv/file/4000758/\n", "You can use Django's post_init signal. I...
[ 1, 0 ]
[]
[]
[ "constructor", "django", "multiple_inheritance", "python" ]
stackoverflow_0003699713_constructor_django_multiple_inheritance_python.txt
Q: error on running my application in Django with mod_python I have win32,python2.5,django1.2, apache2.2, and mod_python3.3.1 I have installed properly mod_python. Now my application name is myapp.setting which path is c:\myapp.setting. In myapp.settings my file is myapp.settings\url.py,settings.py etc. now in apache httpd.conf file I have changes following:- <Location "/mysite"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE myapp.settings PythonDebug On PythonPath "['/'] + sys.path" </Location> and I have tried many changes in PythonPath. but when i typed http://localhost/mysite the error is following:- MOD_PYTHON ERROR ProcessId: 1384 Interpreter: '192.168.1.166' ServerName: '192.168.1.166' DocumentRoot: 'C:/Program Files/Apache Software Foundation/Apache2.2/htdocs' URI: '/mysite' Location: '/mysite' Directory: None Filename: 'C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/mysite' PathInfo: '' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\Lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\Lib\site-packages\django\core\handlers\modpython.py", line 191, in __call__ self.load_middleware() File "C:\Python25\Lib\site-packages\django\core\handlers\base.py", line 33, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "C:\Python25\Lib\site-packages\django\utils\functional.py", line 276, in __getattr__ self._setup() File "C:\Python25\Lib\site-packages\django\conf\__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "C:\Python25\Lib\site-packages\django\conf\__init__.py", line 75, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myapp.settings' (Is it on sys.path? Does it have syntax errors?): No module named myapp.settings Please help me I am new in Django... A: As rebus says in his comment, it's nonsense to call your project 'myapp.settings'. It's neither an app (which is a component of a site), nor is it a settings file. Call it something sensible - if you really can't think of anything, call it 'mysite'. Finally, however, you should not be using mod_python. Use mod_wsgi instead.
error on running my application in Django with mod_python
I have win32,python2.5,django1.2, apache2.2, and mod_python3.3.1 I have installed properly mod_python. Now my application name is myapp.setting which path is c:\myapp.setting. In myapp.settings my file is myapp.settings\url.py,settings.py etc. now in apache httpd.conf file I have changes following:- <Location "/mysite"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE myapp.settings PythonDebug On PythonPath "['/'] + sys.path" </Location> and I have tried many changes in PythonPath. but when i typed http://localhost/mysite the error is following:- MOD_PYTHON ERROR ProcessId: 1384 Interpreter: '192.168.1.166' ServerName: '192.168.1.166' DocumentRoot: 'C:/Program Files/Apache Software Foundation/Apache2.2/htdocs' URI: '/mysite' Location: '/mysite' Directory: None Filename: 'C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/mysite' PathInfo: '' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\Lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\Lib\site-packages\django\core\handlers\modpython.py", line 191, in __call__ self.load_middleware() File "C:\Python25\Lib\site-packages\django\core\handlers\base.py", line 33, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "C:\Python25\Lib\site-packages\django\utils\functional.py", line 276, in __getattr__ self._setup() File "C:\Python25\Lib\site-packages\django\conf\__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "C:\Python25\Lib\site-packages\django\conf\__init__.py", line 75, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myapp.settings' (Is it on sys.path? Does it have syntax errors?): No module named myapp.settings Please help me I am new in Django...
[ "As rebus says in his comment, it's nonsense to call your project 'myapp.settings'. It's neither an app (which is a component of a site), nor is it a settings file. Call it something sensible - if you really can't think of anything, call it 'mysite'.\nFinally, however, you should not be using mod_python. Use mod_ws...
[ 2 ]
[]
[]
[ "apache", "django", "mod_python", "python" ]
stackoverflow_0003699673_apache_django_mod_python_python.txt
Q: how can I add users/numbers to asterisk from php? How can I go about adding users/number, changing things from PHP(or python) on an asterisk server? ps. also are there any better ways to get the current asterisk settings, users, numbers other than scraping the config files? A: You can use ASterisk-gui for this. It does exactly what you need A: Disclaimer: I never worked with asterisk. Just some links to look into: http://www.straw-dogs.co.uk/asterisk-api-php/ Asterisk manager Examples
how can I add users/numbers to asterisk from php?
How can I go about adding users/number, changing things from PHP(or python) on an asterisk server? ps. also are there any better ways to get the current asterisk settings, users, numbers other than scraping the config files?
[ "You can use ASterisk-gui for this. It does exactly what you need\n", "Disclaimer: I never worked with asterisk. Just some links to look into:\n\nhttp://www.straw-dogs.co.uk/asterisk-api-php/\nAsterisk manager Examples\n\n" ]
[ 6, 2 ]
[]
[]
[ "asterisk", "php", "python" ]
stackoverflow_0002950456_asterisk_php_python.txt
Q: how can I consume django web service in C#? python - django webmethod returns simplejson.dumps, how can I convert the simplejson string into C# 2.0 Object ? for example, dict -> Hashtable string -> String ... is there any JSON Serializable library in existing .NET framework or any 3rd party tool ? A: Tried System.Json? A: Try the JSON.net project hosted at GitHub : JSON.NET
how can I consume django web service in C#?
python - django webmethod returns simplejson.dumps, how can I convert the simplejson string into C# 2.0 Object ? for example, dict -> Hashtable string -> String ... is there any JSON Serializable library in existing .NET framework or any 3rd party tool ?
[ "Tried System.Json?\n", "Try the JSON.net project hosted at GitHub : JSON.NET\n" ]
[ 1, 1 ]
[]
[]
[ "c#", "django", "python", "serialization", "simplejson" ]
stackoverflow_0003699699_c#_django_python_serialization_simplejson.txt
Q: extracting individual items resulting from a string split() operation a = line.splitlines()[:2] I got this output as shown below . ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1'] ['Host: www.explainth.at'] ['User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11'] ['Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'] ['Accept-Language: en-gb,en;q=0.5'] ['Accept-Encoding: gzip,deflate'] ['Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7'] ['Keep-Alive: 300'] I want to get the first two items: GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 Host: www.explainth.at A: to get first 2 items. a[:2] A: The Host header field is not necessarily the first header field after the status line. So instead of getting the first two lines you should do something like this: lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:'] The list comprehension lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:'] will only return the line if it starts with Host:. A: >>> a = ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1', ... 'Host: www.explainth.at', ... 'User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11', ... 'Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', ... 'Accept-Language: en-gb,en;q=0.5', ... 'Accept-Encoding: gzip,deflate', ... 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7', ... 'Keep-Alive: 300'] >>> getstr=a.pop(0) >>> adict = dict(x.partition(':')[::2] for x in a) >>> adict['Host'] ' www.explainth.at'
extracting individual items resulting from a string split() operation
a = line.splitlines()[:2] I got this output as shown below . ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1'] ['Host: www.explainth.at'] ['User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11'] ['Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'] ['Accept-Language: en-gb,en;q=0.5'] ['Accept-Encoding: gzip,deflate'] ['Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7'] ['Keep-Alive: 300'] I want to get the first two items: GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 Host: www.explainth.at
[ "to get first 2 items. \na[:2]\n\n", "The Host header field is not necessarily the first header field after the status line. So instead of getting the first two lines you should do something like this:\nlines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:']\n\nThe list comprehension lines[0] +...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003699438_python.txt
Q: wx.wizard and python I have a class which derived from wx.frame and need to attach it to wx.wizard as a page is that possible and if yes how can i do that : for example i have frame=myDrevidedFrame(..) where myDervidedFrame its base class wx.frame how can i attach the frame object to wx.wizard ? A: No I dont think you can do that. It wouldnt make any sense to put a Frame as a child of a Dialog(which is basically what a wx.wizard is). It shouldn't be too hard to convert your derived frame class to a PywizardPage, basically instead of extending the wx.Frame extend the wx.wizard.PyWizardPage. If you haven't already, download the docs_demos and have a look at the wx.Wizard demo for an example of proper usage, it should be enough to get started in the right direction.
wx.wizard and python
I have a class which derived from wx.frame and need to attach it to wx.wizard as a page is that possible and if yes how can i do that : for example i have frame=myDrevidedFrame(..) where myDervidedFrame its base class wx.frame how can i attach the frame object to wx.wizard ?
[ "No I dont think you can do that. It wouldnt make any sense to put a Frame as a child of a Dialog(which is basically what a wx.wizard is). \nIt shouldn't be too hard to convert your derived frame class to a PywizardPage,\nbasically instead of extending the wx.Frame extend the wx.wizard.PyWizardPage.\nIf you haven't...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003700256_python_wxpython.txt
Q: How to create/modify the controller class generated by pylons? Say I wanted to add some imports to the file generated when I run: paster controller controllern_name Is this possible? A: I assume you want to modify the pylons templates -- in this case controller.py_tmpl. It's best to create your own set of templates based on the ones from pylons, and then use them when starting a new project.
How to create/modify the controller class generated by pylons?
Say I wanted to add some imports to the file generated when I run: paster controller controllern_name Is this possible?
[ "I assume you want to modify the pylons templates -- in this case controller.py_tmpl. It's best to create your own set of templates based on the ones from pylons, and then use them when starting a new project.\n" ]
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003699796_pylons_python.txt
Q: Python 2.5 String formatting problem! I am trying to use the python 2.5 string formatting however I have run into problem in the following example: values = { 'url': 'http://blabla.com', 'link' : 'http://blabla.com', 'username' : 'user', 'spot' : 0, 'views' : 10, 'date' : 3232312, 'private' : 1, } query = """insert into hyves.Image (URL, StaticLink , HostUsername, SpotCount, ViewCount, UploadDate) values ('%(url)','%(link)','%(username)',%(spot),%(views),%(date), %(private) )""" % values print query It gives me the following error:ValueError: unsupported format character ''' (0x27) at index 106. Can anyone help me? A: Never use string formatting for composing sql queries like that! Use your database module to do the interpolation -- it will do it with correct escaping, so that this doesn't happen to you: http://xkcd.com/327/ In case you want to use that formatting for different things than sql, use %(foo)s (or d, or whatever format you need). A: You are missing the format characters, i.e.: "INSERT INTO ... %(url)s, ..." % values ...if you want to format URL as a string. A: You need to specify explicit conversion flags: query = """insert into hyves.Image (URL, StaticLink , HostUsername, SpotCount, ViewCount, UploadDate) values (%(url)s,%(link)s,%(username)s,%(spot)i,%(views)i,%(date)i, %(private)i )""" % values
Python 2.5 String formatting problem!
I am trying to use the python 2.5 string formatting however I have run into problem in the following example: values = { 'url': 'http://blabla.com', 'link' : 'http://blabla.com', 'username' : 'user', 'spot' : 0, 'views' : 10, 'date' : 3232312, 'private' : 1, } query = """insert into hyves.Image (URL, StaticLink , HostUsername, SpotCount, ViewCount, UploadDate) values ('%(url)','%(link)','%(username)',%(spot),%(views),%(date), %(private) )""" % values print query It gives me the following error:ValueError: unsupported format character ''' (0x27) at index 106. Can anyone help me?
[ "Never use string formatting for composing sql queries like that! Use your database module to do the interpolation -- it will do it with correct escaping, so that this doesn't happen to you: http://xkcd.com/327/\nIn case you want to use that formatting for different things than sql, use %(foo)s (or d, or whatever f...
[ 9, 3, 3 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0003700689_python_string_formatting.txt
Q: Forwarding __getitem__ to getattr Can someone explain what is happening here? class Test(object): __getitem__ = getattr t = Test() t['foo'] gives error (in Python 2.7 and 3.1): TypeError: getattr expected at least 2 arguments, got 1 whereas: def f(*params): print params # or print(params) in 3.1 class Test(object): __getitem__ = f prints the two parameters I'd expect. A: Confusingly, built-in functions (and certain other types of callables) do not become bound methods as normal functions do when used in a class: >>> class Foo(object): __getitem__ = getattr >>> Foo().__getitem__ <built-in function getattr> Compared to: >>> def ga(*args): return getattr(*args) >>> class Foo(object): __getitem__ = ga >>> Foo().__getitem__ <bound method Foo.ga of <__main__.Foo object at 0xb77ad94c>> So, getattr is not correctly receiving the first ('self') parameter. You'll need to write a normal method to wrap it. A: getattr is being called without the 'self' parameter because it's assigned to an object property. You want to do this: __getitem__ = lambda *a, **k: getattr(*a, **k) That will give you the output you seem to want.
Forwarding __getitem__ to getattr
Can someone explain what is happening here? class Test(object): __getitem__ = getattr t = Test() t['foo'] gives error (in Python 2.7 and 3.1): TypeError: getattr expected at least 2 arguments, got 1 whereas: def f(*params): print params # or print(params) in 3.1 class Test(object): __getitem__ = f prints the two parameters I'd expect.
[ "Confusingly, built-in functions (and certain other types of callables) do not become bound methods as normal functions do when used in a class:\n>>> class Foo(object): __getitem__ = getattr\n>>> Foo().__getitem__\n<built-in function getattr>\n\nCompared to:\n>>> def ga(*args): return getattr(*args)\n>>> class Foo(...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003700865_python.txt
Q: learning pylons now, in django, how easy is it to use sqlalchemy and a different view engine? learning pylons now, in django, how easy is it to use sqlalchemy and a different view engine? Is it hackery or its really easy? That's pretty much the only reason I am using pylons over django. But I like that fact that django has a bigger community and easier to get answers to issues. A: Eric Florenzano gave a great talk about this at PyCon this year called "Using Django in Non-Standard Ways." You can find the slides here (.pdf) and the video of the presentation here. All in all I would say that it's not impossibly hard but you will find some difficulty in using pluggable applications (which is part of what makes the community so great) and the Django admin which are both major selling points for Django.
learning pylons now, in django, how easy is it to use sqlalchemy and a different view engine?
learning pylons now, in django, how easy is it to use sqlalchemy and a different view engine? Is it hackery or its really easy? That's pretty much the only reason I am using pylons over django. But I like that fact that django has a bigger community and easier to get answers to issues.
[ "Eric Florenzano gave a great talk about this at PyCon this year called \"Using Django in Non-Standard Ways.\" You can find the slides here (.pdf) and the video of the presentation here. All in all I would say that it's not impossibly hard but you will find some difficulty in using pluggable applications (which is ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003701027_django_python.txt
Q: Disco/MapReduce: Using results of previous iteration as input to new iteration Currently am implementing PageRank on Disco. As an iterative algorithm, the results of one iteration are used as input to the next iteration. I have a large file which represents all the links, with each row representing a page and the values in the row representing the pages to which it links. For Disco, I break this file into N chunks, then run MapReduce for one round. As a result, I get a set of (page, rank) tuples. I'd like to feed this rank to the next iteration. However, now my mapper needs two inputs: the graph file, and the pageranks. I would like to "zip" together the graph file and the page ranks, such that each line represents a page, it's rank, and it's out links. Since this graph file is separated into N chunks, I need to split the pagerank vector into N parallel chunks, and zip the regions of the pagerank vectors to the graph chunks This all seems more complicated than necessary, and as a pretty straightforward operation (with the quintessential mapreduce algorithm), it seems I'm missing something about Disco that could really simplify the approach. Any thoughts? A: Looks like you'll want to use an init_map for the first pass and then a iter_map for each subsequent iteration. See: http://discoproject.org/doc/faq.html#id7 Can you output python object that include the outlinks, instead of just the (page,rank) tuples? Another option would be to have the outlinks keyed by page somewhere (dict, memcache, kyotocabinet, etc...) and look them up from the mapping function. If you're chaining things with Disco, I don't think you'll want to zip things together in the middle of the workflow.
Disco/MapReduce: Using results of previous iteration as input to new iteration
Currently am implementing PageRank on Disco. As an iterative algorithm, the results of one iteration are used as input to the next iteration. I have a large file which represents all the links, with each row representing a page and the values in the row representing the pages to which it links. For Disco, I break this file into N chunks, then run MapReduce for one round. As a result, I get a set of (page, rank) tuples. I'd like to feed this rank to the next iteration. However, now my mapper needs two inputs: the graph file, and the pageranks. I would like to "zip" together the graph file and the page ranks, such that each line represents a page, it's rank, and it's out links. Since this graph file is separated into N chunks, I need to split the pagerank vector into N parallel chunks, and zip the regions of the pagerank vectors to the graph chunks This all seems more complicated than necessary, and as a pretty straightforward operation (with the quintessential mapreduce algorithm), it seems I'm missing something about Disco that could really simplify the approach. Any thoughts?
[ "Looks like you'll want to use an init_map for the first pass and then a iter_map for each subsequent iteration.\nSee: http://discoproject.org/doc/faq.html#id7\nCan you output python object that include the outlinks, instead of just the (page,rank) tuples?\nAnother option would be to have the outlinks keyed by page...
[ 1 ]
[]
[]
[ "disco", "mapreduce", "python" ]
stackoverflow_0002566402_disco_mapreduce_python.txt
Q: How to check constraints between elements in a list / is this Constraint Programming? I have many variable-sized lists containing instances of the same class with attribute foo, and for every list I must apply rules like: if there's an element foo=A there cannot be elements with foo in [B,C,D] if there's an element foo=X there must by at least one with foo in [Y,Z] there can be between MIN and MAX elements foo=BAR combining the above three rules is probably enough to express any similar constraint I'll ever need. It's something like dependency checking in software packages but I have quantities and lack versions :) a naïve approach would be: R_CONFLICT={ A: [B,C,D] } R_DEPENDS ={ X: [ [Y,Z], W, .. } # means: A depends on either Y or Z, and W R_MIN ={BAR: n, BAZ: m} R_MAX ={BAR: o, BAZ: p} # now just loop over lists to check them.. Is this a problem of Constraint programming? I don't actually need to solve something to get a result, I need to validate my list against some constraints and check if they are satisfied or not. How would you classify this problem and how would you solve it? For what it's worth, I'm coding in Python, but I welcome a generic programming answer :) If it turns out I must delve in constraint programming I'll probably start by trying python-constraint. A: Short answer - yes this could be checked using constraint programming, in effect you are supplying a solution and checking it against constraints rather than having the solver search through domains of potentials for a matching solution. Which kind of makes constraint programming overkill, especially if you are using Python which can quite easily check those kind of conditions. I don't have Python on this machine so there may be a typo/error in this code but it shows what you're after without needing to get involved with constraint programming. conflict = set([B, C , D]) foos = set([x.foo for x in list]) if A in foos: if len(foos & conflict): #Set intersection return false len([x for x in list where x.foo == BAR]) #Gives you number of occurances of BAR Basically I'd say unless the constraints are going to get much more complex or you're going to want to find solutions rather than just test I'd stick with code rather than constraint programming.
How to check constraints between elements in a list / is this Constraint Programming?
I have many variable-sized lists containing instances of the same class with attribute foo, and for every list I must apply rules like: if there's an element foo=A there cannot be elements with foo in [B,C,D] if there's an element foo=X there must by at least one with foo in [Y,Z] there can be between MIN and MAX elements foo=BAR combining the above three rules is probably enough to express any similar constraint I'll ever need. It's something like dependency checking in software packages but I have quantities and lack versions :) a naïve approach would be: R_CONFLICT={ A: [B,C,D] } R_DEPENDS ={ X: [ [Y,Z], W, .. } # means: A depends on either Y or Z, and W R_MIN ={BAR: n, BAZ: m} R_MAX ={BAR: o, BAZ: p} # now just loop over lists to check them.. Is this a problem of Constraint programming? I don't actually need to solve something to get a result, I need to validate my list against some constraints and check if they are satisfied or not. How would you classify this problem and how would you solve it? For what it's worth, I'm coding in Python, but I welcome a generic programming answer :) If it turns out I must delve in constraint programming I'll probably start by trying python-constraint.
[ "Short answer - yes this could be checked using constraint programming, in effect you are supplying a solution and checking it against constraints rather than having the solver search through domains of potentials for a matching solution. Which kind of makes constraint programming overkill, especially if you are us...
[ 4 ]
[]
[]
[ "constraint_programming", "constraints", "python" ]
stackoverflow_0003666246_constraint_programming_constraints_python.txt
Q: Python: `key not in my_dict` but `key in my_dict.keys()` I have a weird situation. I have a dict, self.containing_dict. Using the debug probe, I see that dict's contents and I can see that self is a key of it. But look at this: >>> self in self.containing_dict False >>> self in self.containing_dict.keys() True >>> self.containing_dict.has_key(self) False What's going on? (I will note that this is in a piece of code which gets executed on a weakref callback.) Update: I was asked to show the __hash__ implementation of self. Here it is: def __hash__(self): return hash( ( tuple(sorted(tuple(self.args))), self.star_args, tuple(sorted(tuple(self.star_kwargs))) ) ) args = property(lambda self: dict(self.args_refs)) star_args = property( lambda self: tuple((star_arg_ref() for star_arg_ref in self.star_args_refs)) ) star_kwargs = property(lambda self: dict(self.star_kwargs_refs)) A: The problem you describe can only be caused by self having implemented __eq__ (or __cmp__) without implementing an accompanying __hash__. If you didn't implement a __hash__ method, you should do so -- normally you can't use objects that define __eq__ but not __hash__ as dict keys, but if you inherit a __hash__ that may slip by. If you do implement __hash__, you have to make sure it acts the right way: the result must not change over the lifetime of the object (or at least as long as the object is in use as a dict key or set item), and it must be consistent with __eq__. An object's hash value must be the same as objects it's equal to (according to its __eq__ or __cmp__.) An object's hash value may be different from objects it's not equal to, but it doesn't have to be. The requirements also mean you can not have the result of __eq__ change over the lifetime of the object, which is why mutable objects usually can't be used as dict keys. If your __hash__ and __eq__ are not matched up, Python won't be able to find the object in dicts and sets, but it will still show up in dict.keys() and list(set), which is what you're describing here. The usual way to implement __hash__ methods is by returning the hash() of whatever attributes you use in your __eq__ or __cmp__ method. A: Judging from your __hash__ method, the class stores references to its arguments, and uses that as a hash. The problem is, those arguments are shared with the code that constructed the object. If they change the argument, the hash will change and you won't be able to find the object in any dictionaries it had been in. The arguments need not be anything complicated, just a simple list will do. In [13]: class Spam(object) : ....: def __init__(self, arg) : ....: self.arg = arg ....: def __hash__(self) : ....: return hash(tuple(self.arg,)) In [18]: l = range(5) In [19]: spam = Spam(l) In [20]: hash(spam) Out[20]: -3958796579502723947 If I change the list that I passed as an argument, the hash will change. In [21]: l += [10] In [22]: hash(spam) Out[22]: -6439366262097674983 Since dictionary keys are organized by hash, when I do x in d, the first thing Python does is compute the hash of x, and look in the dictionary for something with that hash value. The problem is, when the hash of an object changes after being put in the dictionary, Python will look at the new hash value, and not see the desired key there. Using the list of keys, forces Python to check each key by equality, bypassing the hash check. A: Most likely you have custom hash and comparison defined for whatever class self is an instance and you mutated self after you added it to the dictionary. If you use a mutable object as a dictionary key then after you mutate it you may not be able to access it in the dictionary but it will still appear in the keys() result.
Python: `key not in my_dict` but `key in my_dict.keys()`
I have a weird situation. I have a dict, self.containing_dict. Using the debug probe, I see that dict's contents and I can see that self is a key of it. But look at this: >>> self in self.containing_dict False >>> self in self.containing_dict.keys() True >>> self.containing_dict.has_key(self) False What's going on? (I will note that this is in a piece of code which gets executed on a weakref callback.) Update: I was asked to show the __hash__ implementation of self. Here it is: def __hash__(self): return hash( ( tuple(sorted(tuple(self.args))), self.star_args, tuple(sorted(tuple(self.star_kwargs))) ) ) args = property(lambda self: dict(self.args_refs)) star_args = property( lambda self: tuple((star_arg_ref() for star_arg_ref in self.star_args_refs)) ) star_kwargs = property(lambda self: dict(self.star_kwargs_refs))
[ "The problem you describe can only be caused by self having implemented __eq__ (or __cmp__) without implementing an accompanying __hash__. If you didn't implement a __hash__ method, you should do so -- normally you can't use objects that define __eq__ but not __hash__ as dict keys, but if you inherit a __hash__ tha...
[ 5, 2, 0 ]
[]
[]
[ "dictionary", "hash", "python" ]
stackoverflow_0003701220_dictionary_hash_python.txt
Q: Is there a Python package to parse readable data files with sections I am looking for a method to parse readable (i.e., not binary) data files with sections. I had been using ConfigObj to read config files (INI files?), but I ran into a problem with multi-line lists. Specifically, ConfigObj does not allow list members to contain carriage returns. In other words, the following fails to parse: [section] data = [(1, 0.1), (2, 0.2), (3, 0.3)] Removing the carriage returns fixes the problem [section] data = [(1, 0.1), (2, 0.2), (3, 0.3)] Obviously, I could just use this simple fix, but the readability suffers significantly when the data extends beyond a single line. Is there an alternate config-file parser that would work here? Alternatively, are there parsers for csv files with sections? For example, something that could parse [data1] 1, 0.1 2, 0.2 3, 0.3 [data2] 1, 0.1 2, 0.2 3, 0.3 I considered JSON files but I wasn't quite happy with the look of the data files. NOTE: the 1, 2, 3 columns are just for illustration: it is not my intent to save row numbers. A: Take at look at YAML files. There is a Python module called pyyaml to read those. I find YAML to be pretty readable. A: ConfigParser is another standard library module that should let you read files like this: [section] data = row1, 1, 2 row2, 2, 3 row3, 3, 4 A: If not json, then maybe YAML? http://pyyaml.org/
Is there a Python package to parse readable data files with sections
I am looking for a method to parse readable (i.e., not binary) data files with sections. I had been using ConfigObj to read config files (INI files?), but I ran into a problem with multi-line lists. Specifically, ConfigObj does not allow list members to contain carriage returns. In other words, the following fails to parse: [section] data = [(1, 0.1), (2, 0.2), (3, 0.3)] Removing the carriage returns fixes the problem [section] data = [(1, 0.1), (2, 0.2), (3, 0.3)] Obviously, I could just use this simple fix, but the readability suffers significantly when the data extends beyond a single line. Is there an alternate config-file parser that would work here? Alternatively, are there parsers for csv files with sections? For example, something that could parse [data1] 1, 0.1 2, 0.2 3, 0.3 [data2] 1, 0.1 2, 0.2 3, 0.3 I considered JSON files but I wasn't quite happy with the look of the data files. NOTE: the 1, 2, 3 columns are just for illustration: it is not my intent to save row numbers.
[ "Take at look at YAML files. There is a Python module called pyyaml to read those. I find YAML to be pretty readable.\n", "ConfigParser is another standard library module that should let you read files like this:\n[section]\ndata = \n row1, 1, 2\n row2, 2, 3\n row3, 3, 4\n\n", "If not json, then may...
[ 3, 2, 0 ]
[]
[]
[ "csv", "parsing", "python" ]
stackoverflow_0003701696_csv_parsing_python.txt
Q: Installing Libraries on a Server I'm fairly noob at the using the terminal and doing server administration. I recently "inherited" a Twitter app, and I need to install a Python OAuth library: http://dev.twitter.com/pages/oauth_libraries#python Unfortunately, I'm pretty much clueless about how to: download a library to the server installing the library on the server so I can "import " Can someone please walk me through this process? Or, provide me with resources that will? Thanks!! A: The easiest solution is probably to run 'easy_install' as root using the same python that runs the application (there may be different versions of python). You may need to install a package such as 'setuptools' first, or download and run the easy_install-installer as follows: # wget http://peak.telecommunity.com/dist/ez_setup.py # python ./ez_setup.py But again, only do this if you don't have easy_install A: The 'best' way to do it depends on how you run your application (mod_python, cgi or wsgi). With WSGI the best way would be to have a seperate virtualenv for each site in which you install things for that site only. This way you can have different versions of the same library installed which is also a big plus for development but even more so for websites where you might want to keep one website on the older version of a lib and another on the newer version. A few links to get you started: WSGI + virtualenv, virtualenv Any question you can add as a comment.
Installing Libraries on a Server
I'm fairly noob at the using the terminal and doing server administration. I recently "inherited" a Twitter app, and I need to install a Python OAuth library: http://dev.twitter.com/pages/oauth_libraries#python Unfortunately, I'm pretty much clueless about how to: download a library to the server installing the library on the server so I can "import " Can someone please walk me through this process? Or, provide me with resources that will? Thanks!!
[ "The easiest solution is probably to run 'easy_install' as root using the same python that runs the application (there may be different versions of python). You may need to install a package such as 'setuptools' first, or download and run the easy_install-installer as follows:\n# wget http://peak.telecommunity.com...
[ 0, 0 ]
[]
[]
[ "libraries", "python", "server_administration" ]
stackoverflow_0003701324_libraries_python_server_administration.txt
Q: Deterministic key serialization I'm writing a mapping class which persists to the disk. I am currently allowing only str keys but it would be nice if I could use a couple more types: hopefully up to anything that is hashable (ie. same requirements as the builtin dict), but more reasonable I would accept string, unicode, int, and tuples of these types. To that end I would like to derive a deterministic serialization scheme. Option 1 - Pickling the key The first thought I had was to use the pickle (or cPickle) module to serialize the key, but I noticed that the output from pickle and cPickle do not match each other: >>> import pickle >>> import cPickle >>> def dumps(x): ... print repr(pickle.dumps(x)) ... print repr(cPickle.dumps(x)) ... >>> dumps(1) 'I1\n.' 'I1\n.' >>> dumps('hello') "S'hello'\np0\n." "S'hello'\np1\n." >>> dumps((1, 2, 'hello')) "(I1\nI2\nS'hello'\np0\ntp1\n." "(I1\nI2\nS'hello'\np1\ntp2\n." Is there any implementation/protocol combination of pickle which is deterministic for some set of types (e.g. can only use cPickle with protocol 0)? Option 2 - Repr and ast.literal_eval Another option is to use repr to dump and ast.literal_eval to load. I have written a function to determine if a given key would survive this process (it is rather conservative on the types it allows): def is_reprable_key(key): return type(key) in (int, str, unicode) or (type(key) == tuple and all( is_reprable_key(x) for x in key)) The question for this method is if repr itself is deterministic for the types that I have allowed here. I believe this would not survive the 2/3 version barrier due to the change in str/unicode literals. This also would not work for integers where 2**32 - 1 < x < 2**64 jumping between 32 and 64 bit platforms. Are there any other conditions (ie. do strings serialize differently under different conditions in the same interpreter)? Edit: I'm just trying to understand the conditions that this breaks down, not necessarily overcome them. Option 3: Custom repr Another option which is likely overkill is to write my own repr which flattens out the things of repr which I know (or suspect may be) a problem. I just wrote an example here: http://gist.github.com/423945 (If this all fails miserably then I can store the hash of the key along with the pickle of both the key and value, then iterate across rows that have a matching hash looking for one that unpickles to the expected key, but that really does complicate a few other things and I would rather not do it. Edit: it turns out that the builtin hash is not deterministic across platforms either. Scratch that.) Any insights? A: Important note: repr() is not deterministic if a dictionary or set type is embedded in the object you are trying to serialize. The keys could be printed in any order. For example print repr({'a':1, 'b':2}) might print out as {'a':1, 'b':2} or {'b':2, 'a':1}, depending on how Python decides to manage the keys in the dictionary. A: After reading through much of the source (of CPython 2.6.5) for the implementation of repr for the basic types I have concluded (with reasonable confidence) that repr of these types is, in fact, deterministic. But, frankly, this was expected. I believe that the repr method is susceptible to nearly all of the same cases under which the marshal method would break down (longs > 2**32 can never be an int on a 32bit machine, not guaranteed to not change between versions or interpreters, etc.). My solution for the time being has been to use the repr method and write a comprehensive test suite to make sure that repr returns the same values on the various platforms I am using. In the long run the custom repr function would flatten out all platform/implementation differences, but is certainly overkill for the project at hand. I may do this in the future, however. A: "Any value which is an acceptable key for a builtin dict" is not feasible: such values include arbitrary instances of classes that don't define __hash__ or comparisons, implicitly using their id for hashing and comparison purposes, and the ids won't be the same even across runs of the very same program (unless those runs are strictly identical in all respects, which is very tricky to arrange -- identical inputs, identical starting times, absolutely identical environment, etc, etc). For strings, unicodes, ints, and tuples whose items are all of these kinds (including nested tuples), the marshal module could help (within a single version of Python: marshaling code can and does change across versions). E.g.: >>> marshal.dumps(23) 'i\x17\x00\x00\x00' >>> marshal.dumps('23') 't\x02\x00\x00\x0023' >>> marshal.dumps(u'23') 'u\x02\x00\x00\x0023' >>> marshal.dumps((23,)) '(\x01\x00\x00\x00i\x17\x00\x00\x00' This is Python 2; Python 3 would be similar (except that all the representation of these byte strings would have a leading b, but that's a cosmetic issue, and of course u'23' becomes invalid syntax and '23' becomes a Unicode string). You can see the general idea: a leading byte represents the type, such as u for Unicode strings, i for integers, ( for tuples; then for containers comes (as a little-endian integer) the number of items followed by the items themselves, and integers are serialized into a little-endian form. marshal is designed to be portable across platforms (for a given version; not across versions) because it's used as the underlying serializations in compiled bytecode files (.pyc or .pyo). A: You mention a few requirements in the paragraph, and I think you might want to be a little more clear on these. So far I gather: You're building an SQLite backend to basically a dictionary. You want to allow the keys to be more than basestring type (which types). You want it to survive the Python 2 -> Python 3 barrier. You want to support large integers above 2**32 as the key. Ability to store infinite values (because you don't want hash collisions). So, are you trying to build a general 'this can do it all' solution, or just trying to solve an immediate problem to continue on within a current project? You should spend a little more time to come up with a clear set of requirements. Using a hash seemed like the best solution to me, but then you complain that you're going to have multiple rows with the same hash implying you're going to be storing enough values to even worry about the hash.
Deterministic key serialization
I'm writing a mapping class which persists to the disk. I am currently allowing only str keys but it would be nice if I could use a couple more types: hopefully up to anything that is hashable (ie. same requirements as the builtin dict), but more reasonable I would accept string, unicode, int, and tuples of these types. To that end I would like to derive a deterministic serialization scheme. Option 1 - Pickling the key The first thought I had was to use the pickle (or cPickle) module to serialize the key, but I noticed that the output from pickle and cPickle do not match each other: >>> import pickle >>> import cPickle >>> def dumps(x): ... print repr(pickle.dumps(x)) ... print repr(cPickle.dumps(x)) ... >>> dumps(1) 'I1\n.' 'I1\n.' >>> dumps('hello') "S'hello'\np0\n." "S'hello'\np1\n." >>> dumps((1, 2, 'hello')) "(I1\nI2\nS'hello'\np0\ntp1\n." "(I1\nI2\nS'hello'\np1\ntp2\n." Is there any implementation/protocol combination of pickle which is deterministic for some set of types (e.g. can only use cPickle with protocol 0)? Option 2 - Repr and ast.literal_eval Another option is to use repr to dump and ast.literal_eval to load. I have written a function to determine if a given key would survive this process (it is rather conservative on the types it allows): def is_reprable_key(key): return type(key) in (int, str, unicode) or (type(key) == tuple and all( is_reprable_key(x) for x in key)) The question for this method is if repr itself is deterministic for the types that I have allowed here. I believe this would not survive the 2/3 version barrier due to the change in str/unicode literals. This also would not work for integers where 2**32 - 1 < x < 2**64 jumping between 32 and 64 bit platforms. Are there any other conditions (ie. do strings serialize differently under different conditions in the same interpreter)? Edit: I'm just trying to understand the conditions that this breaks down, not necessarily overcome them. Option 3: Custom repr Another option which is likely overkill is to write my own repr which flattens out the things of repr which I know (or suspect may be) a problem. I just wrote an example here: http://gist.github.com/423945 (If this all fails miserably then I can store the hash of the key along with the pickle of both the key and value, then iterate across rows that have a matching hash looking for one that unpickles to the expected key, but that really does complicate a few other things and I would rather not do it. Edit: it turns out that the builtin hash is not deterministic across platforms either. Scratch that.) Any insights?
[ "Important note: repr() is not deterministic if a dictionary or set type is embedded in the object you are trying to serialize. The keys could be printed in any order.\nFor example print repr({'a':1, 'b':2}) might print out as {'a':1, 'b':2} or {'b':2, 'a':1}, depending on how Python decides to manage the keys in t...
[ 3, 2, 1, 0 ]
[]
[]
[ "pickle", "python", "serialization" ]
stackoverflow_0002966684_pickle_python_serialization.txt
Q: How to convert raw html from the web into parsable xml in Python I thought BeautifulSoup could do that, but it does not seem to do the trick. What method have you already used, and is long term reliable ? A: You could use the lxml library, specifically lxml.html which gives you an ETree object which you can then serialize as XML with (amongst others) the .tostring() method. If this fails on your HTML (it is too broken) you can use ElementSoup (an extension on BeautifulSoup) to build a lxml.html tree. A: You can try http://utidylib.berlios.de/ , a python wrapper for tidy library. Tidy works well in most cases. For something more robust (or at least more browser-like), I guess you could try webkit or gecko. I'm not sure the wrappers responsible for cleaning HTML are available, but you can have a look.
How to convert raw html from the web into parsable xml in Python
I thought BeautifulSoup could do that, but it does not seem to do the trick. What method have you already used, and is long term reliable ?
[ "You could use the lxml library, specifically lxml.html which gives you an ETree object which you can then serialize as XML with (amongst others) the .tostring() method. \nIf this fails on your HTML (it is too broken) you can use ElementSoup (an extension on BeautifulSoup) to build a lxml.html tree.\n", "You can ...
[ 4, 2 ]
[]
[]
[ "html", "python", "python_3.x", "xml" ]
stackoverflow_0003616934_html_python_python_3.x_xml.txt
Q: detect new or modified files with python I'm trying to detect when a new file is created a directory or when an existing file is modified in a directory. I tried searching for a script that would do this (preferably in python or bash) but came up short. My environment is linux with Python 2.6 Related Question A: You can use gio which is the Filesystem part of GLib (In GLib's python bindings) import gio def directory_changed(monitor, file1, file2, evt_type): if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED, gio.FILE_MONITOR_EVENT_DELETED)): print "Changed:", file1, file2, evt_type gfile = gio.File(".") monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None) monitor.connect("changed", directory_changed) however, your program must be running a GLib mainloop for the events to arrive. One quick way to test that is by using: import glib ml = glib.MainLoop() ml.run() GLib is a high-level library which is well suited for Applications. You don't have to care about which underlying system it uses for the file monitoring. I now see you use Fedora Core 2. Really version 2? That might be too old to use GIO in GLib. Pyinotify that has been mentioned might be a better solution, although less portable. A: If you're using Linux, you may try pyinotify that acts like an object-oriented wrapper around the inotify(7) system calls. The project website contains quite straightforward tutorials and examples. A: If you can use PyQt, there's QFileSystemWatcher that does just this. A: There are also Python bindings for gamin.
detect new or modified files with python
I'm trying to detect when a new file is created a directory or when an existing file is modified in a directory. I tried searching for a script that would do this (preferably in python or bash) but came up short. My environment is linux with Python 2.6 Related Question
[ "You can use gio which is the Filesystem part of GLib (In GLib's python bindings)\nimport gio\n\ndef directory_changed(monitor, file1, file2, evt_type):\n if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED,\n gio.FILE_MONITOR_EVENT_DELETED)):\n print \"Changed:\", file1, file2, evt_type\n\ngfile = gio.Fi...
[ 13, 4, 1, 0 ]
[]
[]
[ "file", "filesystems", "linux", "python" ]
stackoverflow_0001618853_file_filesystems_linux_python.txt
Q: trying to install MySQL-python-1.2.3 but I get an error Here tis the error I get while trying to install MySQL-python-1.2.3. any idea's? Traceback (most recent call last): File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup.py", line 15, in <module> metadata, options = get_config() File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup_windows.py", line 7, in get_config serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key']) WindowsError: [Error 2] The system cannot find the file specified Trying to install this on Python 2.7 on a windows xp machine A: Please take a look at this page: http://www.lfd.uci.edu/~gohlke/pythonlibs/ and search for "MySQL-python". You'll find some pre-compiled packages of MySQL-python for Windows. Maybe one of them will be ok for you. Using one of them (for Windows 7) was the only way I found to make MySQL-python work on Windows. A: There is a step by step on how to get around this problem here: http://www.fuyun.org/2009/12/install-mysql-for-python-on-windows/
trying to install MySQL-python-1.2.3 but I get an error
Here tis the error I get while trying to install MySQL-python-1.2.3. any idea's? Traceback (most recent call last): File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup.py", line 15, in <module> metadata, options = get_config() File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup_windows.py", line 7, in get_config serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key']) WindowsError: [Error 2] The system cannot find the file specified Trying to install this on Python 2.7 on a windows xp machine
[ "Please take a look at this page: http://www.lfd.uci.edu/~gohlke/pythonlibs/ and search for \"MySQL-python\". You'll find some pre-compiled packages of MySQL-python for Windows. Maybe one of them will be ok for you.\nUsing one of them (for Windows 7) was the only way I found to make MySQL-python work on Windows.\n"...
[ 9, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003685111_mysql_python.txt
Q: Accessing data files before and after distutils/setuptools I'm doing a platform independent PyQt application. I intend to use write a setup.py files using setuptools. So far I've managed to detech platform, e.g. load specific options for setup() depending on platform in order to use py2exe on Windows... etc... However, with my application I'm distributing some themes, HTML and images, I need to load these images in the application at runtime. So far they are stored in the themes/ directory of the application. I've been reading documentation on setuptools and distutils, and figured out that if I gave setup() the data_files options with all the files in the themes/ directory to be installed in "share/MyApp/themes/" it would be installed with a /usr/ prefix, or whatever sys.prefix is on the platform. I assume that I would find the data files using os.path.join(sys.prefix, "share", "MyApp", "themes") nomatter what platform I'm on, right? However, I want to be able to access the data files during development too, where they reside in the themes/ directory relative to application source. How do I do this? Is there some smart way to figure out whether the application has been installed? Or a utility that maps to the data files regardless of where they are, at the moment? I would really hate to add all sorts of ugly hacks to see if there are themes relative to the source, or in sys.prefix/share... etc... How do I find there data files during development? and after install on arbitrary platform ? A: You could try pkg_resources: my_data = pkg_resources.resource_string(__name__, fname) A: I've used a utility method called data_file: def data_file(fname): """Return the path to a data file of ours.""" return os.path.join(os.path.split(__file__)[0], fname) I put this in the init.py file in my project, and then call it from anywhere in my package to get a file relative to the package. Setuptools offers a similar function, but this doesn't need setuptools. A: You should use the pkgutil/pkg_resources module to load the data files. It even works from within ziped eggs.
Accessing data files before and after distutils/setuptools
I'm doing a platform independent PyQt application. I intend to use write a setup.py files using setuptools. So far I've managed to detech platform, e.g. load specific options for setup() depending on platform in order to use py2exe on Windows... etc... However, with my application I'm distributing some themes, HTML and images, I need to load these images in the application at runtime. So far they are stored in the themes/ directory of the application. I've been reading documentation on setuptools and distutils, and figured out that if I gave setup() the data_files options with all the files in the themes/ directory to be installed in "share/MyApp/themes/" it would be installed with a /usr/ prefix, or whatever sys.prefix is on the platform. I assume that I would find the data files using os.path.join(sys.prefix, "share", "MyApp", "themes") nomatter what platform I'm on, right? However, I want to be able to access the data files during development too, where they reside in the themes/ directory relative to application source. How do I do this? Is there some smart way to figure out whether the application has been installed? Or a utility that maps to the data files regardless of where they are, at the moment? I would really hate to add all sorts of ugly hacks to see if there are themes relative to the source, or in sys.prefix/share... etc... How do I find there data files during development? and after install on arbitrary platform ?
[ "You could try pkg_resources:\nmy_data = pkg_resources.resource_string(__name__, fname)\n\n", "I've used a utility method called data_file:\ndef data_file(fname):\n \"\"\"Return the path to a data file of ours.\"\"\"\n return os.path.join(os.path.split(__file__)[0], fname)\n\nI put this in the init.py file ...
[ 7, 6, 6 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0001219367_distutils_python_setuptools.txt
Q: measuring page request timing in pylons app? How can I test the time it takes to render a pylons page request? Where do I hook this in? (and what class/method do I use to output this information) I'm sort of new to both pylons and python. A: There are several ways you could do this and it depends on whether you want to do with for profiling/testing or for production. If you want to profile then the simplest thing to setup is repoze.profile. It is a WSGI middleware that profiles everything that happens after it in the WSGI stack. To use put it just before your app in your middleware.py For example: # The Pylons WSGI app app = PylonsApp() #Profile the app app = AccumulatingProfileMiddleware( app, log_filename='/profiling.log', cachegrind_filename='/cachegrind.out', discard_first_request=True, flush_at_shutdown=True, path='/__profile__' ) This will profile just your app and give you a web page where you can look at the output. Be aware the output takes some getting used to and if you are using SqlAlchemy most of the calls will be in there. DO NOT use this is production environment as it adds massive overhead If you want the page times for testing then using the timeit module and the pylons url() method will allow you to test the rendering of a single page. If I have time to put together a sample I'll add it to this answer.
measuring page request timing in pylons app?
How can I test the time it takes to render a pylons page request? Where do I hook this in? (and what class/method do I use to output this information) I'm sort of new to both pylons and python.
[ "There are several ways you could do this and it depends on whether you want to do with for profiling/testing or for production.\nIf you want to profile then the simplest thing to setup is repoze.profile. It is a WSGI middleware that profiles everything that happens after it in the WSGI stack.\nTo use put it just b...
[ 3 ]
[]
[]
[ "performance", "pylons", "python" ]
stackoverflow_0003692287_performance_pylons_python.txt
Q: constructor params vs. method calls I write a URL router in Python 3.1 and wonder whether it is more than a matter of taste to use one of the following variants: Tuples as constructor params: router = Router( (r"/item/{id}", ItemResource()), (r"/article/{title}", ArticleResource()) ) Method calls router = Router() router.connect(r"/item/{id}", ItemResource()) router.connect(r"/article/{title}", ArticleResource()) Do you see any advantages or disadvantages here? A: The traditional OOP view is that the constructor should guarantee that an object is in its final, usable state -- that is, the state may change, of course, if there are dynamically changing requirements (e.g. is there a disconnect method to go with that connect, and an actual app requirement to enable the dynamic changing of routing in the course of operations?), but it "should" stay usable from the moment the object is born, to when it goes away. In the real world, the alternative pattern sometimes known as "two-phase construction" (though here it might be more than just two phases of course, as you keep calling connect;-) may have some advantages in terms of flexibility -- persisting and de-persisting objects, building them right dependently on configuration files, easing dependency injection and mocking (and therefore testing). Whether you're actually going to take advantage of these flexibility aspects, is a question you can answer better than we can... since you best know your app's exact requirements and your own skill and preferences in OO development, testing, &c. If you're not, in fact, going to use the flexibility aspects, then it's simpler to omit them altogether, and go with the "traditional self-sufficient constructor" OOP approach. A: I favor passing the tuples to the constructor for two reasons that Alex didn't mention (at least not explicitly). Readability. If is plain to any reader of the code that the Router instance requires a list of routes to be usable. Lose coupling. Client code does not have to bother with initializing Router instances. This is the responsibility of the Router class. If this is feeling bulky to you, I would recommend breaking the Router class into smaller classes and passing instances of those classes to Router.__init__. For example, here you could have a RoutesList class: routes = RoutesList((r"/item/{id}", ItemResource()), (r"/article/{title}", ArticleResource())) router = Router(routes) This buys you the flexibility of the two phase construction that Alex mentioned but also prevents client code from being responsible from initializing the router class. This still preserves readability because you have to read backwards to see what routes is and not forward (if you don't happen to remember). It has the added advantage that if you should decide to change how you are representing your routes, the Router class shouldn't have to change at all: all such changes should be encapsulated in the RoutesList class (or perhaps even in an as of yet undefined Route class). Or routes could just be a list of tuples and you could have a module level function to map the route to the controller ;) A: Unless the parameter are mandatory, you could use the method call approach which would be more flexible if you need to add more in the future. If you must use both parameters for your instance to be valid, use the constructor approach. A: Since you are building a router to route web request to appropriate resource, you can also look into Routes. It allows you to map URLs to your application’s actions. http://routes.groovie.org/
constructor params vs. method calls
I write a URL router in Python 3.1 and wonder whether it is more than a matter of taste to use one of the following variants: Tuples as constructor params: router = Router( (r"/item/{id}", ItemResource()), (r"/article/{title}", ArticleResource()) ) Method calls router = Router() router.connect(r"/item/{id}", ItemResource()) router.connect(r"/article/{title}", ArticleResource()) Do you see any advantages or disadvantages here?
[ "The traditional OOP view is that the constructor should guarantee that an object is in its final, usable state -- that is, the state may change, of course, if there are dynamically changing requirements (e.g. is there a disconnect method to go with that connect, and an actual app requirement to enable the dynamic ...
[ 2, 2, 0, 0 ]
[]
[]
[ "constructor", "oop", "parameters", "python" ]
stackoverflow_0003702954_constructor_oop_parameters_python.txt
Q: How to know if I run python from Textmate/emacs? I use TextMate to debug python script, as I like the feature of using 'Command-R' for running python from TextMate, and I learned that emacs provide similar feature. I need to know if the python is run from command line or from TextMate/emacs. How can I do that? ADDED I use TextMate for python coding/debugging, and it's pretty useful. But, sometimes I need to run the test using command line. I normally turn on debugging/logging mode with TextMate, and off with command line mode. This is the reason I asked the question. Also, I plan to use emacs for python debugging, so I wanted to ask the case for emacs. I got an answer in the case with emacs, and I happen to solve this issue with TextMate. Set variables in Preferences -> Advanced -> Shell Variables, and I found that TM_ORGANIZATION_NAME is already there to be used. So, I'll just use this variable. Use this variable, if os.environ['TM_ORGANIZATION_NAME']: return True I guess the shell variable from TextMate disappear when I'm done using it. A: For Emacs: If python is run as an inferior process, then the environment variable INSIDE_EMACS will be set. From docs: Emacs sets the environment variable INSIDE_EMACS in the subshell to a comma-separated list including the Emacs version. Programs can check this variable to determine whether they are running inside an Emacs subshell. A: sys.argv will tell you how Python was invoked. I don't know about TextMate, but when I tell Emacs to eval buffer, its value is ['-c']. That means it's executing a specified command, according to the man page. If Python's run directly from the command line with no parameters, sys.argv will be []. If you run a python script, it will have the script name and whatever arguments you pass it. You might want to set up your python-mode in Emacs and whatever the equivalent in TextMate is to put something special like -t in the command line. That's pretty hackish though. Maybe there's a better way. A: From the docs for sys.path: As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. So if sys.path[0]: # python was run interactively else: # python is running a script. Or, for example, from the IPython prompt (inside Emacs): In [65]: sys.path Out[65]: ['', <-------------------- first entry is empty string '/usr/bin', '/usr/local/lib/python2.6/dist-packages/scikits.statsmodels-0.2.0-py2.6.egg', '/usr/local/lib/python2.6/dist-packages/pyinterval-1.0b21-py2.6-linux-i686.egg', ... ] A: Use Command-R to run the script directly Use Shift-Command-R to run the script from terminal.
How to know if I run python from Textmate/emacs?
I use TextMate to debug python script, as I like the feature of using 'Command-R' for running python from TextMate, and I learned that emacs provide similar feature. I need to know if the python is run from command line or from TextMate/emacs. How can I do that? ADDED I use TextMate for python coding/debugging, and it's pretty useful. But, sometimes I need to run the test using command line. I normally turn on debugging/logging mode with TextMate, and off with command line mode. This is the reason I asked the question. Also, I plan to use emacs for python debugging, so I wanted to ask the case for emacs. I got an answer in the case with emacs, and I happen to solve this issue with TextMate. Set variables in Preferences -> Advanced -> Shell Variables, and I found that TM_ORGANIZATION_NAME is already there to be used. So, I'll just use this variable. Use this variable, if os.environ['TM_ORGANIZATION_NAME']: return True I guess the shell variable from TextMate disappear when I'm done using it.
[ "For Emacs: If python is run as an inferior process, then the environment variable INSIDE_EMACS will be set.\nFrom docs:\n\nEmacs sets the environment variable\n INSIDE_EMACS in the subshell to a\n comma-separated list including the\n Emacs version. Programs can check this\n variable to determine whether they a...
[ 4, 1, 1, 0 ]
[]
[]
[ "emacs", "environment", "python", "textmate" ]
stackoverflow_0003702889_emacs_environment_python_textmate.txt
Q: Pygame installation on Windows - error: Unable to find vcvarsall.bat I have a Win7 64 bit dev machine. I've downloaded and installed Python 2.6.6 32bit. I've also downloaded pygame 1.9.1 for python 2.6 and tried to install it. I got: C:\pygame-1.9.1release>setup.py install .... running build_ext building 'pygame._numericsurfarray' extension error: Unable to find vcvarsall.bat What should I do? (I don't have any compiler or visual studio or anything installed, if it's relevant) A: On PyGame's download page - use the msi file which is a dedicated Windows installation instead of downloading the source and executing: setup.py install A: I had a similar problem with a package (Traits) a couple of weeks ago - for me it was because the package was trying to compile extensions and I didn't have Visual Studio. What worked for me was to install MinGW and direct Python to use it as the compiler in the distutils.cfg config file under \Lib\distutils in your Python installation folder. Looks like this page can automate the whole process for you; if you'd prefer to do it manually here's the contents of my distutils.cfg: [build] compiler=mingw32 Rerun setup.py and you should be good to go.
Pygame installation on Windows - error: Unable to find vcvarsall.bat
I have a Win7 64 bit dev machine. I've downloaded and installed Python 2.6.6 32bit. I've also downloaded pygame 1.9.1 for python 2.6 and tried to install it. I got: C:\pygame-1.9.1release>setup.py install .... running build_ext building 'pygame._numericsurfarray' extension error: Unable to find vcvarsall.bat What should I do? (I don't have any compiler or visual studio or anything installed, if it's relevant)
[ "On PyGame's download page - use the msi file which is a dedicated Windows installation instead of downloading the source and executing:\nsetup.py install\n\n", "I had a similar problem with a package (Traits) a couple of weeks ago - for me it was because the package was trying to compile extensions and I didn't ...
[ 4, 2 ]
[]
[]
[ "installation", "pygame", "python" ]
stackoverflow_0003691188_installation_pygame_python.txt
Q: Set position of image in a window using pygtk Is it possible to set the position of an image using pygtk? import pygtk import gtk class Example: self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.image = gtk.Image() self.image.set_from_file("example.png") # Position goes here (it should, shouldn't it?) self.window.add(self.image) self.image.show() self.window.fullscreen() self.window.show_all() A: GTK lays widgets out based on relative alignments and padding, not absolute pixel positions. Instances of gtk.Image have properties xalign, xpad, yalign, ypad that can be used to position the widget if the parent has more space than is needed. For example self.image.xalign = 0.5 self.image.yalign = 0.5 would center the image in the window self.image.xalign = 0 self.image.yalign = 0 would place the image in the upper left self.image.xalign = 1 self.image.yalign = 1 would place the image in the bottom right If you really want to deal with fixed positions then you need to use the gtk.Fixed widget. It allows to specify an explicit position when adding a child through the method put(child, x, y). Heed the warning in the documentation, though, that it's a bad idea and will make for a broken UI.
Set position of image in a window using pygtk
Is it possible to set the position of an image using pygtk? import pygtk import gtk class Example: self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.image = gtk.Image() self.image.set_from_file("example.png") # Position goes here (it should, shouldn't it?) self.window.add(self.image) self.image.show() self.window.fullscreen() self.window.show_all()
[ "GTK lays widgets out based on relative alignments and padding, not absolute pixel positions. Instances of gtk.Image have properties xalign, xpad, yalign, ypad that can be used to position the widget if the parent has more space than is needed.\nFor example\nself.image.xalign = 0.5\nself.image.yalign = 0.5\n\nwould...
[ 1 ]
[]
[]
[ "image", "position", "pygtk", "python" ]
stackoverflow_0003703509_image_position_pygtk_python.txt
Q: Php/Cakephp interface with Python script I have a webapp, created using CakePhp. I need to interface with a Python script. What is the best way to go about doing that? (I could use pipe etc., but I want to check what the best practices are) Thanks. A: It really depends what you're looking for. If you are going to be interfacing with python extensively, then I would recommend looking into an XML-RPC solution. Details on how to configure an XML-RPC server using Twisted (Python) can be found here: http://twistedmatrix.com/documents/10.1.0/web/howto/xmlrpc.html Documentation on creating an XML-RPC client in PHP: http://devzone.zend.com/article/1307 This solution may not be the cake-iest solution, but it works well as a vendor. If what your looking for is more of a one off type of deal, then using exec() would be much easier, though not the cleanest way. A: First of all, check what kinds of syndication CakePHP offers. It may expose part of its API through xmlrpc, json, RSS, and so on. If that's not an option, connect directly to the same database the CakePHP application uses. Or alternatively, implement some php code within your CakePHP framework that expors relevant data as JSON and interface with it. A: What sort of interface? Two way? One way? I haven't done this as I'm not a Python programmer (yet), but there are many ways to expose/access cake - URL/param/param , POST, GET, RSS, whatever. Take a look at the request handler: http://book.cakephp.org/view/1292/Obtaining-Request-Information I don't know whether you're a Python or a CakePHP programmer, but if you're the former, the book: http://book.cakephp.org does tend to cover most things and is fairly logically laid out (whatever CodeIgniter/Symphony/Kohana fans might say).
Php/Cakephp interface with Python script
I have a webapp, created using CakePhp. I need to interface with a Python script. What is the best way to go about doing that? (I could use pipe etc., but I want to check what the best practices are) Thanks.
[ "It really depends what you're looking for. If you are going to be interfacing with python extensively, then I would recommend looking into an XML-RPC solution. Details on how to configure an XML-RPC server using Twisted (Python) can be found here:\nhttp://twistedmatrix.com/documents/10.1.0/web/howto/xmlrpc.html\...
[ 2, 1, 1 ]
[]
[]
[ "cakephp", "php", "python" ]
stackoverflow_0003702724_cakephp_php_python.txt
Q: Python: split list into chunks of defined size and fill up rest I want to split my list into rows that have all the same number of columns, I'm looking for the best (most elegant/pythonic) way to achieve this: >>> split.split_size([1,2,3], 5, 0) [[1, 2, 3, 0, 0]] >>> split.split_size([1,2,3,4,5], 5, 0) [[1, 2, 3, 4, 5]] >>> split.split_size([1,2,3,4,5,6], 5, 0) [[1, 2, 3, 4, 5], [6, 0, 0, 0, 0]] >>> split.split_size([1,2,3,4,5,6,7], 5, 0) [[1, 2, 3, 4, 5], [6, 7, 0, 0, 0]] That's what I came up with so far: def split_size(l, size, fillup): """ splits list into chunks of defined size, fills up last chunk with fillup if below size """ # len(l) % size or size # does i.e. size=5: 3->2, 4->1, 5->0 stack = l + [fillup] * (size - (len(l) % size or size)) result = [] while len(stack) > 0: result.append(stack[:5]) del stack[:5] return result I'm sure there must be some smarter solutions. Especially for the "inverse mod" part: len(l) % size or size there must be a more readable way to do this, no? A: The itertools recipe called grouper does what you want: def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)
Python: split list into chunks of defined size and fill up rest
I want to split my list into rows that have all the same number of columns, I'm looking for the best (most elegant/pythonic) way to achieve this: >>> split.split_size([1,2,3], 5, 0) [[1, 2, 3, 0, 0]] >>> split.split_size([1,2,3,4,5], 5, 0) [[1, 2, 3, 4, 5]] >>> split.split_size([1,2,3,4,5,6], 5, 0) [[1, 2, 3, 4, 5], [6, 0, 0, 0, 0]] >>> split.split_size([1,2,3,4,5,6,7], 5, 0) [[1, 2, 3, 4, 5], [6, 7, 0, 0, 0]] That's what I came up with so far: def split_size(l, size, fillup): """ splits list into chunks of defined size, fills up last chunk with fillup if below size """ # len(l) % size or size # does i.e. size=5: 3->2, 4->1, 5->0 stack = l + [fillup] * (size - (len(l) % size or size)) result = [] while len(stack) > 0: result.append(stack[:5]) del stack[:5] return result I'm sure there must be some smarter solutions. Especially for the "inverse mod" part: len(l) % size or size there must be a more readable way to do this, no?
[ "The itertools recipe called grouper does what you want:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0003703677_python.txt
Q: Security precautions for running python in cgi-bin I've been writing python scripts that run locally. I would now like to offer a service online using one of these python scripts and through the webhosting I have I can run python in the cgi-bin. The python script takes input from an html form filled in by the user, has the credentials and connects with a local database, calculates stuff using python libraries and sends out the results as HTML to be displayed. What I would like to know is what security precautions I should take. Here are my worries: What are the right file permissions for scripts called via web? 755? I am taking user input. How do I guarantee it is sanitized? I have user/pass for the database in the script. How do I prevent the script from being downloaded and the code seen? Can I install the other libraries next to the file? Do I have to worry about security of/in these as well? Do I set their permissions to 700? 744? Any other vulnerability I am unaware of? A: check out owasp.org - you're now writing a web application, and you need to worry about everything web apps need to worry about. The list is too long and complicated to place here, but owasp is a good starting point. A: File permissions - 755 is reasonable. Sanitize your user input. That's how you guarantee it's sanitized. See this question. Don't let people download the code for the script. You could also put the username/password in some directory that can't be accessed via the web (like outside the servable directories). The best place to install other libraries is in your PYTHONPATH but outside the path Apache uses to serve things. Vulnerabilities abound. Watch out for displaying things the user types, as that leads to XSS problems. A: What are the right file permissions for scripts called via web? 755? Use mod_wsgi so that your scripts are not run as scripts but as functions under a WSGI application. I am taking user input. How do I guarantee it is sanitized? Use a framework like Django. I have user/pass for the database in the script. How do I prevent the script from being downloaded and the code seen? Use a framework like Django. Can I install the other libraries next to the file? Yes. Do I have to worry about security of/in these as well? Yes. Do I set their permissions to 700? 744? They must be readable. That's all. However, if you use mod_wsgi, life is simpler. If you use a framework, simpler still. Any other vulnerability I am unaware of? Tons. Please see the http://www.owasp.org site. Also, please use a framework. Please don't reinvent everything yourself. Folks have already solved all of these problems.
Security precautions for running python in cgi-bin
I've been writing python scripts that run locally. I would now like to offer a service online using one of these python scripts and through the webhosting I have I can run python in the cgi-bin. The python script takes input from an html form filled in by the user, has the credentials and connects with a local database, calculates stuff using python libraries and sends out the results as HTML to be displayed. What I would like to know is what security precautions I should take. Here are my worries: What are the right file permissions for scripts called via web? 755? I am taking user input. How do I guarantee it is sanitized? I have user/pass for the database in the script. How do I prevent the script from being downloaded and the code seen? Can I install the other libraries next to the file? Do I have to worry about security of/in these as well? Do I set their permissions to 700? 744? Any other vulnerability I am unaware of?
[ "check out owasp.org - you're now writing a web application, and you need to worry about everything web apps need to worry about. The list is too long and complicated to place here, but owasp is a good starting point.\n", "\nFile permissions - 755 is reasonable.\nSanitize your user input. That's how you guarante...
[ 5, 2, 2 ]
[]
[]
[ "cgi_bin", "python", "security" ]
stackoverflow_0003703621_cgi_bin_python_security.txt
Q: Please let me know the problem in the following python code I am trying to written this code which would just test whether a file exists and then reads it and prints. I have written this code as a file named readFile.py and trying to run it through shell using execfile command. I have put many print stmts to check till where the control is going. The result shows me only first two print stmts and the control is not entering the def readFile()..I am unable to find the reason and need help.Thanks!! print 'i am doing fine' filename = "train-win.dat" print 'i am doing fine1' def readFile(): print 'i am doing fine2' import os print 'i am doing fine3' if os.path.exists(filename): print 'i am doing fine4' f = open(filename,"r") print 'i am doing fine5' a = f.readlines() print 'i am doing fine6' print a print 'i am doing fine7' f.close()p A: You define the function readFilebut you haven't called it so it will never execute. Add this at the end of your file (not indented): readFile() Also you have a syntax error on the last line of the function: f.close()p That p shouldn't be there. After making both these changes your program seems to work. A: While your code will work with minor modifications shown in another answer, the usual way of writing Python presents code in a slightly different order. Without the extra print statements, I might write: import os def readFile(): if os.path.exists(filename): f = open(filename, "r") a = f.readlines() print a f.close() filename = "train-win.dat" readFile() The first thing is to import the modules. Normally this is done at the top of the file. The next part defines a function called readFile. The def statement doesn't actually do anything at the time it's executed, but Python remembers the statements within the block to be executed later. Finally, readFile() actually calls the readFile function. Note also that I moved f.close() inside the if statement. You wouldn't want to try to close f if it had never been opened in the first place.
Please let me know the problem in the following python code
I am trying to written this code which would just test whether a file exists and then reads it and prints. I have written this code as a file named readFile.py and trying to run it through shell using execfile command. I have put many print stmts to check till where the control is going. The result shows me only first two print stmts and the control is not entering the def readFile()..I am unable to find the reason and need help.Thanks!! print 'i am doing fine' filename = "train-win.dat" print 'i am doing fine1' def readFile(): print 'i am doing fine2' import os print 'i am doing fine3' if os.path.exists(filename): print 'i am doing fine4' f = open(filename,"r") print 'i am doing fine5' a = f.readlines() print 'i am doing fine6' print a print 'i am doing fine7' f.close()p
[ "You define the function readFilebut you haven't called it so it will never execute. Add this at the end of your file (not indented):\nreadFile()\n\nAlso you have a syntax error on the last line of the function:\n f.close()p\n\nThat p shouldn't be there.\nAfter making both these changes your program seems to work.\...
[ 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003703613_python.txt
Q: top gotchas for someone moving from a static lang (java/c#) to dynamic language like python What are the top gotchas for someone moving from a static lang (java/c#) to dynamic language like python? It seems cool how things can be done, but renaming a method, or adding/removing parameters seems so risky! Is the only solution to write tests for each method? A: "Is the only solution to write tests for each method?" Are you saying you didn't write tests for each method in Java? If you wrote tests for each method in Java, then -- well -- nothing changes, does it? renaming a method, seems so risky! Correct. Don't do it. adding/removing parameters seems so risky! What? Are you talking about optional parameters? If so, then having multiple overloaded names in Java seems risky and confusing. Having optional parameters seems simpler. If you search on SO for the most common Python questions, you'll find that some things are chronic questions. How to update the PYTHONPATH. Why some random floating-point calculation isn't the same as a mathematical abstraction might indicate. Using Python 3 and typing code from a Python 2 tutorial. Why Python doesn't have super-complex protected, private and public declarations. Why Python doesn't have an enum type. The #1 chronic problem seems to be using mutable objects as default values for a function. Simply avoid this. A: Some things that struck me when first trying out Python (coming from a mainly Java background): Write Pythonic code. Use idioms recommended for Python, rather than doing it the old Java/C way. This is more than just a cosmetic or dogmatic issue. Pythonic code is actually hugely faster in practice than C-like code practically all the time. As a matter of fact, IMHO a lot of the "Python is slow" notion floating around is due to the fact that inexperienced coders tried to code Java/C in Python and ended up taking a big performance hit and got the idea that Python is horribly slow. Use list comprehensions and map/filter/reduce whenever possible. Get comfortable with the idea that functions are truly objects. Pass them around as callbacks, make functions return functions, learn about closures etc. There are a lot of cool and almost magical stuff you can do in Python like renaming methods as you mention. These things are great to show off Python's features, but really not necessary if you don't need them. Indeed, as S. Lott pointed out, its better to avoid things that seem risky. A: I would say that the number one gotcha is trying to write statically typed code in a dynamic language. Dont hesitate to use an identifier to point to a string and then a list in self-contained sections of code keys = 'foo bar foobar' # Imagine this coming in as an argument keys = keys.split() # Now the semantically chose name for the argument can be # reused As the semantically chosen name for a local variable don't hesitate to treat functions like regular values: they are. Take the following parser. Suppose that we want to treat all header tags alike and ul tags like ol tags. class Parser(HTMLParser): def __init__(self, html): self.feed(html) def handle_starttag(self, tag, attrs): parse_method = 'parse_' + tag if hasattr(self, parse_method): getattr(self, parse_method)(attrs) def parse_list(self, attrs): # generic code def parse_header(self, attrs): # more generic code parse_h1 = parse_h2 = parse_h3 = parse_h4 = parse_h5 = parse_h6 = parse_header parse_ol = parse_ul = parse_list This could be done by using less generic code in the handle_starttag method in a language like java by keeping track of which tags map to the same method but then if you decide that you want to handle div tags, you have to add that into the dispatching logic. Here you just add the method parse_div and you are good to go. Don't typecheck! Duck-type! def funtion(arg): if hasattr(arg, 'attr1') and hasattr(arg, 'attr2'): foo(arg): else: raise TypeError("arg must have 'attr1' and 'attr2'") as opposed to isinstance(arg, Foo). This lets you pass in any object with attr1 and attr2. This allows you to for instance pass in a tracing class wrapped around an object for debugging purposes. You would have to modify the class to do that in Java AFAIK. As pointed out by THC4k, another (more pythonic) way to do this is the EAPF idiom. I don't like this because I like to catch errors as early as possible. It is more efficient if you expect for the code to rarely fail though. Don't tell anybody I don't like it though our they'll stop thinking that I know how to write python. Here's an example courtesy of THC4k. try: foo(arg): except (AttributeError, TypeError): raise InvalidArgumentError(foo, arg) It's a tossup as to if we should be catching the AttributeError and TypeError or just let them propagate to somewhere that knows how to handle them but this is just an example so we'll let it fly.
top gotchas for someone moving from a static lang (java/c#) to dynamic language like python
What are the top gotchas for someone moving from a static lang (java/c#) to dynamic language like python? It seems cool how things can be done, but renaming a method, or adding/removing parameters seems so risky! Is the only solution to write tests for each method?
[ "\n\"Is the only solution to write tests for each method?\"\n\nAre you saying you didn't write tests for each method in Java?\nIf you wrote tests for each method in Java, then -- well -- nothing changes, does it?\n\nrenaming a method, seems so risky!\n\nCorrect. Don't do it.\n\nadding/removing parameters seems so ...
[ 3, 2, 2 ]
[]
[]
[ "dynamic_languages", "java", "python" ]
stackoverflow_0003703704_dynamic_languages_java_python.txt
Q: How do I add basic authentication to a Python REST request? I have the following simple Python code that makes a simple post request to a REST service - params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) The problem is that the url used to call the REST service will now require basic authentication (username and password). How can I incorporate a username and password / basic authentication into this code, as simply as possible? A: If basic authentication = HTTP authentication, use this: import urllib import urllib2 username = 'foo' password = 'bar' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, MY_APP_PATH, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) If not, use mechanize or cookielib to make an additional request for logging in. But if the service you access has an XML API, this API surely includes auth too. 2016 edit: By all means, use the requests library! It provides all of the above in a single call. A: You may want a library to abstract out some of the details. I've used restkit to great effect before. It handles HTTP auth.
How do I add basic authentication to a Python REST request?
I have the following simple Python code that makes a simple post request to a REST service - params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) The problem is that the url used to call the REST service will now require basic authentication (username and password). How can I incorporate a username and password / basic authentication into this code, as simply as possible?
[ "If basic authentication = HTTP authentication, use this:\nimport urllib\nimport urllib2\n\nusername = 'foo'\npassword = 'bar'\n\npassman = urllib2.HTTPPasswordMgrWithDefaultRealm()\npassman.add_password(None, MY_APP_PATH, username, password)\nauthhandler = urllib2.HTTPBasicAuthHandler(passman)\nopener = urllib2.bu...
[ 7, 1 ]
[]
[]
[ "authentication", "http_post", "python", "rest", "web_services" ]
stackoverflow_0003702370_authentication_http_post_python_rest_web_services.txt
Q: Using sessions in Django I'm using sessions in Django to store login user information as well as some other information. I've been reading through the Django session website and still have a few questions. From the Django website: By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to store session data elsewhere, so Django can be configured to store session data on your filesystem or in your cache. Also: For persistent, cached data, set SESSION_ENGINE to django.contrib.sessions.backends.cached_db. This uses a write-through cache – every write to the cache will also be written to the database. Session reads only use the database if the data is not already in the cache. Is there a good rule of thumb for which one to use? cached_db seems like it would always be a better choice because best case, the data is in the cache, and worst case it's in the database where it would be anyway. The one downside is I have to setup memcached. By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False, which means session cookies will be stored in users' browsers for as long as SESSION_COOKIE_AGE. Use this if you don't want people to have to log in every time they open a browser. Is it possible to have both, the session expire at the browser close AND give an age? If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. What is considered "inactivity"? If you're using the database backend, note that session data can accumulate in the django_session database table and Django does not provide automatic purging. Therefore, it's your job to purge expired sessions on a regular basis. So that means, even if the session is expired there are still records in my database. Where exactly would one put code to "purge the db"? I feel like you would need a seperate thread to just go through the db every once in awhile (Every hour?) and delete any expired sessions. A: Is there a good rule of thumb for which one to use? No. Cached_db seems like it would always be a better choice ... That's fine. In some cases, there a many Django (and Apache) processes querying a common database. mod_wsgi allows a lot of scalability this way. The cache doesn't help much because the sessions are distributed randomly among the Apache (and Django) processes. Is it possible to have both, the session expire at the browser close AND give an age? Don't see why not. What is considered "inactivity"? I assume you're kidding. "activity" is -- well -- activity. You know. Stuff happening in Django. A GET or POST request that Django can see. What else could it be? Where exactly would one put code to "purge the db"? Put it in crontab or something similar. I feel like you would need a seperate thread to just go through the db every once in awhile (Every hour?) Forget threads (please). It's a separate process. Once a day is fine. How many sessions do you think you'll have?
Using sessions in Django
I'm using sessions in Django to store login user information as well as some other information. I've been reading through the Django session website and still have a few questions. From the Django website: By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to store session data elsewhere, so Django can be configured to store session data on your filesystem or in your cache. Also: For persistent, cached data, set SESSION_ENGINE to django.contrib.sessions.backends.cached_db. This uses a write-through cache – every write to the cache will also be written to the database. Session reads only use the database if the data is not already in the cache. Is there a good rule of thumb for which one to use? cached_db seems like it would always be a better choice because best case, the data is in the cache, and worst case it's in the database where it would be anyway. The one downside is I have to setup memcached. By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False, which means session cookies will be stored in users' browsers for as long as SESSION_COOKIE_AGE. Use this if you don't want people to have to log in every time they open a browser. Is it possible to have both, the session expire at the browser close AND give an age? If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. What is considered "inactivity"? If you're using the database backend, note that session data can accumulate in the django_session database table and Django does not provide automatic purging. Therefore, it's your job to purge expired sessions on a regular basis. So that means, even if the session is expired there are still records in my database. Where exactly would one put code to "purge the db"? I feel like you would need a seperate thread to just go through the db every once in awhile (Every hour?) and delete any expired sessions.
[ "\nIs there a good rule of thumb for which one to use? \n\nNo.\n\nCached_db seems like it would always be a better choice ... \n\nThat's fine.\nIn some cases, there a many Django (and Apache) processes querying a common database. mod_wsgi allows a lot of scalability this way. The cache doesn't help much because th...
[ 7 ]
[]
[]
[ "django", "django_sessions", "python", "session" ]
stackoverflow_0003704404_django_django_sessions_python_session.txt
Q: Turning jQuery charts into PDFs I've found two jQuery charts plugins I like - flot and jqPlot. I'm thinking of using one of these on the front-end of my web site. However, I also need to be able to allow users to export data in PDF format. I'm ideally looking for a pure Python solution, but could run to Java or PHP at a push. The quality of the generated charts is the most important factor. Options I've considered are: Generate charts on the server, and create a PDF using those charts. I've looked at matplotlib and several other python charting packages, but the charts don't look anywhere near as polished as flot or jqPlot will make. Use Rhino and Env.js to run the same jQuery code on the server, and somehow capture the generated charts and insert those into PDFs. Is this possible with Rhino? How difficult is it likely to be? I've seen the Rhino-canvas project, but it looks way out of date. What would be the best way of doing this? If I can get the Rhino solution to work that'd be great since it'd maintain consistency between the front-end and generated PDFs. A: Convert graph to image As far as I understand it, flot draws to the canvas element (where available). I googled for examples of exporting the canvas content and found canvas2image, for example. It might, or might not, be an avenue to explore. See this StackOverflow question too. Going from that one, it might be quite simple to export an image (using Canvas.ToDataUrl(type) which takes a mime type. I am quite sure it will not do anything meaningful with application/pdf though...). Update: Well, look here, a modified version of canvas2image resides in the flotr source: http://flotr.googlecode.com/svn/trunk/flotr/flotr/prototype/lib/canvas2image.js Generate PDF There are solutions to generate PDF from within JavaScript on the client: CollinsPDF jsPDF End result Combine these two and you might have a solution. A: I suggest to take another look at matplotlib. The charts are highly customizable and can look very polished. Granted, the many options can be intimidating at first. But a lot of eye-candy effects can be achieved if you know how. If you want shadows, for instance, take a look at the transforms tutorial. Furthermore, matplotlib gives you high dpi bitmap images or even PDF vector graphics. I don't know how hard it is to use the mentioned jQuery libraries for higher resolution graphics. A: You can run a headless webkit (rendering engine) with Python and Qt on a server which you can then print to PDF. The changes you need to make to print a PDF with Qt are listed here albeit they might not be complete. This solution will just render the page and you could store the charts as separate images or go the proposed path of generating a full PDF of the page.
Turning jQuery charts into PDFs
I've found two jQuery charts plugins I like - flot and jqPlot. I'm thinking of using one of these on the front-end of my web site. However, I also need to be able to allow users to export data in PDF format. I'm ideally looking for a pure Python solution, but could run to Java or PHP at a push. The quality of the generated charts is the most important factor. Options I've considered are: Generate charts on the server, and create a PDF using those charts. I've looked at matplotlib and several other python charting packages, but the charts don't look anywhere near as polished as flot or jqPlot will make. Use Rhino and Env.js to run the same jQuery code on the server, and somehow capture the generated charts and insert those into PDFs. Is this possible with Rhino? How difficult is it likely to be? I've seen the Rhino-canvas project, but it looks way out of date. What would be the best way of doing this? If I can get the Rhino solution to work that'd be great since it'd maintain consistency between the front-end and generated PDFs.
[ "Convert graph to image\nAs far as I understand it, flot draws to the canvas element (where available). I googled for examples of exporting the canvas content and found canvas2image, for example. It might, or might not, be an avenue to explore.\nSee this StackOverflow question too. Going from that one, it might be ...
[ 4, 1, 1 ]
[]
[]
[ "charts", "jquery", "python" ]
stackoverflow_0003542122_charts_jquery_python.txt
Q: PyGTK - polling GTK table for locations of widgets I'm working on a Python application involving the use of a GTK table. The application requires that widgets of various sizes be added to a table dynamically. Because of this, I need to be able to ask the table what cells are in use (more accurately, NOT in use) so that I know where I can place a new widget without overlapping. Based on the information in the reference manual (http://www.pygtk.org/docs/pygtk/) I have been unable to find a way to get that information directly from the table. The only other option I can think of is to create a map object that holds used cell information, and have it updated upon changes to the table. Since I'm sure someone has dealt with this before me, and I would hope GTK would provide a better way, it seemed wise to ask around before trying to implement the map. Help would be greatly appreciated. A: This function should give you a set of the free cells in the table: def free_cells(table): free_cells = set([(x,y) for x in range(table.props.n_columns) for y in range(table.props.n_rows)]) def func(child): (l,r,t,b) = table.child_get(child, 'left-attach','right-attach','top-attach','bottom-attach') used_cells = set([(x,y) for x in range(l,r) for y in range(t,b)]) free_cells.difference_update(used_cells) table.foreach(func) return free_cells It starts with a set of all the table cells, then iterates over the children of the table, removing the cells occupied by each child. A: I'm the original poster, was logged into wrong account when posting question. Anyway, this appears to be exactly what I'm looking for! Thanks Geoff!
PyGTK - polling GTK table for locations of widgets
I'm working on a Python application involving the use of a GTK table. The application requires that widgets of various sizes be added to a table dynamically. Because of this, I need to be able to ask the table what cells are in use (more accurately, NOT in use) so that I know where I can place a new widget without overlapping. Based on the information in the reference manual (http://www.pygtk.org/docs/pygtk/) I have been unable to find a way to get that information directly from the table. The only other option I can think of is to create a map object that holds used cell information, and have it updated upon changes to the table. Since I'm sure someone has dealt with this before me, and I would hope GTK would provide a better way, it seemed wise to ask around before trying to implement the map. Help would be greatly appreciated.
[ "This function should give you a set of the free cells in the table:\ndef free_cells(table):\n free_cells = set([(x,y) for x in range(table.props.n_columns) for y in range(table.props.n_rows)])\n\n def func(child):\n (l,r,t,b) = table.child_get(child, 'left-attach','right-attach','top-attach','bottom-a...
[ 1, 0 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0003704001_gtk_python.txt
Q: Create decorator that can see current class method Can you create a decorator inside a class that will see the classes methods and variables? The decorator here doesnt see: self.longcondition() class Foo: def __init__(self, name): self.name = name # decorator that will see the self.longcondition ??? class canRun(object): def __init__(self, f): self.f = f def __call__(self, *args): if self.longcondition(): # <-------- ??? self.f(*args) # this is supposed to be a very long condition :) def longcondition(self): return isinstance(self.name, str) @canRun # <------ def run(self, times): for i in xrange(times): print "%s. run... %s" % (i, self.name) A: There's no real need to implement this decorator as a class, and there's no need to implement it inside the definition of the Foo class. The following will suffice: def canRun(meth): def decorated_meth(self, *args, **kwargs): if self.longcondition(): print 'Can run' return meth(self, *args, **kwargs) else: print 'Cannot run' return None return decorated_meth Using that decorator seems to work: >>> Foo('hello').run(5) Can run 0. run... hello 1. run... hello 2. run... hello 3. run... hello 4. run... hello >>> Foo(123).run(5) Cannot run A: My previous answer was made in haste. If you're wanting to write a decorator you should really use wraps from the functools module. It takes care of the hard stuff for you. A proper way to define the canRun decorator is: from functools import wraps def canRun(f): @wraps(f) def wrapper(instance, *args): if instance.longcondition(): return f(instance, *args) return wrapper The canRun function should be defined outside of the class. A: You can have it be a class but you need to use the descriptor protocol import types class canRun(object): def __init__(self, f): self.f = f self.o = object # <-- What the hell is this about? def __call__(self, *args): if self.longcondition(): self.f(*args) def __get__(self, instance, owner): return types.MethodType(self, instance) You always need to use a descriptor when you want to decorate class methods with a class instance using the __call__ method. The reason for this is that there will only be one self passed in which refers to the instance of the decorating class and not the instance of the decorated method.
Create decorator that can see current class method
Can you create a decorator inside a class that will see the classes methods and variables? The decorator here doesnt see: self.longcondition() class Foo: def __init__(self, name): self.name = name # decorator that will see the self.longcondition ??? class canRun(object): def __init__(self, f): self.f = f def __call__(self, *args): if self.longcondition(): # <-------- ??? self.f(*args) # this is supposed to be a very long condition :) def longcondition(self): return isinstance(self.name, str) @canRun # <------ def run(self, times): for i in xrange(times): print "%s. run... %s" % (i, self.name)
[ "There's no real need to implement this decorator as a class, and there's no need to implement it inside the definition of the Foo class. The following will suffice:\ndef canRun(meth):\n def decorated_meth(self, *args, **kwargs):\n if self.longcondition():\n print 'Can run'\n return...
[ 5, 1, 1 ]
[]
[]
[ "class_method", "decorator", "python" ]
stackoverflow_0003704392_class_method_decorator_python.txt
Q: In Python small floats tending to zero I have a Bayesian Classifier programmed in Python, the problem is that when I multiply the features probabilities I get VERY small float values like 2.5e-320 or something like that, and suddenly it turns into 0.0. The 0.0 is obviously of no use to me since I must find the "best" class based on which class returns the MAX value (greater value). What would be the best way to deal with this? I thought about finding the exponential portion of the number (-320) and, if it goes too low, multiplying the value by 1e20 or some value like that. But maybe there is a better way? A: What you describe is a standard problem with the naive Bayes classifier. You can search for underflow with that to find the answer. or see here. The short answer is it is standard to express all that in terms of logarithms. So rather than multiplying probabilities, you sum their logarithms. You might want to look at other algorithms as well for classification. A: Would it be possible to do your work in a logarithmic space? (For example, instead of storing 1e-320, just store -320, and use addition instead of multiplication) A: Floating point numbers don't have infinite precision, which is why you saw the numbers turn to 0. Could you multiply all the probabilities by a large scalar, so that your numbers stay in a higher range? If you're only worried about max and not magnitude, you don't even need to bother dividing through at the end. Alternatively you could use an infinite precision decimal, like ikanobori suggests. A: Take a look at Decimal from the stdlib. from decimal import Decimal, getcontext getcontext().prec = 320 Decimal(1) / Decimal(7) I am not posting the results here as it is quite long.
In Python small floats tending to zero
I have a Bayesian Classifier programmed in Python, the problem is that when I multiply the features probabilities I get VERY small float values like 2.5e-320 or something like that, and suddenly it turns into 0.0. The 0.0 is obviously of no use to me since I must find the "best" class based on which class returns the MAX value (greater value). What would be the best way to deal with this? I thought about finding the exponential portion of the number (-320) and, if it goes too low, multiplying the value by 1e20 or some value like that. But maybe there is a better way?
[ "What you describe is a standard problem with the naive Bayes classifier. You can search for underflow with that to find the answer. or see here.\nThe short answer is it is standard to express all that in terms of logarithms. So rather than multiplying probabilities, you sum their logarithms.\nYou might want to loo...
[ 24, 20, 7, 5 ]
[]
[]
[ "floating_point", "numerical_stability", "python" ]
stackoverflow_0003704570_floating_point_numerical_stability_python.txt
Q: Django, Python, trying to change field values / attributes in object retrieved from DB objects.all call, not working I'm trying to change a specific field from a field in an object that I retrieved from a django db call. class Dbobject () def __init__(self): dbobject = Modelname.objects.all() def test (self): self.dbobject[0].fieldname = 'some new value' then I am able to access a specific attribute like so: objclass = Dbobject() fieldvalue = dbobject.dbobject[0].fieldname but I want to be able to use the "test" method of the Dbobject class to try to change the specific value on an object's attribute value, but it isn't changing it. I am stumped by this as this is how I thought I am supposed to change an object's attribute value. A: I'm not sure if this is the problem or not, but I think you might be missing a save() method. from models import Person p = Person.objects.get(pk=100) p.name = 'Rico' p.save() # <== This writes it to the db. Is this what you're missing? Above is the simple case. Adapted for what you wrote above, it'd be like: dbobject.dbobject[0].fieldname = 'some new value' dbobject.dbobject[0].save() or, I'd write it more like: rec = dbobject.dbobject[0] rec.fieldname = 'some new value' rec.save() Also note that depending on whether and how you are using transactions, you may or may not see a change to the database until you commit. A: I am not totally sure what you are trying to achieve, but shouldn't it be something like: class Dbobject (): def __init__(self): self.dbobject = Modelname.objects.all() def test (self): self.dbobject[0].fieldname = 'some new value'
Django, Python, trying to change field values / attributes in object retrieved from DB objects.all call, not working
I'm trying to change a specific field from a field in an object that I retrieved from a django db call. class Dbobject () def __init__(self): dbobject = Modelname.objects.all() def test (self): self.dbobject[0].fieldname = 'some new value' then I am able to access a specific attribute like so: objclass = Dbobject() fieldvalue = dbobject.dbobject[0].fieldname but I want to be able to use the "test" method of the Dbobject class to try to change the specific value on an object's attribute value, but it isn't changing it. I am stumped by this as this is how I thought I am supposed to change an object's attribute value.
[ "I'm not sure if this is the problem or not, but I think you might be missing a save() method.\nfrom models import Person\np = Person.objects.get(pk=100)\np.name = 'Rico'\np.save() # <== This writes it to the db. Is this what you're missing?\n\nAbove is the simple case. Adapted for what you wrote above, it'd ...
[ 15, 0 ]
[]
[]
[ "attributes", "django", "object", "python" ]
stackoverflow_0003704709_attributes_django_object_python.txt
Q: Django app stops working when deployed on Apache ( subprocess runs, but fails ) My Django app stops working when deployed on Apache ( with mod_wsgi ). It runs on a Windows server. The app calls on a windows executable called "rex" ( Alchemy Remote Executor ) which executes a command on another remote windows box. process = subprocess.Popen( ['rex',ip,usr,pwd,command], stdout=subprocess.PIPE, universal_newlines=True ) out, err = process.communicate() This all works fine in development, but when deployed on Apache with mod_wsgi, it doesn't work! The "rex" program still runs, but it fails to do it's thing, and gives the following message: Failed to execute the program: A specified logon session does not exist. It may already have been terminated. So, the "rex" program is running, but it is not able to make the required connections or something when it's spawned from Apache. It almost seems like Apache is somehow closing the connection made by "rex.exe" before it can finish! Any ideas? A: It's always a challenge when deploying to a windows service that you are running as a different user than you're running under when you are in development, running it as a real user. I've had all kinds of troubles with this writing an updater that runs as a service, getting file permissions problems. Can you try logging in to Windows as the same user that is running the Apache service, and try your rex executable from there? With luck, you might be able to get rex to fail there where you're interactive and can troubleshoot it. But the basic idea is to replicate the failure outside of the apache service, then do whatever is needed to let this thing run while under the permissions of the service, and you're fixed. It could be that your rex program is trying to read or write to files (such as configuration files?) that it doesn't have permissions for.
Django app stops working when deployed on Apache ( subprocess runs, but fails )
My Django app stops working when deployed on Apache ( with mod_wsgi ). It runs on a Windows server. The app calls on a windows executable called "rex" ( Alchemy Remote Executor ) which executes a command on another remote windows box. process = subprocess.Popen( ['rex',ip,usr,pwd,command], stdout=subprocess.PIPE, universal_newlines=True ) out, err = process.communicate() This all works fine in development, but when deployed on Apache with mod_wsgi, it doesn't work! The "rex" program still runs, but it fails to do it's thing, and gives the following message: Failed to execute the program: A specified logon session does not exist. It may already have been terminated. So, the "rex" program is running, but it is not able to make the required connections or something when it's spawned from Apache. It almost seems like Apache is somehow closing the connection made by "rex.exe" before it can finish! Any ideas?
[ "It's always a challenge when deploying to a windows service that you are running as a different user than you're running under when you are in development, running it as a real user. I've had all kinds of troubles with this writing an updater that runs as a service, getting file permissions problems. Can you try...
[ 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python", "subprocess" ]
stackoverflow_0003703794_apache_django_mod_wsgi_python_subprocess.txt
Q: How does django one-to-one relationships map the name to the child object? Apart from one example in the docs, I can't find any documentation on how exactly django chooses the name with which one can access the child object from the parent object. In their example, they do the following: class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): return u"%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place, primary_key=True) serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() def __unicode__(self): return u"%s the restaurant" % self.place.name # Create a couple of Places. >>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton') >>> p1.save() >>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland') >>> p2.save() # Create a Restaurant. Pass the ID of the "parent" object as this object's ID. >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False) >>> r.save() # A Restaurant can access its place. >>> r.place <Place: Demon Dogs the place> # A Place can access its restaurant, if available. >>> p1.restaurant So in their example, they simply call p1.restaurant without explicitly defining that name. Django assumes the name starts with lowercase. What happens if the object name has more than one word, like FancyRestaurant? Side note: I'm trying to extend the User object in this way. Might that be the problem? A: If you define a custom related_name then it will use that, otherwise it will lowercase the entire model name (in your example .fancyrestaurant). See the else block in django.db.models.related code: def get_accessor_name(self): # This method encapsulates the logic that decides what name to give an # accessor descriptor that retrieves related many-to-one or # many-to-many objects. It uses the lower-cased object_name + "_set", # but this can be overridden with the "related_name" option. if self.field.rel.multiple: # If this is a symmetrical m2m relation on self, there is no reverse accessor. if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model: return None return self.field.rel.related_name or (self.opts.object_name.lower() + '_set') else: return self.field.rel.related_name or (self.opts.object_name.lower()) And here's how the OneToOneField calls it: class OneToOneField(ForeignKey): ... snip ... def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), SingleRelatedObjectDescriptor(related)) The opts.object_name (referenced in the django.db.models.related.get_accessor_name) defaults to cls.__name__. As for Side note: I'm trying to extend the User object in this way. Might that be the problem? No it won't, the User model is just a regular django model. Just watch out for related_name collisions.
How does django one-to-one relationships map the name to the child object?
Apart from one example in the docs, I can't find any documentation on how exactly django chooses the name with which one can access the child object from the parent object. In their example, they do the following: class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): return u"%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place, primary_key=True) serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() def __unicode__(self): return u"%s the restaurant" % self.place.name # Create a couple of Places. >>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton') >>> p1.save() >>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland') >>> p2.save() # Create a Restaurant. Pass the ID of the "parent" object as this object's ID. >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False) >>> r.save() # A Restaurant can access its place. >>> r.place <Place: Demon Dogs the place> # A Place can access its restaurant, if available. >>> p1.restaurant So in their example, they simply call p1.restaurant without explicitly defining that name. Django assumes the name starts with lowercase. What happens if the object name has more than one word, like FancyRestaurant? Side note: I'm trying to extend the User object in this way. Might that be the problem?
[ "If you define a custom related_name then it will use that, otherwise it will lowercase the entire model name (in your example .fancyrestaurant). See the else block in django.db.models.related code: \ndef get_accessor_name(self):\n # This method encapsulates the logic that decides what name to give an\n # ac...
[ 14 ]
[]
[]
[ "django", "one_to_one", "python" ]
stackoverflow_0003705124_django_one_to_one_python.txt
Q: Python - Way to restart a for loop, similar to "continue" for while loops? Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met. What I'm trying to do is this: for index, item in enumerate(list2): if item == '||' and list2[index-1] == '||': del list2[index] *<some action that resarts the whole process>* That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with: ['berry','||','pancake'] instead. Thanks! A: I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration? If it's the latter, then for loops support continue just like while loops do: for i in xrange(10): if i == 5: continue print i The above will print the numbers from 0 to 9, except for 5. If you're talking about starting over from the beginning of the for loop, there's no way to do that except "manually", for example by wrapping it in a while loop: should_restart = True while should_restart: should_restart = False for i in xrange(10): print i if i == 5: should_restart = True break The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know). A: while True: for i in xrange(10): if condition(i): break else: break That will do what you seem to want. Why you would want to do it is a different matter. Maybe you should take a look at your code and make sure you're not missing an obvious and easier way to do it. A: some action that resarts the whole process A poor way to think of an algorithm. You're just filtering, i.e., removing duplicates. And -- in Python -- you're happiest making copies, not trying to do del. In general, there's very little call to use del. def unique( some_list ): list_iter= iter(some_list) prev= list_iter.next() for item in list_iter: if item != prev: yield prev prev= item yield prev list( unique( ['berry','||','||','||','pancake'] ) ) A: The inevitable itertools version, because it just came to me: from itertools import groupby def uniq(seq): for key, items in groupby(seq): yield key print list(uniq(['berry','||','||','||','pancake'])) # ['berry','||', 'pancake'] # or simply: print [key for key, items in groupby(['berry','||','||','||','pancake'])] A: Continue will work for any loop. A: continue works in for loops also. >>> for i in range(3): ... print 'Before', i ... if i == 1: ... continue ... print 'After', i ... Before 0 After 0 Before 1 # After 1 is missing Before 2 After 2 A: As you can see answering your question leads to some rather convoluted code. Usually a better way can be found, which is why such constructs aren't built into the language If you are not comfortable using itertools, consider using this loop instead. Not only is it easier to follow than your restarting for loop, it is also more efficient because it doesn't waste time rechecking items that have already been passed over. L = ['berry','||','||','||','pancake'] idx=1 while idx<len(L): if L[idx-1]==L[idx]: del L[idx] else: idx+=1 A: def remove_adjacent(nums): return [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b] example = ['berry','||','||','||','pancake'] example = remove_adjacent(example) print example """ Output: ['berry', '||', 'pancake'] """ And by the way this is repeating of Remove adjacent duplicate elements from a list
Python - Way to restart a for loop, similar to "continue" for while loops?
Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met. What I'm trying to do is this: for index, item in enumerate(list2): if item == '||' and list2[index-1] == '||': del list2[index] *<some action that resarts the whole process>* That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with: ['berry','||','pancake'] instead. Thanks!
[ "I'm not sure what you mean by \"restarting\". Do you want to start iterating over from the beginning, or simply skip the current iteration?\nIf it's the latter, then for loops support continue just like while loops do:\nfor i in xrange(10):\n if i == 5:\n continue\n print i\n\nThe above will print the numbers...
[ 43, 25, 5, 4, 3, 3, 1, 0 ]
[]
[]
[ "continue", "for_loop", "loops", "python" ]
stackoverflow_0003704918_continue_for_loop_loops_python.txt
Q: Why can't I use Cocoa classes from my Python script? Today is the first time I've used Python, so I'm sure this'll be an easy question. I need to convert this Python script from a command line application: webkit2png. The end result will be a URL that returns an image of the webpage passed into it as a querystring param. I've achieved this on Windows with .NET and IE, Gecko and WebKit, but now need to do the same for Safari on OS X. I think I've got it converted, but unfortunately I'm running into a problem running the script from Apache on OS X: app = AppKit.NSApplication.sharedApplication() # create an app delegate delegate = AppDelegate.alloc().init() AppKit.NSApp().setDelegate_(delegate) # create a window rect = Foundation.NSMakeRect(0,0,100,100) win = AppKit.NSWindow.alloc() win.initWithContentRect_styleMask_backing_defer_ (rect, AppKit.NSBorderlessWindowMask, 2, 0) The error is thrown on the final line "initWithContentRect...". The error I see is: <class 'objc.error'>: NSInternalInconsistencyException - Error (1002) creating CGSWindow args = ('NSInternalInconsistencyException - Error (1002) creating CGSWindow',) message = 'NSInternalInconsistencyException - Error (1002) creating CGSWindow' name = u'NSInternalInconsistencyException' If I run the script on the command line (after removing the CGI stuff), it runs perfectly. Here's the libraries I'm importing: import cgi import cgitb; cgitb.enable() # for troubleshooting import sys try: import Foundation import WebKit import AppKit import objc except ImportError: print "Cannot find pyobjc library files. Are you sure it is installed?" sys.exit() A: You cannot (usually) connect to the window server from a process not associated to a GUI user. See this Apple tech note. Basically, it's a big no-no to use NSWindow etc. from the process spawned by Apache. The window server is not even guaranteed to exist if there's no GUI user logged in. So, you can't reliably do what you're trying to do. The problem is that the WebKit which comes with OS X depends on the window server. One way out might be to install Qt, which hopefully has a backend of WebKit independent of the Core Graphics window server.
Why can't I use Cocoa classes from my Python script?
Today is the first time I've used Python, so I'm sure this'll be an easy question. I need to convert this Python script from a command line application: webkit2png. The end result will be a URL that returns an image of the webpage passed into it as a querystring param. I've achieved this on Windows with .NET and IE, Gecko and WebKit, but now need to do the same for Safari on OS X. I think I've got it converted, but unfortunately I'm running into a problem running the script from Apache on OS X: app = AppKit.NSApplication.sharedApplication() # create an app delegate delegate = AppDelegate.alloc().init() AppKit.NSApp().setDelegate_(delegate) # create a window rect = Foundation.NSMakeRect(0,0,100,100) win = AppKit.NSWindow.alloc() win.initWithContentRect_styleMask_backing_defer_ (rect, AppKit.NSBorderlessWindowMask, 2, 0) The error is thrown on the final line "initWithContentRect...". The error I see is: <class 'objc.error'>: NSInternalInconsistencyException - Error (1002) creating CGSWindow args = ('NSInternalInconsistencyException - Error (1002) creating CGSWindow',) message = 'NSInternalInconsistencyException - Error (1002) creating CGSWindow' name = u'NSInternalInconsistencyException' If I run the script on the command line (after removing the CGI stuff), it runs perfectly. Here's the libraries I'm importing: import cgi import cgitb; cgitb.enable() # for troubleshooting import sys try: import Foundation import WebKit import AppKit import objc except ImportError: print "Cannot find pyobjc library files. Are you sure it is installed?" sys.exit()
[ "You cannot (usually) connect to the window server from a process not associated to a GUI user. See this Apple tech note. \nBasically, it's a big no-no to use NSWindow etc. from the process spawned by Apache. The window server is not even guaranteed to exist if there's no GUI user logged in. So, you can't reliably...
[ 2 ]
[]
[]
[ "cocoa", "macos", "nswindow", "python" ]
stackoverflow_0003704629_cocoa_macos_nswindow_python.txt
Q: Creating a Python function that opens a textfile, reads it, tokenizes it, and finally runs from the command line or as a module I have been trying to learn Python for a while now. By chance, I happened across chapter 6 of the official tutorial through a Google search link pointing here. When I learned, from that page, that functions were the heart of modules, and that modules could be called from the command line, I was all ears. Here's my first attempt at doing both, openbook.py import nltk, re, pprint from __future__ import division def openbook(book): file = open(book) raw = file.read() tokens = nltk.wordpunct_tokenize(raw) text = nltk.Text(tokens) words = [w.lower() for w in text] vocab = sorted(set(words)) return vocab if __name__ == "__main__": import sys openbook(file(sys.argv[1])) What I want is for this function to be importable as the module openbook, as well as for openbook.py to take a file from the command line and do all of those things to it. When I run openbook.py from the command line, this happens: gemeni@a:~/Projects-FinnegansWake$ python openbook.py vicocyclometer Traceback (most recent call last): File "openbook.py", line 23, in <module> openbook(file(sys.argv[1])) File "openbook.py", line 5, in openbook file = open(book) When I try using it as a module, this happens: >>> import openbook >>> openbook('vicocyclometer') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable So, what can I do to fix this, and hopefully continue down the long winding path to enlightenment? A: Error executing openbook.py For the first error, you are opening the file twice: openbook(file(sys.argv[1])) ph0 = open(book) Calling both file() and open() is redundant. They both do the same thing. Pick one or the other: preferably open(). open(...) open(name[, mode[, buffering]]) → file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. Error importing openbook module For the second error, you need to add the module name: >>> import openbook >>> openbook.openbook('vicocyclometer') Or import the openbook() function into the global namespace: >>> from openbook import openbook >>> openbook('vicocyclometer') A: Here are some things you need to fix: nltk.word_tokenize will fail every time: The function takes sentences as arguments. Make sure that you use nltk.sent_tokenize on the whole text first, so that things work correctly. Files not being dealt with: Only open the file once. You're not closing the file once it's done. I recommend using Python's with statement to extract the text, as it closes things automatically: with open(book) as raw: nltk.sent_tokenize(raw) ... Import the openbook function from the module, not just the module: from openbook import openbook. Lastly, you could consider: Adding things to the set with a generator expression, which will probably reduce the memory load: set(w.lower() for w in text) Using nltk.FreqDist to generate a vocab & frequency distribution for you. A: Try from openbook import * instead of import openbook OR: import openbook and then call it with openbook.openbook("vicocyclometer") A: In your interactive session, you're getting that error because you need to from openbook import openbook. I can't tell what happened with the command line because the line with the error got snipped. It's probably that you tried to open a file object. Try just passing the string into the openbook function directly.
Creating a Python function that opens a textfile, reads it, tokenizes it, and finally runs from the command line or as a module
I have been trying to learn Python for a while now. By chance, I happened across chapter 6 of the official tutorial through a Google search link pointing here. When I learned, from that page, that functions were the heart of modules, and that modules could be called from the command line, I was all ears. Here's my first attempt at doing both, openbook.py import nltk, re, pprint from __future__ import division def openbook(book): file = open(book) raw = file.read() tokens = nltk.wordpunct_tokenize(raw) text = nltk.Text(tokens) words = [w.lower() for w in text] vocab = sorted(set(words)) return vocab if __name__ == "__main__": import sys openbook(file(sys.argv[1])) What I want is for this function to be importable as the module openbook, as well as for openbook.py to take a file from the command line and do all of those things to it. When I run openbook.py from the command line, this happens: gemeni@a:~/Projects-FinnegansWake$ python openbook.py vicocyclometer Traceback (most recent call last): File "openbook.py", line 23, in <module> openbook(file(sys.argv[1])) File "openbook.py", line 5, in openbook file = open(book) When I try using it as a module, this happens: >>> import openbook >>> openbook('vicocyclometer') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not callable So, what can I do to fix this, and hopefully continue down the long winding path to enlightenment?
[ "Error executing openbook.py\nFor the first error, you are opening the file twice:\nopenbook(file(sys.argv[1]))\nph0 = open(book)\n\nCalling both file() and open() is redundant. They both do the same thing. Pick one or the other: preferably open().\n\nopen(...)\nopen(name[, mode[, buffering]]) → file object\nOpen a...
[ 6, 1, 0, 0 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0003703944_nltk_python.txt
Q: uploading empty file to ftp with psuedo-file As far as i know it is impossible to create an empty file with ftp, you have to create an empty file on the local drive, upload it, then delete it when you are done. I was wondering if it is possible to do something like: class FakeFile: def read(self): return '\x04' ftpinstance.storbinary('stor fe', FakeFile()) I thought this might work because the docs for storbinary say that it takes an object with a method 'read' and calls it til it returns EOF, and \x04 is the ASCII EOF character. I have tried this though, and the file ends up on the server being a random number of kilobytes large. Am I misunderstanding something? A: No need to implement your own file-like class, just use the in-memory files from builtin module StringIO (or BytesIO in Python 3): import ftplib import cStringIO ftp = ftplib.FTP('ftp.example.com') ftp.login('user', 'pass') voidfile = cStringIO.StringIO('') ftp.storbinary('STOR emptyfile.foo', voidfile) ftp.close() voidfile.close() A: End of File is not ASCII 4 in modern usage. That is obsolete usage from the days of XMODEM and teletype. Try this: class FakeFile: def read(self, size=0): return '' since an empty read is EOF. With your current code, you should be getting a random length file consisting entirely of '\x04' characters. This is because it seems to always have data when read. ^_- A: Actually the doc reads 'reads until EOF'. I solved this by making the read function return an empty string.
uploading empty file to ftp with psuedo-file
As far as i know it is impossible to create an empty file with ftp, you have to create an empty file on the local drive, upload it, then delete it when you are done. I was wondering if it is possible to do something like: class FakeFile: def read(self): return '\x04' ftpinstance.storbinary('stor fe', FakeFile()) I thought this might work because the docs for storbinary say that it takes an object with a method 'read' and calls it til it returns EOF, and \x04 is the ASCII EOF character. I have tried this though, and the file ends up on the server being a random number of kilobytes large. Am I misunderstanding something?
[ "No need to implement your own file-like class, just use the in-memory files from builtin module StringIO (or BytesIO in Python 3):\nimport ftplib\nimport cStringIO\n\nftp = ftplib.FTP('ftp.example.com')\nftp.login('user', 'pass')\n\nvoidfile = cStringIO.StringIO('')\nftp.storbinary('STOR emptyfile.foo', voidfile)\...
[ 4, 2, 0 ]
[]
[]
[ "file", "ftp", "python" ]
stackoverflow_0003705464_file_ftp_python.txt
Q: Create console in python I'm looking to have the same functionality (history, ...) as when you simply type python in your terminal. The script I have goes through a bunch of setup code, and when ready, the user should have a command prompt. What would be the best way to achieve this? A: Either use readline and code the shell behaviour yourself, or simply prepare the environment and drop into IPython. A: Run the script from the console with python -i. It will go through the commands and drop you in the usual Python console when it's done.
Create console in python
I'm looking to have the same functionality (history, ...) as when you simply type python in your terminal. The script I have goes through a bunch of setup code, and when ready, the user should have a command prompt. What would be the best way to achieve this?
[ "Either use readline and code the shell behaviour yourself, or simply prepare the environment and drop into IPython.\n", "Run the script from the console with python -i. It will go through the commands and drop you in the usual Python console when it's done.\n" ]
[ 9, 6 ]
[]
[]
[ "console", "interactive", "python" ]
stackoverflow_0003705421_console_interactive_python.txt
Q: django orm versus sqlachemy, are they basically the same thing? When using django, I believe you can swap out the built-in orm for sqlalchemy (not sure how though?). Are they both basically the same thing or there is a clear winner between the 2? A: When using django, I believe you can swap out the built-in orm for sqlalchemy (not sure how though?). You can use SQLAlchemy in your Django applications. That doesn't mean you can "swap" out the ORM though. Some of Django's built-in batteries would cease to work if you completely replace Django's ORM with SQLAlchemy. For instance the Admin app wouldn't work. I have read about people using both. Django's ORM to get the batteries to work and SQLAlchemy to tackle complex SQL relationships and queries. Are they both basically the same thing or there is a clear winner between the 2? They are not the same thing. SQLAlchemy is more versatile than Django's ORM. For instance while Django's ORM tightly couples the business logic layer and the persistence layer into models, SQLAlchemy will let you keep them separate. On the other hand SQLAlchemy has a steeper learning curve and would be an overkill for many projects. The existing migration tools for SQLAlchemy may not easily integrate with Django. All said, I wouldn't presume to declare either a "winner". They are broadly similar tools but with their own strengths, weaknesses and best-fit situations. While you are on the subject it wouldn't hurt to read this (dated but relevant) blog post about the short comings of the Django ORM and how it compares with SQLAlchemy. A: SQLAlchemy is more powerful, but also more complex, than Django ORM. Elixir provides an interface on top of SQLAlchemy that is closer to Django ORM in terms of complexity, but also lets you use constructs from SQLAlchemy if Elixir alone isn't enough. For example, I've found SQLAlchemy's AssociationProxy class to be useful on several occasions. You just drop an AssociationProxy field into an Elixir model class and you're good to go.
django orm versus sqlachemy, are they basically the same thing?
When using django, I believe you can swap out the built-in orm for sqlalchemy (not sure how though?). Are they both basically the same thing or there is a clear winner between the 2?
[ "\nWhen using django, I believe you can swap out the built-in orm for sqlalchemy (not sure how though?).\n\nYou can use SQLAlchemy in your Django applications. That doesn't mean you can \"swap\" out the ORM though. Some of Django's built-in batteries would cease to work if you completely replace Django's ORM with S...
[ 8, 0 ]
[]
[]
[ "django", "python", "sqlalchemy" ]
stackoverflow_0003701012_django_python_sqlalchemy.txt
Q: python print not functioning correctly after using curses I have created a simple gui with curses. However, when the curses menu is finished the print function does not print anything to screen until the main program exits. In the example below, when calc.py is run, the text "Directory list ok" is printed to the screen after the foo(calcDirs) is run. If I comment out the line folderSelection.menu(dirs) the text is printed to the screen as it normally would. Any ideas? I use python 2.5 calc.py: import folderSelection [...] calcDirs=folderSelection.menu(dirs) print "Directory list ok" foo(calcDirs) folderSelection.py: import curses def menu(folders): global scr scr = curses.initscr() curses.noecho() # Do not echo keypresses curses.cbreak() # No enter required scr.keypad(1) # Support keypad curses.curs_set(0) # Do not show the cursor # Do some calculations [...] exitCurses() return calcDirs def exitCurses(): global scr curses.nocbreak() curses.curs_set(1) scr.keypad(0) curses.echo() curses.endwin() Edit: It seems that the text is necessarily delayed until the program terminates. It may just be delayed some 30-40 seconds. A: I ran into a similar problem. It seems that curses does something to the output buffering on stdout. I think it's increasing the output buffer size, or setting buffered output mode. Reopening stdout with a buffer size of zero may fix it. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) Try that after curses returns but before you print anything.
python print not functioning correctly after using curses
I have created a simple gui with curses. However, when the curses menu is finished the print function does not print anything to screen until the main program exits. In the example below, when calc.py is run, the text "Directory list ok" is printed to the screen after the foo(calcDirs) is run. If I comment out the line folderSelection.menu(dirs) the text is printed to the screen as it normally would. Any ideas? I use python 2.5 calc.py: import folderSelection [...] calcDirs=folderSelection.menu(dirs) print "Directory list ok" foo(calcDirs) folderSelection.py: import curses def menu(folders): global scr scr = curses.initscr() curses.noecho() # Do not echo keypresses curses.cbreak() # No enter required scr.keypad(1) # Support keypad curses.curs_set(0) # Do not show the cursor # Do some calculations [...] exitCurses() return calcDirs def exitCurses(): global scr curses.nocbreak() curses.curs_set(1) scr.keypad(0) curses.echo() curses.endwin() Edit: It seems that the text is necessarily delayed until the program terminates. It may just be delayed some 30-40 seconds.
[ "I ran into a similar problem. It seems that curses does something to the output buffering on stdout. I think it's increasing the output buffer size, or setting buffered output mode. \nReopening stdout with a buffer size of zero may fix it.\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n\nTry that after curs...
[ 1 ]
[]
[]
[ "curses", "python", "python_2.5" ]
stackoverflow_0003657103_curses_python_python_2.5.txt
Q: Creating a list with >255 elements Ok, so I'm writing some python code (I don't write python much, I'm more used to java and C). Anyway, so I have collection of integer literals I need to store. (Ideally >10,000 of them, currently I've only got 1000 of them) I would have liked to be accessing the literals by file IO, or by accessing there source API, but that is disallowed. And not ontopic anyway. So I have the literals put into a list: src=list(0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1) #some code that uses the src But when I try to run the file it comes up with an error because there are more than 255 arguments. So the constructor is the problem. How should I do this? The data is intitally avaiable to me as a space deliminated textfile. I just searched and replaced and copied it in A: If you use [] instead of list(), you won't run into the limit because [] is not a function. src = [0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1] A: src = [int(value) for value in open('mycsv.csv').read().split(',') if value.strip()] Or are you not able to save text file in your system?
Creating a list with >255 elements
Ok, so I'm writing some python code (I don't write python much, I'm more used to java and C). Anyway, so I have collection of integer literals I need to store. (Ideally >10,000 of them, currently I've only got 1000 of them) I would have liked to be accessing the literals by file IO, or by accessing there source API, but that is disallowed. And not ontopic anyway. So I have the literals put into a list: src=list(0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1) #some code that uses the src But when I try to run the file it comes up with an error because there are more than 255 arguments. So the constructor is the problem. How should I do this? The data is intitally avaiable to me as a space deliminated textfile. I just searched and replaced and copied it in
[ "If you use [] instead of list(), you won't run into the limit because [] is not a function.\nsrc = [0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1]\n\n", "src = [int(value) for value in open('mycsv.csv').read().split(',') if value.strip()]\n\nOr are you not able to save text file in your system?\n" ]
[ 21, 1 ]
[]
[]
[ "list", "literals", "parameters", "python", "syntax_error" ]
stackoverflow_0003706199_list_literals_parameters_python_syntax_error.txt
Q: splitting an exml file into smaller files the xml file contains information about movies. how do i split the xml file into smaller files? ( so each small file is a separate movie) A: Without knowing the details, here is a broad outline of a possible approach: Parse the XML using a suitable library (BeautifulSoup, lxml etc.) Find the element corresponding to each movie. This can be done using a plain findAll or may require using an XPATH expression. Pretty print the subtree starting corresponding to each movie element into separate files. Of course a more detailed answer is not possible unless you post some sample XML and provide more details.
splitting an exml file into smaller files
the xml file contains information about movies. how do i split the xml file into smaller files? ( so each small file is a separate movie)
[ "Without knowing the details, here is a broad outline of a possible approach:\n\nParse the XML using a suitable library (BeautifulSoup, lxml etc.)\nFind the element corresponding to each movie. This can be done using a plain findAll or may require using an XPATH expression. \nPretty print the subtree starting corre...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003706352_python.txt
Q: Elegant Solution for looping over a json hash with a fickle structure I have a json hash which has a lot of keys. I retrieve this hash from a web service at regular intervals and for different parameters etc. This has more or less fixed structure, in the sense that keys are sometimes missing. So I end up with a lot of code of the following nature Edit: Sample data data = { id1 : {dict...}, id2 : {dict..}, '' : {value...}, ... } for item in data: id = data.get("id") if not id: continue ... I want to skip the 3rd element and move on. The structure data is a nested dict and I loop inside each of these nests. There are keys missing there as well :( I was wondering if there was a more elegant solution than having 50 different ifs and continues Thanks A: How about iterating over the dict keys and doing your processing: data = { 'id1' : {'a':"", 'b':""}, 'id2' : {'c':"", 'd':""}, '' : {'c':"", 'd':""}, "": {'c':"", 'd':""}, } for key in data.iterkeys(): if key: print key print "Processing %s" % key # do further processing of data[key] This outputs the following. Notice that it skips processing for which key is missing. id2 Processing id2 id1 Processing id1
Elegant Solution for looping over a json hash with a fickle structure
I have a json hash which has a lot of keys. I retrieve this hash from a web service at regular intervals and for different parameters etc. This has more or less fixed structure, in the sense that keys are sometimes missing. So I end up with a lot of code of the following nature Edit: Sample data data = { id1 : {dict...}, id2 : {dict..}, '' : {value...}, ... } for item in data: id = data.get("id") if not id: continue ... I want to skip the 3rd element and move on. The structure data is a nested dict and I loop inside each of these nests. There are keys missing there as well :( I was wondering if there was a more elegant solution than having 50 different ifs and continues Thanks
[ "How about iterating over the dict keys and doing your processing:\ndata = {\n'id1' : {'a':\"\", 'b':\"\"},\n'id2' : {'c':\"\", 'd':\"\"},\n'' : {'c':\"\", 'd':\"\"},\n\"\": {'c':\"\", 'd':\"\"},\n}\n\nfor key in data.iterkeys():\n if key:\n print key\n print \"Processing %s\" % key\n # do f...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003706368_python.txt
Q: Mixing regex and shell wildcards I have a python script that reads from a config file. The config file is going to contain some user defined regex patterns. However, I was thinking I'd like to let the user use either full regex patterns, OR shell wildcards. So I should be able to interpret both *.txt as well as .*\.txt$ correctly. So those 2 should be equivalent. However I'd like to be able to do this without making the user tell me which they're using. Is this even possible? Maybe allowing full regex is overkill. A: You can't do this. What should prefix.* match? What about somefiles?? These have very different meanings in regex vs glob matching, but are common use cases in both. A: One possible approach could be: Try to compile the given expression as a regex. a. If this fails (syntax error), use the expression as a glob string. b. If it doesn't fail to compile, use it as a regex. If it doesn't match anything, use it as a glob string. In any case, tell the user what you did ("Interpreting pattern.* as a regular expression") and allow him to override whatever you have guessed. After all, as Zak Thompson wrote, some patterns will be both valid regexes and glob patterns. Another thing to take into consideration is that a user can easily overload or crash your system with a regex through catastrophic backtracking. So unless it's your user's own machine, you might want to think about allowing regexes in the first place. A: Consider, for example, the pattern foo?.txt In glob-syntax, this will match foo1.txt, fooZ.txt but not fo.txt, fob.txt or fooZtxt In regexp syntaxt, this will match fo.txt, foQtxt, but not fooZ.txt You can't, unambiguously, accept both syntaxes. The only option I can think of is have the user prefix the expression, i.e. regexp:foo?.txt A: Try not to leave the creation of regex to the user. The user should have an easier means to configure their files without needing to use regex. Eg let the users have a few choices, starts with ends with contains (OR and AND) etc Then as the programmer, you use these choices to construct your regex.
Mixing regex and shell wildcards
I have a python script that reads from a config file. The config file is going to contain some user defined regex patterns. However, I was thinking I'd like to let the user use either full regex patterns, OR shell wildcards. So I should be able to interpret both *.txt as well as .*\.txt$ correctly. So those 2 should be equivalent. However I'd like to be able to do this without making the user tell me which they're using. Is this even possible? Maybe allowing full regex is overkill.
[ "You can't do this. What should prefix.* match? What about somefiles?? These have very different meanings in regex vs glob matching, but are common use cases in both.\n", "One possible approach could be:\n\nTry to compile the given expression as a regex.\na. If this fails (syntax error), use the expression as a...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex", "wildcard" ]
stackoverflow_0003706469_python_regex_wildcard.txt
Q: Library for kademila end emule Anyone known a ruby (or at least python or java) library for kademila and emule? A: One option: http://sourceforge.net/projects/jmule/ - active, not lib but I guess that UI can be cutoff - however it may need some Java coding. Another option: Use mldonkey gui protocol to control mldonkey instance http://mldonkey.sourceforge.net/GuiProtocol . eDonkey2000 is proprietary protocol and nobody wants to invest in it thus no serious solutions. It is easier to find BitTorrent library implementations as they are used and developed also in commercial software for CDN.
Library for kademila end emule
Anyone known a ruby (or at least python or java) library for kademila and emule?
[ "One option: http://sourceforge.net/projects/jmule/ - active, not lib but I guess that UI can be cutoff - however it may need some Java coding.\nAnother option: Use mldonkey gui protocol to control mldonkey instance http://mldonkey.sourceforge.net/GuiProtocol .\neDonkey2000 is proprietary protocol and nobody wants...
[ 1 ]
[]
[]
[ "java", "python", "ruby" ]
stackoverflow_0003699562_java_python_ruby.txt
Q: py2exe problems c:\python26\setup.py py2exe Trying to run py2exe and when I get to command prompt I run the line above. However as opposed to converting my file it try's to open it. What am I doing wrong? A: You must create your own setup.py and then run it with py2exe: c:\my_python_scripts>python setup.py py2exe In your setup.py you import distutils, py2exe and show names of your scripts to compile. There is template for it. Then I usually create .bat file which compiles my scripts. Have you read py2exe tutorial?
py2exe problems
c:\python26\setup.py py2exe Trying to run py2exe and when I get to command prompt I run the line above. However as opposed to converting my file it try's to open it. What am I doing wrong?
[ "You must create your own setup.py and then run it with py2exe:\nc:\\my_python_scripts>python setup.py py2exe\n\nIn your setup.py you import distutils, py2exe and show names of your scripts to compile. There is template for it. Then I usually create .bat file which compiles my scripts.\nHave you read py2exe tutoria...
[ 2 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0003706290_py2exe_python.txt
Q: removing duplication in google search api? I am performing a google search in my application through google search api. It gives me the duplicate results. How to avoid it. I refer http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje A: You can look at the filtering option used at : http://code.google.com/apis/searchappliance/documentation/64/xml_reference.html It uses two types of filter: Duplicate Snippet Filter Duplicate Directory Filter So when calling, mark Filter=True results = server.doGoogleSearch(key, 'mark', 0, 10, False, "", ...) The API provides the following argument: key - Your Google API key q - The search word start - The index of the result to start on maxResults - The number of results to return. filter - If True, Google will filter out duplicate pages restrict - Set this to country plus a country code to get results only from a particular country safeSearch - If True, Google will filter out porn sites lr (“language restrict”) - Set this to a language code ie and oe must be "utf-8"
removing duplication in google search api?
I am performing a google search in my application through google search api. It gives me the duplicate results. How to avoid it. I refer http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje
[ "You can look at the filtering option used at :\n\nhttp://code.google.com/apis/searchappliance/documentation/64/xml_reference.html\n\nIt uses two types of filter:\n\nDuplicate Snippet Filter\nDuplicate Directory Filter\n\nSo when calling, mark Filter=True\nresults = server.doGoogleSearch(key, 'mark', 0, 10, False, ...
[ 0 ]
[]
[]
[ "google_search_api", "python" ]
stackoverflow_0003706742_google_search_api_python.txt
Q: Python Packager What is the easiest way to package Python programs into stand-alone executables? A: http://python-packager.com :-)
Python Packager
What is the easiest way to package Python programs into stand-alone executables?
[ "http://python-packager.com :-)\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003706173_python.txt
Q: How to make single from multiple element? l = [{'name': 'abc', 'marks': 50}, {'name': 'abc', 'marks': 50}] I want to uniqify the dictionary result. result = [{'name': 'abc', 'marks': 50}] A: Normally, the easiest way to make a list only have unique elements is to convert it to a set, assuming: The list entries are hashable You don't care about the order of the items However, a dict isn't hashable so in your case it might be easiest just to this by hand: >>> l = [{'name': 'abc', 'marks': 50}, {'name': 'abc', 'marks': 50}] >>> l2 = [] >>> for d in l: ... if not d in l2: ... l2.append(d) ... >>> l2 [{'name': 'abc', 'marks': 50}] The code above assumes you want to "uniquify" based on exactly matching dict items. For example, if you have two items with the same name but different marks they will both be added to the list.
How to make single from multiple element?
l = [{'name': 'abc', 'marks': 50}, {'name': 'abc', 'marks': 50}] I want to uniqify the dictionary result. result = [{'name': 'abc', 'marks': 50}]
[ "Normally, the easiest way to make a list only have unique elements is to convert it to a set, assuming:\n\nThe list entries are hashable\nYou don't care about the order of the items\n\nHowever, a dict isn't hashable so in your case it might be easiest just to this by hand:\n>>> l = [{'name': 'abc', 'marks': 50}, ...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003706981_python.txt
Q: I need MSVCR90.dll version 9.0.21022.8 According to a py2exe tutorial I found I need MSVCR90.dll version 9.0.21022.8 to run it for python 2.6. Where do I find MSVCR90.dll version 9.0.21022.8? A: Install the VS 2008 redistrbutable package.
I need MSVCR90.dll version 9.0.21022.8
According to a py2exe tutorial I found I need MSVCR90.dll version 9.0.21022.8 to run it for python 2.6. Where do I find MSVCR90.dll version 9.0.21022.8?
[ "Install the VS 2008 redistrbutable package.\n" ]
[ 7 ]
[]
[]
[ "py2exe", "python", "visual_c++" ]
stackoverflow_0003707178_py2exe_python_visual_c++.txt
Q: Quickest way to extract the bits of the colors in a .pgm image? I've got a hundred 128 x 128 .pgm files with some shapes on them and I think their color scale is 255 (not sure on this one though, so it'd be nice if a solution could also take that in consideration) and I need to extract these colors to process the images. So what I'd like to end up with would be a 128 x 128 matrix with each element having a value between 0 - 255, assuming the 256 colors example. As for the language, anything in Python/Java/C# will do, preferably in that order. I can use either Windows or Linux so exclusive libraries are not an issue. A: As far as a python solution goes, I believe PIL supports .pgm files. In that case (using numpy as the array container, but this part is optional): (Edit: Re-read your question and realized that you specifically wanted grayscale, rather than RGB... Which I should have realized from the .pgm format, anyway...) import Image import numpy as np im = Image.open('test.pgm') # Convert to grayscale (single 8-bit band), if it's not already... im = im.convert('L') # "data" is a uint8 (0-255) numpy array... data = np.asarray(im) A: P ortable G ray M ap format is so trivial that I would consider a matter of honor to write a parser for pgm files yourself in whatever language you need. Each value read from PGM file would correspond to RGB 255*Value/Max_Value byte. good luck.
Quickest way to extract the bits of the colors in a .pgm image?
I've got a hundred 128 x 128 .pgm files with some shapes on them and I think their color scale is 255 (not sure on this one though, so it'd be nice if a solution could also take that in consideration) and I need to extract these colors to process the images. So what I'd like to end up with would be a 128 x 128 matrix with each element having a value between 0 - 255, assuming the 256 colors example. As for the language, anything in Python/Java/C# will do, preferably in that order. I can use either Windows or Linux so exclusive libraries are not an issue.
[ "As far as a python solution goes, I believe PIL supports .pgm files. In that case (using numpy as the array container, but this part is optional):\n(Edit: Re-read your question and realized that you specifically wanted grayscale, rather than RGB... Which I should have realized from the .pgm format, anyway...)\nim...
[ 1, 0 ]
[]
[]
[ "c#", "image_processing", "java", "pgm", "python" ]
stackoverflow_0003702824_c#_image_processing_java_pgm_python.txt
Q: executing programs without python installed its possible to execute a python program on system where python is not installed? I want to execute my python program like c program I compile it on linux and then I can execute on any linux system A: You can use Freeze to make Linux binaries. py2exe is essentially the same thing for Windows. A: You'll have to use something like Py2Exe for Windows, or Freeze for Linux. And there is also the cross-platform cx_Freeze.
executing programs without python installed
its possible to execute a python program on system where python is not installed? I want to execute my python program like c program I compile it on linux and then I can execute on any linux system
[ "You can use Freeze to make Linux binaries. py2exe is essentially the same thing for Windows.\n", "You'll have to use something like Py2Exe for Windows, or Freeze for Linux. And there is also the cross-platform cx_Freeze.\n" ]
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003707470_python.txt
Q: What does this python syntax mean? I am not a python guy and I am trying to understand some python code. I wonder what the last line of below code does? Is that kind of multiple objects returned? or list of 3 objects returned? req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req #<----- What does this mean ? A: There are two things going on in that line. The easier one to explain is that the yield statement is returning a value which is a sequence, so the commas take values of the sequence and put them in the variables, much like this: >>> def func(): ... return (1,2,3) ... >>> a,b,c = func() >>> a 1 >>> b 2 >>> c 3 Now, the yield statement is used to create a generator, which can return a number of values rather than just one, returning one value each time yield is used. For example: >>> def func(): ... for a in ['one','two','three']: ... yield a ... >>> g = func() >>> g.next() 'one' >>> g.next() 'two' >>> g.next() 'three' In effect, the function stops at the yield statement, waiting to be asked for the next value before carrying on. In the example above next() gets the next value from the generator. However, if we use send() instead we can send values back to the generator which are returned by the yield statement back in to the function: >>> def func(): ... total = 0 ... while True: ... add = yield total ... total = total + add ... >>> g = func() >>> g.next() 0 >>> g.send(10) 10 >>> g.send(15) 25 Putting this all together we get: >>> def func(): ... total = 0 ... while True: ... x,y = yield total ... total = total + (x * y) ... >>> g = func() >>> g.next() 0 >>> g.send([6,7]) 42 A generator used in this way is called a coroutine. A: the last line is unpacking a tuple from the send method of the coroutine that the displayed code is located in. that is to say that it occurs in a function: def coroutine(*args): yield None req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req there is then client code that somewhere that looks something like this. co = coroutine(*args) next(co) # consume the first value so we can start sending. co.send((device, resp, fault)) a simpler example of this that doesn't involve coroutines is something along the lines of a, b, c = (1, 2, 3) or (slightly fancier) for a, b in zip(['a', 'b'], [1, 2]): print a, b here zip returns tuples that get unpacked to a and b. so one tuple would look like ('a', 1) and then a == 'a' and b == 1.
What does this python syntax mean?
I am not a python guy and I am trying to understand some python code. I wonder what the last line of below code does? Is that kind of multiple objects returned? or list of 3 objects returned? req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req #<----- What does this mean ?
[ "There are two things going on in that line. The easier one to explain is that the yield statement is returning a value which is a sequence, so the commas take values of the sequence and put them in the variables, much like this:\n>>> def func():\n... return (1,2,3)\n...\n>>> a,b,c = func()\n>>> a\n1\n>>> b\n2...
[ 9, 4 ]
[]
[]
[ "generator", "python", "yield" ]
stackoverflow_0003707383_generator_python_yield.txt
Q: Problem adding to solr index from Django using zc.buildout I'm trying to get Apache Solr running inside my zc.buildout environment. I've defined a simple model: class NewsItem(models.Model): title = models.CharField(blank=False, max_length=255, help_text=u"Title of this news item") slug = models.SlugField(blank=False, help_text=u"Slug will be automatically generated from the title") article = models.TextField(help_text=u"The body text of this news item") created_on = models.DateTimeField(auto_now_add = True) updated_on = models.DateTimeField(auto_now = True) published = models.BooleanField(default=True) def __unicode__(self): return self.title search_index.py: import datetime from haystack.indexes import * from haystack import site from appname.models import * class NewsItemIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) def get_queryset(self): """Used when the entire index for model is updated.""" return NewsItem.objects.all() site.register(NewsItem, NewsItemIndex) And a search_sites.py defines: import haystack haystack.autodiscover() The settings file contains: HAYSTACK_SITECONF = 'appname.search_sites' HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://127.0.0.1:8983/solr' HAYSTACK_SEARCH_RESULTS_PER_PAGE = 30 HAYSTACK_INCLUDE_SPELLING = True 'haystack' is listed in INSTALLED_APPS, pysolr is listed in the 'install_requires' in setup.py (offered by buildout) My buildout.cfg contains solr-files, solr, solr-conf and supervisor. I've added ${buildout:directory}/solr-conf to the [mkdir] paths. The supervisor and solr sections in buildout.cfg look like this: [supervisor] recipe = collective.recipe.supervisor port = localhost:9001 user = admin password = admin plugins = superlance # solr security settings: see # http://docs.codehaus.org/display/JETTY/Connectors+slow+to+startup programs = 10 solr (startsecs=10) java [-Djava.security.egd=file:/dev/urandom -jar start.jar] ${buildout:parts-directory}/solr true eventlisteners = SolrHttpOk TICK_60 ${buildout:bin-directory}/httpok [-p solr -t 20 http://localhost:8983/solr/] [solr-files] recipe = hexagonit.recipe.download url = ftp://mir1.ovh.net/ftp.apache.org/dist/lucene/solr/1.3.0/apache-solr-1.3.0.tgz md5sum = 23774b077598c6440d69016fed5cc810 strip-top-level-dir = true [solr] recipe = collective.recipe.solrinstance solr-location = ${buildout:parts-directory}/solr-files host = localhost port = 8983 unique-key = uniqueID default-search-field = text index = name:uniqueID type:string indexed:true stored:true required:true name:text type:string indexed:true stored:true required:false omitnorms:false multivalued:true [solr-conf] recipe = iw.recipe.cmd on_install = true on_update = true cmds = cp -v ${buildout:directory}/solr-conf/jetty.xml ${solr:jetty-destination} cp -v ${buildout:directory}/solr-conf/schema.xml ${solr:schema-destination} cp -v ${buildout:directory}/solr-conf/stopwords_fr.txt ${solr:schema-destination} [solr-rebuild] recipe = iw.recipe.cmd on_install = true on_update = true # since solr is not started by solr-instance but supervisord, solr-instance has # no pid file and thinks that solr is down. Thus we must run it with # solr-instance to be able to "solr-instance purge" cmds = ${buildout:bin-directory}/supervisorctl stop solr cp -v ${buildout:directory}/solr-conf/schema.xml ${solr:schema-destination} ${buildout:bin-directory}/solr-instance start COUNT=15; echo "Waiting $COUNT s"; sleep $COUNT ${buildout:bin-directory}/solr-instance purge time ${buildout:bin-directory}/${django:control-script} rebuild_index ${buildout:bin-directory}/solr-instance stop ${buildout:bin-directory}/supervisorctl start solr When I run $ bin/buildout install solr-rebuild, I get the following output: `/appname/solr-conf/schema.xml' -> `/appname/parts/solr/solr/conf/schema.xml' Solr started with pid 16023 Waiting 15 s SimplePostTool: version 1.2 SimplePostTool: WARNING: Make sure your XML documents are encoded in UTF-8, other encodings are not currently supported SimplePostTool: POSTing args to http://localhost:8983/solr/update.. SimplePostTool: COMMITting Solr index changes.. WARNING: This will irreparably remove EVERYTHING from your search index. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 1 news items. Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct'] 0.32user 0.05system 0:02.82elapsed 13%CPU (0avgtext+0avgdata 57872maxresident)k 160inputs+8outputs (3major+4257minor)pagefaults 0swaps Solr stopped successfully. Similarly, running $ bin/django rebuild_index or $ bin/buildout update_index complains about 'django_ct': Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct'] (one thing I'm going to try is update solr to the latest version.. will report if that does it..) I'm not sure where to look next.. Searching google, groups and stackoverflow didn't get me past this point. Thanks in advance! A: OK, problem solved. Updating to Solr 1.4.1 (and, strangely, rebooting after that) did the trick.
Problem adding to solr index from Django using zc.buildout
I'm trying to get Apache Solr running inside my zc.buildout environment. I've defined a simple model: class NewsItem(models.Model): title = models.CharField(blank=False, max_length=255, help_text=u"Title of this news item") slug = models.SlugField(blank=False, help_text=u"Slug will be automatically generated from the title") article = models.TextField(help_text=u"The body text of this news item") created_on = models.DateTimeField(auto_now_add = True) updated_on = models.DateTimeField(auto_now = True) published = models.BooleanField(default=True) def __unicode__(self): return self.title search_index.py: import datetime from haystack.indexes import * from haystack import site from appname.models import * class NewsItemIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) def get_queryset(self): """Used when the entire index for model is updated.""" return NewsItem.objects.all() site.register(NewsItem, NewsItemIndex) And a search_sites.py defines: import haystack haystack.autodiscover() The settings file contains: HAYSTACK_SITECONF = 'appname.search_sites' HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://127.0.0.1:8983/solr' HAYSTACK_SEARCH_RESULTS_PER_PAGE = 30 HAYSTACK_INCLUDE_SPELLING = True 'haystack' is listed in INSTALLED_APPS, pysolr is listed in the 'install_requires' in setup.py (offered by buildout) My buildout.cfg contains solr-files, solr, solr-conf and supervisor. I've added ${buildout:directory}/solr-conf to the [mkdir] paths. The supervisor and solr sections in buildout.cfg look like this: [supervisor] recipe = collective.recipe.supervisor port = localhost:9001 user = admin password = admin plugins = superlance # solr security settings: see # http://docs.codehaus.org/display/JETTY/Connectors+slow+to+startup programs = 10 solr (startsecs=10) java [-Djava.security.egd=file:/dev/urandom -jar start.jar] ${buildout:parts-directory}/solr true eventlisteners = SolrHttpOk TICK_60 ${buildout:bin-directory}/httpok [-p solr -t 20 http://localhost:8983/solr/] [solr-files] recipe = hexagonit.recipe.download url = ftp://mir1.ovh.net/ftp.apache.org/dist/lucene/solr/1.3.0/apache-solr-1.3.0.tgz md5sum = 23774b077598c6440d69016fed5cc810 strip-top-level-dir = true [solr] recipe = collective.recipe.solrinstance solr-location = ${buildout:parts-directory}/solr-files host = localhost port = 8983 unique-key = uniqueID default-search-field = text index = name:uniqueID type:string indexed:true stored:true required:true name:text type:string indexed:true stored:true required:false omitnorms:false multivalued:true [solr-conf] recipe = iw.recipe.cmd on_install = true on_update = true cmds = cp -v ${buildout:directory}/solr-conf/jetty.xml ${solr:jetty-destination} cp -v ${buildout:directory}/solr-conf/schema.xml ${solr:schema-destination} cp -v ${buildout:directory}/solr-conf/stopwords_fr.txt ${solr:schema-destination} [solr-rebuild] recipe = iw.recipe.cmd on_install = true on_update = true # since solr is not started by solr-instance but supervisord, solr-instance has # no pid file and thinks that solr is down. Thus we must run it with # solr-instance to be able to "solr-instance purge" cmds = ${buildout:bin-directory}/supervisorctl stop solr cp -v ${buildout:directory}/solr-conf/schema.xml ${solr:schema-destination} ${buildout:bin-directory}/solr-instance start COUNT=15; echo "Waiting $COUNT s"; sleep $COUNT ${buildout:bin-directory}/solr-instance purge time ${buildout:bin-directory}/${django:control-script} rebuild_index ${buildout:bin-directory}/solr-instance stop ${buildout:bin-directory}/supervisorctl start solr When I run $ bin/buildout install solr-rebuild, I get the following output: `/appname/solr-conf/schema.xml' -> `/appname/parts/solr/solr/conf/schema.xml' Solr started with pid 16023 Waiting 15 s SimplePostTool: version 1.2 SimplePostTool: WARNING: Make sure your XML documents are encoded in UTF-8, other encodings are not currently supported SimplePostTool: POSTing args to http://localhost:8983/solr/update.. SimplePostTool: COMMITting Solr index changes.. WARNING: This will irreparably remove EVERYTHING from your search index. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 1 news items. Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct'] 0.32user 0.05system 0:02.82elapsed 13%CPU (0avgtext+0avgdata 57872maxresident)k 160inputs+8outputs (3major+4257minor)pagefaults 0swaps Solr stopped successfully. Similarly, running $ bin/django rebuild_index or $ bin/buildout update_index complains about 'django_ct': Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct'] (one thing I'm going to try is update solr to the latest version.. will report if that does it..) I'm not sure where to look next.. Searching google, groups and stackoverflow didn't get me past this point. Thanks in advance!
[ "OK, problem solved. Updating to Solr 1.4.1 (and, strangely, rebooting after that) did the trick.\n" ]
[ 1 ]
[]
[]
[ "buildout", "django", "django_haystack", "python", "solr" ]
stackoverflow_0003685975_buildout_django_django_haystack_python_solr.txt
Q: Find associated value to a keyword in file with python Sorry for the beginner python question, but I cant find anywhere how to do this, so bear with me. I am trying to extract the values from a file containing keyword followed by a value: Example: length 95 width 332 length 1253 length 345 width 22 How do I extract all the values assosiated with the keyword "length" for example? A: the following code may help you. I haven't tested it so you may have to do some adjustment, but it should give you the basic idea import re f = open('filename', 'r') for line in f.readlines(): for m in re.finditer('length\s+(?P<number>\d+)', line): print m.group('number') A: The "re" module should do for you. Otherwise, if you know the (possibly few) keywords in your (possibly short) input, go the rough way and do some string slicing. A: >>> s = 'length 95 width 332 length 1253 length 345 width 22' >>> import re >>> re.findall(r'length (\w+)', s) ['95', '1253', '345'] This would do too, but it has additional constraints: >>> sp = s.split() >>> [sp[i+1] for i, l in enumerate(sp) if l == 'length'] ['95', '1253', '345'] A: You will have to split the contents, for example like so (if you're reading the whole file anyway): with open("filename", "rb") as f: l = f.read().split() valuesForLengthKeyword = tuple(int(l[i+1]) for i in xrange(0, len(l), 2) if l[i] == "length") print valuesForLengthKeyword This will print a tuple like (95, 1253, 345).
Find associated value to a keyword in file with python
Sorry for the beginner python question, but I cant find anywhere how to do this, so bear with me. I am trying to extract the values from a file containing keyword followed by a value: Example: length 95 width 332 length 1253 length 345 width 22 How do I extract all the values assosiated with the keyword "length" for example?
[ "the following code may help you. I haven't tested it so you may have to do some adjustment, but it should give you the basic idea\nimport re\n\nf = open('filename', 'r')\nfor line in f.readlines():\n for m in re.finditer('length\\s+(?P<number>\\d+)', line):\n print m.group('number')\n\n", "The \"re\" module ...
[ 1, 1, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003707563_python_string.txt
Q: Create user page at subdomain How to implement automatic page creation on a subdomain when a new user registers on the site? (Working in Python on the Plone CMS and Zope web app server) A: You should have a wildcard entry on your domain, i.e. *.example.com and use some of apache's rewrite magic to redirect this to the correct part of your site. This is already discussed elsewhere on StackOverflow
Create user page at subdomain
How to implement automatic page creation on a subdomain when a new user registers on the site? (Working in Python on the Plone CMS and Zope web app server)
[ "You should have a wildcard entry on your domain, i.e. *.example.com and use some of apache's rewrite magic to redirect this to the correct part of your site. This is already discussed elsewhere on StackOverflow\n" ]
[ 2 ]
[]
[]
[ "apache2", "mod_rewrite", "plone", "python", "zope" ]
stackoverflow_0003707757_apache2_mod_rewrite_plone_python_zope.txt
Q: Python complex event processing Are there any Python alternatives similar to Esper (Java and .NET) that deal with complex event processing (CEP)? A: Casual browsing indicates that this is not a very common problem domain for Python (although very interesting!). The framework that closest come to my mind is PEAK-Rules or dynrules. There might be more, but not widely known (I'll search a bit more) For your own digging: the place to find Python projects is first and foremost PyPI. (@cues7a: Twisted, while indeed being an event framework, is too low-level to be comparable to Esper.) Edit: It seems you can control Sybase's CEP products with Python A: The ruleCore CEP Server uses dynamically loaded Python modules which can be used to extend it. The internal architecture is build around a central event bus which uses a pub/sub approach. So each module can subscribe to internal events and publish events based on logic inside the module. A: What about Twisted Matrix?
Python complex event processing
Are there any Python alternatives similar to Esper (Java and .NET) that deal with complex event processing (CEP)?
[ "Casual browsing indicates that this is not a very common problem domain for Python (although very interesting!). The framework that closest come to my mind is PEAK-Rules or dynrules.\nThere might be more, but not widely known (I'll search a bit more)\nFor your own digging: the place to find Python projects is firs...
[ 4, 3, 0 ]
[]
[]
[ "complex_event_processing", "python" ]
stackoverflow_0003707000_complex_event_processing_python.txt
Q: Why are collections not handled uniformly in Python? Sets and lists are handled differently in Python, and there seems to be no uniform way to work with both. For example, adding an item to a set is done using the add method, and for the list it is done using the append method. I am aware that there are different semantics behind this, but there are also common semantics there, and often an algorithm that works with some collection cares more about the commonalities than the differences. The C++ STL shows that this can work, so why is there no such concept in Python? Edit: In C++ I can use an output_iterator to store values in an (almost) arbitrary type of collection, including lists and sets. I can write an algorithm that takes such an iterator as argument and writes elements to it. The algorithm then is completely agnostic to the kind of container (or other device, may be a file) that backs the iterator. If the backing container is a set that ignores duplicates, then that is the decision of the caller. My specific problem is, that it has happened several times to me now that I used for instance a list for a certain task and later decided that set is more appropriate. Now I have to change the append to add in several places in my code. I am just wondering why Python has no concept for such cases. A: The direct answer: it's a design flaw. You should be able to insert into any container where generic insertion makes sense (eg. excluding dict) with the same method name. There should be a consistent, generic name for insertion, eg. add, corresponding to set.add and list.append, so you can add to a container without having to care as much about what you're inserting into. Using different names for this operation in different types is a gratuitous inconsistency, and sets a poor base standard: the library should encourage user containers to use a consistent API, rather than providing largely incompatible APIs for each basic container. That said, it's not often a practical problem in this case: most of the time where a function's results are a list of items, implement it as a generator. They allow handling both of these consistently (from the perspective of the function), as well as other forms of iteration: def foo(): yield 1 yield 2 yield 3 s = set(foo()) l = list(foo()) results1 = [i*2 for i in foo()] results2 = (i*2 for i in foo()) for r in foo(): print r A: add and append are different. Sets are unordered and contain unique elements, while append suggest the item is always added, and that this is done specifically at the end. sets and lists can both be treated as iterables, and that's their common semantics, and that's freely usable by your algorithms. If you have an algorithm that depends on some sort of addition, you simply can't depend on sets, tuples, lists, dicts, strings behaving the same. A: The actual reason is probably just related to Python history. The built-in set type wasn't built-in until Python 2.6, and was based on a sets module, which itself wasn't in the standard library until Python 2.3. Obviously changing the semantics of the set type could break a host of existing code that relied on the original sets module, and generally language designers shy away from breaking existing code without a major number release. You can blame the original module author if you like, but keep in mind that user-defined types and built-in types necessarily lived in different universes until Python 2.2, which meant you couldn't directly extend a built-in type, and probably allowed module authors to feel OK about not maintaining consistent collection semantics.
Why are collections not handled uniformly in Python?
Sets and lists are handled differently in Python, and there seems to be no uniform way to work with both. For example, adding an item to a set is done using the add method, and for the list it is done using the append method. I am aware that there are different semantics behind this, but there are also common semantics there, and often an algorithm that works with some collection cares more about the commonalities than the differences. The C++ STL shows that this can work, so why is there no such concept in Python? Edit: In C++ I can use an output_iterator to store values in an (almost) arbitrary type of collection, including lists and sets. I can write an algorithm that takes such an iterator as argument and writes elements to it. The algorithm then is completely agnostic to the kind of container (or other device, may be a file) that backs the iterator. If the backing container is a set that ignores duplicates, then that is the decision of the caller. My specific problem is, that it has happened several times to me now that I used for instance a list for a certain task and later decided that set is more appropriate. Now I have to change the append to add in several places in my code. I am just wondering why Python has no concept for such cases.
[ "The direct answer: it's a design flaw.\nYou should be able to insert into any container where generic insertion makes sense (eg. excluding dict) with the same method name. There should be a consistent, generic name for insertion, eg. add, corresponding to set.add and list.append, so you can add to a container wit...
[ 6, 4, 1 ]
[]
[]
[ "collections", "python" ]
stackoverflow_0003707418_collections_python.txt
Q: Foreign Key relations in Django, with a select condition I've a table of partner type PartnerType Name Description RelatedToProject I've a PartnerMaster Name Address PartnerType I've a Project Table Name Partner (from partner master) The partner in the project table has to be only of those types who have RelatedToProject = True How can I achieve this in the model definition itself. A: I don't have much experience with Django, but you may want to consider removing the RelatedToProject field and adding another class called PartnersRelatedToProjects (or something like that). Then simply set up a normal foreign key from this new class to the Partner table, and in the Project class set up a normal foreign key to this new table. You would then need to keep track of which partners are related to projects by adding them to the new PartnersRelatedToProjects table. class Partner(models.Model): Name = models.CharField(max_length=200) Description = models.CharField(max_length=200) class PartnersRelatedToProjects(models.Model): partner = models.ForeignKey('Partner') class Project(models.Model): name = models.CharField(max_length=200) partner = models.ForeignKey('PartnersRelatedToProjects')
Foreign Key relations in Django, with a select condition
I've a table of partner type PartnerType Name Description RelatedToProject I've a PartnerMaster Name Address PartnerType I've a Project Table Name Partner (from partner master) The partner in the project table has to be only of those types who have RelatedToProject = True How can I achieve this in the model definition itself.
[ "I don't have much experience with Django, but you may want to consider removing the RelatedToProject field and adding another class called PartnersRelatedToProjects (or something like that). Then simply set up a normal foreign key from this new class to the Partner table, and in the Project class set up a normal f...
[ 1 ]
[]
[]
[ "django", "foreign_keys", "python" ]
stackoverflow_0003708074_django_foreign_keys_python.txt
Q: How to escape single quotes in Python on a server to be used in JavaScript on a client Consider: >>> sample = "hello'world" >>> print sample hello'world >>> print sample.replace("'","\'") hello'world In my web application I need to store my Python string with all single quotes escaped for manipulation later in the client browsers JavaScript. The trouble is Python uses the same backslash escape notation, so the replace operation as detailed above has no effect. Is there a simple workaround? A: As a general solution for passing data from Python to Javascript, consider serializing it with the json library (part of the standard library in Python 2.6+). >>> sample = "hello'world" >>> import json >>> print json.dumps(sample) "hello\'world" A: Use: sample.replace("'", r"\'") or sample.replace("'", "\\'")
How to escape single quotes in Python on a server to be used in JavaScript on a client
Consider: >>> sample = "hello'world" >>> print sample hello'world >>> print sample.replace("'","\'") hello'world In my web application I need to store my Python string with all single quotes escaped for manipulation later in the client browsers JavaScript. The trouble is Python uses the same backslash escape notation, so the replace operation as detailed above has no effect. Is there a simple workaround?
[ "As a general solution for passing data from Python to Javascript, consider serializing it with the json library (part of the standard library in Python 2.6+).\n>>> sample = \"hello'world\"\n>>> import json\n>>> print json.dumps(sample)\n\"hello\\'world\"\n\n", "Use:\nsample.replace(\"'\", r\"\\'\")\n\nor\nsample...
[ 61, 49 ]
[]
[]
[ "escaping", "javascript", "python", "string" ]
stackoverflow_0003708152_escaping_javascript_python_string.txt
Q: Regular Expression (Python) to extract strings of text from inside of < and > - e.g. etc I'm currently playing with the Stack Overflow data dumps and am trying to construct (what I imagine is) a simple regular expression to extract tag names from inside of < and > characters. So, for each question, I have a list of one or more tags like <tagone><tag-two>...<tag-n> and am trying to extract just a list of tag names. Here are a few example tag strings taken from the data dump: <javascript><internet-explorer> <c#><windows><best-practices><winforms><windows-services> <c><algorithm><sorting><word> <java> For reference, I don't need to divide tag names into words, so for examples like <best-practices> I would like to get back best-practices (not best and practices). Also, for what it's worth, I'm using Python if it makes any difference. Any suggestions? A: Since the tag names of Stackoverflow do not have embedded < > you can use the regex: <(.*?)> or <([^>]*)> Explanation: < : A literal < (..) : To group and remember the match. .*? : To match anything in non-greedy way. > : A literal < [^>] : A char class to match anything other than a > A: Instead of doing data dumps (whatever they are) and using regex, you may be interested in using the Stackoverflow API and json instead. For example, to cull the tags from this question, you could do this: import urllib2 import json import gzip import cStringIO f=urllib2.urlopen('http://api.stackoverflow.com/1.0/questions/3708418?type=jsontext') g=gzip.GzipFile(fileobj=cStringIO.StringIO(f.read())) j=json.loads(g.read()) print(j['questions'][0]['tags']) # [u'python', u'regex'] A: Here is a quick and dirty solution: #!/usr/bin/python import re pattern = re.compile("<(.*?)>") data = """ <javascript><internet-explorer> <c#><windows><best-practices><winforms><windows-services> <c><algorithm><sorting><word> <java> """ for each in pattern.findall(data): print each Update Statutory warning: if the data dump is in XML or JSON (as one of the users commented) then you are much better off using a suitable XML or JSON parser.
Regular Expression (Python) to extract strings of text from inside of < and > - e.g. etc
I'm currently playing with the Stack Overflow data dumps and am trying to construct (what I imagine is) a simple regular expression to extract tag names from inside of < and > characters. So, for each question, I have a list of one or more tags like <tagone><tag-two>...<tag-n> and am trying to extract just a list of tag names. Here are a few example tag strings taken from the data dump: <javascript><internet-explorer> <c#><windows><best-practices><winforms><windows-services> <c><algorithm><sorting><word> <java> For reference, I don't need to divide tag names into words, so for examples like <best-practices> I would like to get back best-practices (not best and practices). Also, for what it's worth, I'm using Python if it makes any difference. Any suggestions?
[ "Since the tag names of Stackoverflow do not have embedded < > you can use the regex:\n<(.*?)>\n\nor\n<([^>]*)>\n\nExplanation:\n\n< : A literal <\n(..) : To group and remember the\nmatch.\n.*? : To match anything in\nnon-greedy way.\n> : A literal <\n[^>] : A char class to match\nanything other than a >\n\n", "I...
[ 3, 3, 2 ]
[]
[]
[ "extraction", "python", "regex", "string", "tags" ]
stackoverflow_0003708418_extraction_python_regex_string_tags.txt
Q: Python smtplib and multiple messages per connection recently i'm studing the smtplib smtp client library for python, but i could not find any reference to the PIPELINING protocol against smtp servers that support it. Is there something i'm missing? It's not yet implemented maybe? Any other implementations rather than smtplib with PIPELINING enabled? Thanks A: Is there something i'm missing? Quite possibly. Simply put PIPELINING is sending SMTP commands without waiting for the responses. It doesn't tend to be implemented because the benefits are marginal and it increases the complexity of error states. From your comment, it sounds as if you are worried that only one message will be sent through one connection. This is not PIPELINING. smtplib supports using the same connection for multiple messages. You can just call sendmail multiple times. E.g. s = smtplib.SMTP("localhost") s.sendmail("foo@bar.baz",["bar@foo.baz"],message1) s.sendmail("foo@bar.baz",["baz@foo.baz"],message2) Final update which is the max number of messages i can append "per-connection" ? This varies between SMTP daemons. Exim seems to default to 1000. do i have to do this synchronously or does smtplib eventually handle contemporary sendmail calls ? The call to the sendmail method will block until complete, your calls will be sequential. If you need to parallelize then you might need to look at threading, multiprocessing or perhaps twisted. There are many possible approaches. The number of concurrent connections you are allowed may also be an SMTP daemon configuration item.
Python smtplib and multiple messages per connection
recently i'm studing the smtplib smtp client library for python, but i could not find any reference to the PIPELINING protocol against smtp servers that support it. Is there something i'm missing? It's not yet implemented maybe? Any other implementations rather than smtplib with PIPELINING enabled? Thanks
[ "\nIs there something i'm missing?\n\nQuite possibly.\nSimply put PIPELINING is sending SMTP commands without waiting for the responses. It doesn't tend to be implemented because the benefits are marginal and it increases the complexity of error states.\nFrom your comment, it sounds as if you are worried that only ...
[ 7 ]
[]
[]
[ "python", "smtp", "smtplib" ]
stackoverflow_0003707945_python_smtp_smtplib.txt
Q: Python changes Integer in Float by itself I'm trying to learn Python, (i have 2.5.4) by writing a snake game, but I'm stuck. Some integers change into floats and keep changing randomly, at least from my perspective :) The problem is that Snake.spawnPoint gets changed by Cam.move() print Snake.spawnPoint # first time, this returns '[25, 20]' ,which is good. Cam.Move() print Snake.spawnPoint # after the method, the value is '[26.0, 21.0]', and that's bad After that, they just drift around. And this is the method: (it has nothing to do with the spawnPoint def Move(self): self.vel[0]+=(self.target[0]-self.cen[0])*self.k self.vel[1]+=(self.target[1]-self.cen[1])*self.k if self.vel[0] > self.friction: self.vel[0]-= self.friction elif self.vel[0] < self.friction: self.vel[0]+= self.friction else: self.vel[0] = 0 if self.vel[1] > self.friction: self.vel[1]-= self.friction elif self.vel[1] < self.friction: self.vel[1]+= self.friction else: self.vel[1]=0 self.cen[0]+=self.vel[0] self.cen[1]+=self.vel[1] The spawnPoint is a constant that I append to the snake's body when he spawns. I like it to be a list because it have the snake's body made of lists, and the rendering method uses index() to do stuff. The code doesn't seem to fit here, so i zipped it. Can someone take a look at it? Thanks http://www.mediafire.com/?zdcx5s93q9hxz4o A: Integers change to floats if you combine them in an expression, i.e. multiplication, addition, subtraction (not necessarily division). Most likely, some of your variables are floats, e.g. self.friction. floats don't change back to integers by themselves, only through int(). If you observe anything else, you observe it wrong. It appears your Move method modifies "spanwPoint" indirectly. I don't know if this is expected behavhiour, but it probably means you have two references pointing to the same list. E.g. self.spawnPoint = [1, 0] self.vel = self.spawnPoint # Does not make a copy! self.vel[0] += 0.1 self.vel[1] += 0.2 will result in self.spawnPoint (also) being [1.1, 0.2] A: In Python (as in many other languages) any simple arithmetic operation (e.g. +,-,/,*) involving an integer and a float evaluates to an answer that is a float. Integers never change into floats, it is the result of the operation that is returned as a float. Note that the result of operations involving only integers is returned as an integer (I'm using the word integer to refer to both int and long in Python).
Python changes Integer in Float by itself
I'm trying to learn Python, (i have 2.5.4) by writing a snake game, but I'm stuck. Some integers change into floats and keep changing randomly, at least from my perspective :) The problem is that Snake.spawnPoint gets changed by Cam.move() print Snake.spawnPoint # first time, this returns '[25, 20]' ,which is good. Cam.Move() print Snake.spawnPoint # after the method, the value is '[26.0, 21.0]', and that's bad After that, they just drift around. And this is the method: (it has nothing to do with the spawnPoint def Move(self): self.vel[0]+=(self.target[0]-self.cen[0])*self.k self.vel[1]+=(self.target[1]-self.cen[1])*self.k if self.vel[0] > self.friction: self.vel[0]-= self.friction elif self.vel[0] < self.friction: self.vel[0]+= self.friction else: self.vel[0] = 0 if self.vel[1] > self.friction: self.vel[1]-= self.friction elif self.vel[1] < self.friction: self.vel[1]+= self.friction else: self.vel[1]=0 self.cen[0]+=self.vel[0] self.cen[1]+=self.vel[1] The spawnPoint is a constant that I append to the snake's body when he spawns. I like it to be a list because it have the snake's body made of lists, and the rendering method uses index() to do stuff. The code doesn't seem to fit here, so i zipped it. Can someone take a look at it? Thanks http://www.mediafire.com/?zdcx5s93q9hxz4o
[ "Integers change to floats if you combine them in an expression, i.e. multiplication, addition, subtraction (not necessarily division). Most likely, some of your variables are floats, e.g. self.friction.\nfloats don't change back to integers by themselves, only through int(). If you observe anything else, you obser...
[ 4, 1 ]
[]
[]
[ "floating_point", "integer", "python" ]
stackoverflow_0003701344_floating_point_integer_python.txt
Q: What is happening to my process? I'm executing a SSH process like so: checkIn() sshproc = subprocess.Popen([command], shell=True) exit = os.waitpid(sshproc.pid, 0)[1] checkOut() Its important that the process form checkIn() and checkOut() actions before and after these lines of code. I have a test case that involves that I exit the SSH session by closing the terminal window manually. Sure enough, my program doesn't operate correctly and checkOut() is never called in this case. Can someone give me a pointer into what I can look in to fix this bug? Let me know if any other information would helpful. Thanks! A: The Python process would normally execute in the same window as the ssh subprocess, and therefore be terminated just as abruptly when you close that window -- before getting a chance to execute checkOut. To try and ensure that a function gets called at program exit (though for sufficiently-abrupt terminations, depending on your OS, there may be no guarantees), try Python standard library module atexit. A: Perhaps all you need is a try ... finally block? try: checkIn() sshproc = subprocess.Popen([command], shell=True) exit = os.waitpid(sshproc.pid, 0)[1] finally: checkOut() Unless the system crashes, the process receives SIGKILL, etc., checkOut() should be called.
What is happening to my process?
I'm executing a SSH process like so: checkIn() sshproc = subprocess.Popen([command], shell=True) exit = os.waitpid(sshproc.pid, 0)[1] checkOut() Its important that the process form checkIn() and checkOut() actions before and after these lines of code. I have a test case that involves that I exit the SSH session by closing the terminal window manually. Sure enough, my program doesn't operate correctly and checkOut() is never called in this case. Can someone give me a pointer into what I can look in to fix this bug? Let me know if any other information would helpful. Thanks!
[ "The Python process would normally execute in the same window as the ssh subprocess, and therefore be terminated just as abruptly when you close that window -- before getting a chance to execute checkOut. To try and ensure that a function gets called at program exit (though for sufficiently-abrupt terminations, de...
[ 1, 1 ]
[]
[]
[ "process", "python" ]
stackoverflow_0003706125_process_python.txt
Q: How to know the location of the library that I load in Python? import ABC loads ABC from somewhere. How can I know the 'somewhere'? I may be able to check the paths in sys.path one by one, but I wonder if I can find it in Python. More Questions When I load library with 'from ABC import *', how can I know where ABC is located? Can 'class xyz' know where it is located when it is called? A: >>> import abc >>> abc.__file__ 'C:\\Program Files\\Python31\\lib\\abc.py' See docs. for more thorough inspection you could use inspect module: >>> import inspect >>> from abc import * >>> inspect.getfile(ABCMeta) 'C:\\Program Files\\Python31\\lib\\abc.py'
How to know the location of the library that I load in Python?
import ABC loads ABC from somewhere. How can I know the 'somewhere'? I may be able to check the paths in sys.path one by one, but I wonder if I can find it in Python. More Questions When I load library with 'from ABC import *', how can I know where ABC is located? Can 'class xyz' know where it is located when it is called?
[ ">>> import abc\n>>> abc.__file__\n'C:\\\\Program Files\\\\Python31\\\\lib\\\\abc.py'\n\nSee docs.\nfor more thorough inspection you could use inspect module:\n>>> import inspect\n>>> from abc import *\n>>> inspect.getfile(ABCMeta)\n'C:\\\\Program Files\\\\Python31\\\\lib\\\\abc.py'\n\n" ]
[ 12 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003709405_path_python.txt
Q: Sql Alchemy > TypeError: 'instancemethod' object does not support item assignment Here's what I've got: from sqlalchemy import * from sqlalchemy.orm import * from web.models.card import * connectionString = "postgresql://www:www@localhost/prod" databaseEngine = create_engine(connectionString) sessionFactory = sessionmaker(autoflush = True, autocommit = False, bind = databaseEngine) session = sessionFactory() CardsCollection = session.query(card).all() _content = {} for index in range(0, len(CardsCollection)): c = CardsCollection[index] _content[index] = c print json.dumps(_content) And here's the error: Traceback (most recent call last): File "/home/src/py/raspberry/src/dictionaryTest.py", line 15, in CardsCollection = session.query(card).all() File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1453, in all return list(self) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1676, in instances rows = [process[0](row, None) for row in fetch] File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/mapper.py", line 2234, in _instance populate_state(state, dict_, row, isnew, only_load_props) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/mapper.py", line 2113, in populate_state populator(state, dict_, row) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/strategies.py", line 127, in new_execute dict_[key] = row[col] TypeError: 'instancemethod' object does not support item assignment Can someone help me out with this? I've tried a few things, and researched into how dictionaries work... but its just not jumping out at me. [edit for strange resolution] Apparently, overriding the self.__dict__(self) method on the card model is what did it. I'm not entirely sure why, though. A: __dict__ is a special attribute holding current state of instance, overwriting it with with method will certainly lead to troubles.
Sql Alchemy > TypeError: 'instancemethod' object does not support item assignment
Here's what I've got: from sqlalchemy import * from sqlalchemy.orm import * from web.models.card import * connectionString = "postgresql://www:www@localhost/prod" databaseEngine = create_engine(connectionString) sessionFactory = sessionmaker(autoflush = True, autocommit = False, bind = databaseEngine) session = sessionFactory() CardsCollection = session.query(card).all() _content = {} for index in range(0, len(CardsCollection)): c = CardsCollection[index] _content[index] = c print json.dumps(_content) And here's the error: Traceback (most recent call last): File "/home/src/py/raspberry/src/dictionaryTest.py", line 15, in CardsCollection = session.query(card).all() File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1453, in all return list(self) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 1676, in instances rows = [process[0](row, None) for row in fetch] File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/mapper.py", line 2234, in _instance populate_state(state, dict_, row, isnew, only_load_props) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/mapper.py", line 2113, in populate_state populator(state, dict_, row) File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/strategies.py", line 127, in new_execute dict_[key] = row[col] TypeError: 'instancemethod' object does not support item assignment Can someone help me out with this? I've tried a few things, and researched into how dictionaries work... but its just not jumping out at me. [edit for strange resolution] Apparently, overriding the self.__dict__(self) method on the card model is what did it. I'm not entirely sure why, though.
[ "__dict__ is a special attribute holding current state of instance, overwriting it with with method will certainly lead to troubles.\n" ]
[ 1 ]
[]
[]
[ "dictionary", "python", "python_2.6", "sqlalchemy" ]
stackoverflow_0003653690_dictionary_python_python_2.6_sqlalchemy.txt
Q: Calling a REST service with Python I have a REST service that I'm trying to call. It requires something similar to the following syntax: http://someServerName:8080/projectName/service/serviceName/ param1Name/param1/param2Name/param2 I have to connect to it using POST. I've tried reading up on it online (here and here, for example)... but this is my problem: If I try using the HTTP get request method, by building my own path, like this: BASE_PATH = "http://someServerName:8080/projectName/service/serviceName/" urllib.urlopen(BASE_PATH + "param1/" + param1 + "/param2/" + param2) it gives me an error saying that GET is not allowed. If I try using the HTTP post request method, like this: params = { "param1" : param1, "param2" : param2 } urllib.urlopen(BASE_PATH, urllib.urlencode(params)) it returns a 404 error along with the message The requested resource () is not available. And when I debug this, it seems to be building the params into a query string ("param1=whatever&param2=whatever"...) How can I use POST but pass the parameters delimited by slashes as it's expected? What am I doing wrong? A: I know this is sort of unfair, but this is what ended up happening... The programmer in charge of the REST service changed it to use the &key=value syntax. A: Use urllib2 You're going to have to be clever; something like params = { "param1" : param1, "param2" : param2 } urllib2.urlopen(BASE_PATH + "?" + urllib.urlencode(params), " ") Might work. A: Something like this might work: param1, param2 = urllib.quote_plus(param1), urllib.quote_plus(param2) BASE_PATH = "http://someServerName:8080/projectName/service/serviceName/" urllib.urlopen(BASE_PATH + "param1/" + param1 + "/param2/" + param2, " ") The second argument to urlopen tells it to do a POST request, with empty data. The quote_plus allows you to escape special characters without being forced into the &key=value scheme.
Calling a REST service with Python
I have a REST service that I'm trying to call. It requires something similar to the following syntax: http://someServerName:8080/projectName/service/serviceName/ param1Name/param1/param2Name/param2 I have to connect to it using POST. I've tried reading up on it online (here and here, for example)... but this is my problem: If I try using the HTTP get request method, by building my own path, like this: BASE_PATH = "http://someServerName:8080/projectName/service/serviceName/" urllib.urlopen(BASE_PATH + "param1/" + param1 + "/param2/" + param2) it gives me an error saying that GET is not allowed. If I try using the HTTP post request method, like this: params = { "param1" : param1, "param2" : param2 } urllib.urlopen(BASE_PATH, urllib.urlencode(params)) it returns a 404 error along with the message The requested resource () is not available. And when I debug this, it seems to be building the params into a query string ("param1=whatever&param2=whatever"...) How can I use POST but pass the parameters delimited by slashes as it's expected? What am I doing wrong?
[ "I know this is sort of unfair, but this is what ended up happening... The programmer in charge of the REST service changed it to use the &key=value syntax.\n", "\nUse urllib2\nYou're going to have to be clever; something like\nparams = { \"param1\" : param1, \"param2\" : param2 }\nurllib2.urlopen(BASE_PATH + \"?...
[ 5, 2, 0 ]
[]
[]
[ "post", "python", "rest", "web_services" ]
stackoverflow_0003579012_post_python_rest_web_services.txt
Q: twisted IRCClient with a listentcp I'm trying to make a simple IRC bot that also listens to another port for incoming data and relays that to an IRC channel.. I'm using the following as sample code for my bot http://www.eflorenzano.com/blog/post/writing-markov-chain-irc-bot-twisted-and-python/ I'm getting stuck how I also add a listenTCP to be able to talk to the bot with the reactor. I can make it listen but not sure how to send it to the bot so the bot can msg the channel A: This is a variation of a popular FAQ, answered here.
twisted IRCClient with a listentcp
I'm trying to make a simple IRC bot that also listens to another port for incoming data and relays that to an IRC channel.. I'm using the following as sample code for my bot http://www.eflorenzano.com/blog/post/writing-markov-chain-irc-bot-twisted-and-python/ I'm getting stuck how I also add a listenTCP to be able to talk to the bot with the reactor. I can make it listen but not sure how to send it to the bot so the bot can msg the channel
[ "This is a variation of a popular FAQ, answered here.\n" ]
[ 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003709473_python_twisted.txt
Q: How to re-use a reusable app in Django I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called "reusable apps". I understand the concept of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are: What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it? From what I understand, the recommendation is to put it on your "PYTHONPATH", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service). So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)? How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use? A: In general, the only thing required to use a reusable app is to make sure it's on sys.path, so that you can import it from Python code. In most cases (if the author follows best practice), the reusable app tarball or bundle will contain a top-level directory with docs, a README, a setup.py, and then a subdirectory containing the actual app (see django-voting for an example; the app itself is in the "voting" subdirectory). This subdirectory is what needs to be placed in your Python path. Possible methods for doing that include: running pip install appname, if the app has been uploaded to PyPI (these days most are) installing the app with setup.py install (this has the same result as pip install appname, but requires that you first download and unpack the code yourself; pip will do that for you) manually symlinking the code directory to your Python site-packages directory using software like virtualenv to create a "virtual Python environment" that has its own site-packages directory, and then running setup.py install or pip install appname with that virtualenv active, or placing or symlinking the app in the virtualenv's site-packages (highly recommended over all the "global installation" options, if you value your future sanity) placing the application in some directory where you intend to place various apps, and then adding that directory to the PYTHONPATH environment variable You'll know you've got it in the right place if you can fire up a Python interpreter and "import voting" (for example) without getting an ImportError. On a server where you have FTP access only, your only option is really the last one, and they have to set it up for you. If they claim to support Django they must provide some place where you can upload packages and they will be available for importing in Python. Without knowing details of your webhost, it's impossible to say how they structure that for you. A: An old question, but here's what I do: If you're using a version control system (VCS), I suggest putting all of the reusable apps and libraries (including django) that your software needs in the VCS. If you don't want to put them directly under your project root, you can modify settings.py to add their location to sys.path. After that deployment is as simple as cloning or checking out the VCS repository to wherever you want to use it. This has two added benefits: Version mismatches; your software always uses the version that you tested it with, and not the version that was available at the time of deployment. If multiple people work on the project, nobody else has to deal with installing the dependencies. When it's time to update a component's version, update it in your VCS and then propagate the update to your deployments via it.
How to re-use a reusable app in Django
I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called "reusable apps". I understand the concept of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are: What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it? From what I understand, the recommendation is to put it on your "PYTHONPATH", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service). So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)? How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use?
[ "In general, the only thing required to use a reusable app is to make sure it's on sys.path, so that you can import it from Python code. In most cases (if the author follows best practice), the reusable app tarball or bundle will contain a top-level directory with docs, a README, a setup.py, and then a subdirector...
[ 28, 2 ]
[]
[]
[ "code_reuse", "django", "python" ]
stackoverflow_0000557171_code_reuse_django_python.txt
Q: django forms autofiled by browser so I have 2 classes this one: class updateForm(forms.Form): address = forms.CharField( max_length = 255, label = 'Home Address', ) cnp = forms.CharField( max_length = 15, label = 'CNP', ) phoneNumber = forms.CharField( max_length = 30, label = 'Phone number', ) token = forms.CharField( max_length = 20, label = 'token', ) oldPass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'Old Password', ) newPass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'New Password', ) retypePass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'Retype Password', ) and this one: class BaseUsernameForm(forms.Form): username = forms.CharField(max_length=255, label='Username') def clean_username(self): username = self.cleaned_data['username'] return _clean_username(username) class BasePasswordForm(forms.Form): password = forms.CharField(max_length=255, widget=forms.PasswordInput, label='Password') class LoginForm(BaseUsernameForm, BasePasswordForm): pass after I login in ... and get to the page where the updateForm is ... i get the token and oldPass field autofiled with the token: username and oldPass: password from the loginForm ... why ? In the html they dont share any id or class ... how can I prevent this ? A: Maybe the values are filled in by your browser? Try a autocomplete="OFF" for the token and oldPass input field to get something like this: <input type="text" autocomplete="OFF" name="token"/>
django forms autofiled by browser
so I have 2 classes this one: class updateForm(forms.Form): address = forms.CharField( max_length = 255, label = 'Home Address', ) cnp = forms.CharField( max_length = 15, label = 'CNP', ) phoneNumber = forms.CharField( max_length = 30, label = 'Phone number', ) token = forms.CharField( max_length = 20, label = 'token', ) oldPass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'Old Password', ) newPass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'New Password', ) retypePass = forms.CharField( widget = forms.PasswordInput, max_length = 30, label = 'Retype Password', ) and this one: class BaseUsernameForm(forms.Form): username = forms.CharField(max_length=255, label='Username') def clean_username(self): username = self.cleaned_data['username'] return _clean_username(username) class BasePasswordForm(forms.Form): password = forms.CharField(max_length=255, widget=forms.PasswordInput, label='Password') class LoginForm(BaseUsernameForm, BasePasswordForm): pass after I login in ... and get to the page where the updateForm is ... i get the token and oldPass field autofiled with the token: username and oldPass: password from the loginForm ... why ? In the html they dont share any id or class ... how can I prevent this ?
[ "Maybe the values are filled in by your browser? Try a autocomplete=\"OFF\" for the token and oldPass input field to get something like this:\n<input type=\"text\" autocomplete=\"OFF\" name=\"token\"/>\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "forms", "python" ]
stackoverflow_0003709554_django_django_forms_forms_python.txt
Q: Lookup Error after packaging python script with py2exe I have written a python script which binds to a socket like this: from socket import * addr = (unicode(), 11111) mySocket = socket(AF_INET, SOCK_STREAM) mySocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) mySocket.bind(addr) I package this script with py2exe using setup.py with the following options: setup( console=["myProgram.py"], options = {"py2exe": {"compressed": 1, "optimize": 2, "bundle_files": 1, "excludes": ["w9xpopen.exe"], "packages": ["encodings","codecs"], }}, zipfile = None) Under Python 2.5 this works fine. However, when I package the source under python 2.6, I get the following error: Traceback (most recent call last): File "Mod_CommsServ.pyo", line 201, in __init File "<string>", line 1, in bind LookupError: unknown encoding: idna As you can see, I already included encodings for py2exe, but the executable still is not able to resolve 'idna'. Can anybody help me? A: Because you pass a unicode string as hostname, python2.6 assumes "IDNA" (Internationalized Domain Names in Applications) needs to take place. Just use addr = ('', 11111) in stead, unless you have very good reasons to require IDNA support.
Lookup Error after packaging python script with py2exe
I have written a python script which binds to a socket like this: from socket import * addr = (unicode(), 11111) mySocket = socket(AF_INET, SOCK_STREAM) mySocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) mySocket.bind(addr) I package this script with py2exe using setup.py with the following options: setup( console=["myProgram.py"], options = {"py2exe": {"compressed": 1, "optimize": 2, "bundle_files": 1, "excludes": ["w9xpopen.exe"], "packages": ["encodings","codecs"], }}, zipfile = None) Under Python 2.5 this works fine. However, when I package the source under python 2.6, I get the following error: Traceback (most recent call last): File "Mod_CommsServ.pyo", line 201, in __init File "<string>", line 1, in bind LookupError: unknown encoding: idna As you can see, I already included encodings for py2exe, but the executable still is not able to resolve 'idna'. Can anybody help me?
[ "Because you pass a unicode string as hostname, python2.6 assumes \"IDNA\" (Internationalized Domain Names in Applications) needs to take place.\nJust use \naddr = ('', 11111)\n\nin stead, unless you have very good reasons to require IDNA support.\n" ]
[ 0 ]
[]
[]
[ "py2exe", "python", "sockets" ]
stackoverflow_0003708788_py2exe_python_sockets.txt
Q: Can logging and CherryPy share the same config file? Both the Python logging module and CherryPy's Config API use ConfigParser files. Therefore, I assumed that I could use one single config file for my own applications configuration, it's logging configuration, and CherryPy's configuration. When my logging and CherryPy were separate, they worked fine, and my config file does parse with no errors using the ConfigParser api. However, CherryPy seems to barf on this section: [loggers] keys=root,myapp,cherrypy,cperror,cpaccess giving the following exception: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap self.run() File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "unittests.py", line 431, in main cherrypy.config.update(server.CONFIG_FILE) File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 263, in update config = _Parser().dict_from_file(config) File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 383, in dict_from_file return self.as_dict() File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 374, in as_dict raise ValueError(msg, x.__class__.__name__, x.args) ValueError: ("Config error in section: 'loggers', option: 'keys', value: 'root,myapp,cherrypy,cperror,cpaccess'. Config values must be valid Python.", 'TypeError', ("unrepr could not resolve the name 'root'",)) The CherryPy docs never say that CherryPy needs its config file to be separate from your other configuration, but I'm beginning to think that this might be necessary. The docs say that site and app configuration might need to be separate if you have more than one app per site, but that seems like a different issue... is it mistaking my logging configuration for a CherryPy app configuration? Is this possible? If not, then I'm unsure why CherryPy even bothers using the ConfigParser library in the first place. A: Short answer: no, you probably cannot mix them. As described in the docs: "Config entries are always a key/value pair, like server.socket_port = 8080. The key is always a name, and the value is always a Python object. That is, if the value you are setting is an int (or other number), it needs to look like a Python int; for example, 8080. If the value is a string, it needs to be quoted, just like a Python string." Even though we want arbitrary Python types in our CherryPy config values, CherryPy uses the ConfigParser simply because we didn't want to write our own parser for the section and entry syntax.
Can logging and CherryPy share the same config file?
Both the Python logging module and CherryPy's Config API use ConfigParser files. Therefore, I assumed that I could use one single config file for my own applications configuration, it's logging configuration, and CherryPy's configuration. When my logging and CherryPy were separate, they worked fine, and my config file does parse with no errors using the ConfigParser api. However, CherryPy seems to barf on this section: [loggers] keys=root,myapp,cherrypy,cperror,cpaccess giving the following exception: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap self.run() File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "unittests.py", line 431, in main cherrypy.config.update(server.CONFIG_FILE) File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 263, in update config = _Parser().dict_from_file(config) File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 383, in dict_from_file return self.as_dict() File "/usr/lib/pymodules/python2.6/cherrypy/_cpconfig.py", line 374, in as_dict raise ValueError(msg, x.__class__.__name__, x.args) ValueError: ("Config error in section: 'loggers', option: 'keys', value: 'root,myapp,cherrypy,cperror,cpaccess'. Config values must be valid Python.", 'TypeError', ("unrepr could not resolve the name 'root'",)) The CherryPy docs never say that CherryPy needs its config file to be separate from your other configuration, but I'm beginning to think that this might be necessary. The docs say that site and app configuration might need to be separate if you have more than one app per site, but that seems like a different issue... is it mistaking my logging configuration for a CherryPy app configuration? Is this possible? If not, then I'm unsure why CherryPy even bothers using the ConfigParser library in the first place.
[ "Short answer: no, you probably cannot mix them. As described in the docs: \"Config entries are always a key/value pair, like server.socket_port = 8080. The key is always a name, and the value is always a Python object. That is, if the value you are setting is an int (or other number), it needs to look like a Pytho...
[ 4 ]
[]
[]
[ "cherrypy", "configparser", "logging", "python" ]
stackoverflow_0003710073_cherrypy_configparser_logging_python.txt
Q: How to print what I think is an object? test = ["a","b","c","d","e"] def xuniqueCombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)-n+1): for cc in xuniqueCombinations(items[i+1:],n-1): yield [items[i]]+cc x = xuniqueCombinations(test, 3) print x outputs "generator object xuniqueCombinations at 0x020EBFA8" I want to see all the combinations that it found. How can i do that? A: leoluk is right, you need to iterate over it. But here's the correct syntax: combos = xuniqueCombinations(test, 3) for x in combos: print x Alternatively, you can convert it to a list first: combos = list(xuniqueCombinations(test, 3)) print combos A: This is a generator object. Access it by iterating over it: for x in xuniqueCombinations: print x A: x = list(xuniqueCombinations(test, 3)) print x convert your generator to list, and print......
How to print what I think is an object?
test = ["a","b","c","d","e"] def xuniqueCombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)-n+1): for cc in xuniqueCombinations(items[i+1:],n-1): yield [items[i]]+cc x = xuniqueCombinations(test, 3) print x outputs "generator object xuniqueCombinations at 0x020EBFA8" I want to see all the combinations that it found. How can i do that?
[ "leoluk is right, you need to iterate over it. But here's the correct syntax:\ncombos = xuniqueCombinations(test, 3)\nfor x in combos:\n print x\n\nAlternatively, you can convert it to a list first:\ncombos = list(xuniqueCombinations(test, 3))\nprint combos\n\n", "This is a generator object. Access it by itera...
[ 17, 4, 0 ]
[ "It might be handy to look at the pprint module: http://docs.python.org/library/pprint.html if you're running python 2.7 or more:\nfrom pprint import pprint\npprint(x)\n\n" ]
[ -3 ]
[ "generator", "python" ]
stackoverflow_0003710823_generator_python.txt
Q: get the host the user is coming from i wanted to know in python how can i get the host the user came from? how do i extract it? i tried this: host = self.request._environ['HTTP_HOST'] but it's empty... Do you have any idea what it should be Thanks. A: self.request._environ['HTTP_HOST'] tells you your host name. You can use self.request.remote_addr to get the remote IP address. You'll need to do a reverse DNS lookup (which might fail) if you need a host name from that.
get the host the user is coming from
i wanted to know in python how can i get the host the user came from? how do i extract it? i tried this: host = self.request._environ['HTTP_HOST'] but it's empty... Do you have any idea what it should be Thanks.
[ "self.request._environ['HTTP_HOST'] tells you your host name.\nYou can use self.request.remote_addr to get the remote IP address. You'll need to do a reverse DNS lookup (which might fail) if you need a host name from that.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "http_host", "python" ]
stackoverflow_0003711008_google_app_engine_http_host_python.txt
Q: Playing MP3 files with Python I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it has too much in the way of documentation. Are there any other alternatives? A: There is http://pyglet.org/ and also have you tried http://code.google.com/p/mp3play/? It's also available from PyPi (http://pypi.python.org/pypi/mp3play/) However, I think mp3play is Win32 only for now. Looking at the updates, there were commits within last couple of months. A: I've been using PyMedia in Python 2.6.5 on Windows successfully. Caveats: the documentation is bad and wrong -- many of the tutorials have glaring errors or otherwise don't work -- so I had to do some experimentation and Googling to get my code to work right. Also for whatever reason the maintainers seem to have stopped updating the project site 4 years ago, though they seem to be actively doing something. I found installers here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ The semi-active forum linked from their website includes some code maintainers who are semi-helpful. I'm jboyd99 if anyone is looking for tips. For reasons that are beyond me the focus is on car audio systems, despite the fact that it is a fairly fully featured library that does some things no other free Python library does, like read MP3s into raw PCM data. The library has some flaws -- I'll probably use PyAudio or PyAudiere for actual playback for better control of synchrony issues. A: Maybe it'd be simpler to write that part of your application in Python 2.4 as a separate "backend". This way you could use PyMedia (http://pymedia.org/) (as you mentioned) for the actual playback. It'd allow you to write your GUI in another Python version (like 2.6), which would also mean more decoupling of program components and parallelism (smoother GUI). If you target only the Windows platform, then using Media Player via COM might help: http://www.daniweb.com/code/snippet216465.html
Playing MP3 files with Python
I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it has too much in the way of documentation. Are there any other alternatives?
[ "There is http://pyglet.org/ and also have you tried http://code.google.com/p/mp3play/? It's also available from PyPi (http://pypi.python.org/pypi/mp3play/) However, I think mp3play is Win32 only for now.\nLooking at the updates, there were commits within last couple of months.\n", "I've been using PyMedia in Pyt...
[ 4, 1, 0 ]
[]
[]
[ "mp3", "playback", "python" ]
stackoverflow_0001804366_mp3_playback_python.txt
Q: Will nginx+paste hold up in a production environment? I've developed a website in Pylons (Python web framework) and have it running, on my production server, under Apache + mod_wsgi. I've been hearing a lot of good things about nginx recently and wanted to give it a try. Currently, it's running as a forwarding proxy to create a front end to Paste. It seems to be running pretty damn fast... Though, I could probably contribute that to me being the only one accessing it. What I want to know is, how will Paste hold up under a heavy load? Am I better off going with nginx + mod_wsgi ? A: Your app will be the bottleneck in performance not Apache or Paste. Nginx is used in lots of production servers so that bit will be fine. I don't know about mod_wsgi but uWSGI is used in production environments and plays well with both nginx and Paste applications. I currently run a server using Apache + Paste using Apache to serve static content and Paste to handle Pylons. When I stress tested the setup (using default settings on Apache) I got a lot of variation in the time it took to handle requests (varying from 0.5 to 10 secs). As a test I setup Nginx + uWSGI. Nginx is known to be very good for handling static content and I saw a 10x improvement in the number of files it could serve. The average response time for the Pylons app didn't change (it's DB bound) but the variability dropped to almost zero. Neither setup dropped a connection or failed to respond so based on this I'll be moving to Nginx + uWSGI for our next app, especially as it has a lot more static content.
Will nginx+paste hold up in a production environment?
I've developed a website in Pylons (Python web framework) and have it running, on my production server, under Apache + mod_wsgi. I've been hearing a lot of good things about nginx recently and wanted to give it a try. Currently, it's running as a forwarding proxy to create a front end to Paste. It seems to be running pretty damn fast... Though, I could probably contribute that to me being the only one accessing it. What I want to know is, how will Paste hold up under a heavy load? Am I better off going with nginx + mod_wsgi ?
[ "Your app will be the bottleneck in performance not Apache or Paste.\nNginx is used in lots of production servers so that bit will be fine. I don't know about mod_wsgi but uWSGI is used in production environments and plays well with both nginx and Paste applications.\nI currently run a server using Apache + Paste u...
[ 1 ]
[]
[]
[ "nginx", "paste", "production_environment", "pylons", "python" ]
stackoverflow_0003689766_nginx_paste_production_environment_pylons_python.txt
Q: Django - deleting object, keeping parent? I have the following multi-table inheritance situation: from django.db import Models class Partner(models.Model): # this model contains common data for companies and persons code = models.CharField() name = models.CharField() class Person(Partner): # some person-specific data ssn = models.CharField() class Company(Partner): # some company-specific data tax_no = models.CharField() How can I convert a Company instance to a Person one, and vice-versa? Let's say someone mistakenly created a Company instance with person's details: company = Company(name="John Smith", tax_no="<some-ssn-#>") I want to convert all wrong Company objects (that were meant to be Persons) to Person objects, keeping all related records (I have models with FKs to the Partner model, so it's important to keep the same partner_ptr value). I can do something like this: person = Person(name=company.name, ssn=company.tax_no, partner_ptr=company.partner_ptr) So far so good, but is it possible to delete the Company objects that are not needed anymore? Deleting the Company object will also delete it's parent Partner object (and any related to the partner, including the newly created Person object). Any recommendations? Thanks! P.S.: This is an already deployed system, with lots of data in it and it is not possible to redesign the whole Partner-Person-Company inheritance concept. A: One way to go about this would be to first add a dummy Partner per each company awaiting deletion. After that you can update the partner_ptr of all unwanted Company instances to the appropriate dummy partner instance. Finally you can delete all the companies. Of course you can use South to help do this. Update Did some rudimentary testing and this works. I am using Django 1.2.1. I have tried this, it's not possible: In 1: Company.objects.get(pk=7924) Out1: In [2]: c.partner_ptr = Partner() In [3]: c.pk In [4]: c.delete() AssertionError: Company object can't be deleted because its partner_ptr_id attribute is set to None. Setting the partner_ptr instance to a dummy one changes the company's PK and it's not the Company. You have to attach a new Partner and then save the company. Then you can safely delete it. So: company = Company.objects.get(pk=7924) dummy_partner = Partner(code = "dummy", name = "dummy") company.partner_ptr = dummy_partner company.save() company.delete()
Django - deleting object, keeping parent?
I have the following multi-table inheritance situation: from django.db import Models class Partner(models.Model): # this model contains common data for companies and persons code = models.CharField() name = models.CharField() class Person(Partner): # some person-specific data ssn = models.CharField() class Company(Partner): # some company-specific data tax_no = models.CharField() How can I convert a Company instance to a Person one, and vice-versa? Let's say someone mistakenly created a Company instance with person's details: company = Company(name="John Smith", tax_no="<some-ssn-#>") I want to convert all wrong Company objects (that were meant to be Persons) to Person objects, keeping all related records (I have models with FKs to the Partner model, so it's important to keep the same partner_ptr value). I can do something like this: person = Person(name=company.name, ssn=company.tax_no, partner_ptr=company.partner_ptr) So far so good, but is it possible to delete the Company objects that are not needed anymore? Deleting the Company object will also delete it's parent Partner object (and any related to the partner, including the newly created Person object). Any recommendations? Thanks! P.S.: This is an already deployed system, with lots of data in it and it is not possible to redesign the whole Partner-Person-Company inheritance concept.
[ "One way to go about this would be to first add a dummy Partner per each company awaiting deletion. After that you can update the partner_ptr of all unwanted Company instances to the appropriate dummy partner instance. Finally you can delete all the companies. \nOf course you can use South to help do this.\nUpdate ...
[ 4 ]
[]
[]
[ "django", "multiple_inheritance", "python" ]
stackoverflow_0003711191_django_multiple_inheritance_python.txt
Q: Django and query string parameters Assuming I have a 'get_item' view, how do I write the URL pattern for the following php style of URL? http://example.com/get_item/?id=2&type=foo&color=bar (I am not using the standard 'nice' type of URL ie: http://example.com/get_item/2/foo/bar as it is not practical) Specifically, how do I make the view respond when the user types the above in a browser, and how do I collect the parameters and use it in my view? I tried to at least get the id part right but to no avail. The view won't run when I type this in my browser http://example.com/get_item?id=2 My url pattern: (r'^get_item/id(?P<id>\d+)$', get_item) My view: def get_item(request): id = request.GET.get('id', None) xxxxxx In short, how do I implement Php's style of url pattern with query string parameters in django? A: Make your pattern like this: (r'^get_item/$', get_item) And in your view: def get_item(request): id = int(request.GET.get('id')) type = request.GET.get('type', 'default') Django processes the query string automatically and makes its parameter/value pairs available to the view. No configuration required. The URL pattern refers to the base URL only, the query string is implicit. For normal Django style, however, you should put the id/slug in the base URL and not in the query string! Use the query parameters eg. for filtering a list view, for determining the current page etc... A: You just need to change your url pattern to: (r'^get_item/$', get_item) And your view code will work. In Django the url pattern matching is used for the actual path not the querystring.
Django and query string parameters
Assuming I have a 'get_item' view, how do I write the URL pattern for the following php style of URL? http://example.com/get_item/?id=2&type=foo&color=bar (I am not using the standard 'nice' type of URL ie: http://example.com/get_item/2/foo/bar as it is not practical) Specifically, how do I make the view respond when the user types the above in a browser, and how do I collect the parameters and use it in my view? I tried to at least get the id part right but to no avail. The view won't run when I type this in my browser http://example.com/get_item?id=2 My url pattern: (r'^get_item/id(?P<id>\d+)$', get_item) My view: def get_item(request): id = request.GET.get('id', None) xxxxxx In short, how do I implement Php's style of url pattern with query string parameters in django?
[ "Make your pattern like this:\n(r'^get_item/$', get_item)\n\nAnd in your view:\ndef get_item(request):\n id = int(request.GET.get('id'))\n type = request.GET.get('type', 'default')\n\nDjango processes the query string automatically and makes its parameter/value pairs available to the view. No configuration re...
[ 70, 22 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003711349_django_python.txt
Q: MediaWiki / Python authentication integration advice needed I'm trying to integrate my MediaWiki site with some custom Python web applications. I have complete control over the MediaWiki server and am free to change the authentication plugin if needed. For the time being, I would like all users to login via a screen on the MediaWiki page (or at least they should believe they are, the whole process should be transparent to them). In general, I would prefer not to completely write my own authentication code, but I don't mind doing some minor adapting. I'm looking for some advice from people who have done something like this before, my questions are: I know absolutely nothing about LDAP, but it seems rather commonly supported with various plugins for MediaWiki and Python. Is it best to have a central LDAP server, and then force all applications to authenticate here? As compared to the above, what are the downsides of just reading from the wiki database, and comparing to see if the shared-secret from the user's cookie match, and then assuming they are logged in? Is it advisable to use openID for a situation like this? What are some of the downsides? A: This might seem obvious but have you seen the LDAP Authentication extension? We used it (with some modifications) and it works well. You can also use in combination with e.g. Lockdown. So my (limited) answers to your questions are: Yes (I can't think why you would not want it in one place). One downside is if users move groups / authentication. They need manually to delete their cookies, which can cause headaches for people supporting the wiki. Sorry, don't know that one. Hope this limited answer helps.
MediaWiki / Python authentication integration advice needed
I'm trying to integrate my MediaWiki site with some custom Python web applications. I have complete control over the MediaWiki server and am free to change the authentication plugin if needed. For the time being, I would like all users to login via a screen on the MediaWiki page (or at least they should believe they are, the whole process should be transparent to them). In general, I would prefer not to completely write my own authentication code, but I don't mind doing some minor adapting. I'm looking for some advice from people who have done something like this before, my questions are: I know absolutely nothing about LDAP, but it seems rather commonly supported with various plugins for MediaWiki and Python. Is it best to have a central LDAP server, and then force all applications to authenticate here? As compared to the above, what are the downsides of just reading from the wiki database, and comparing to see if the shared-secret from the user's cookie match, and then assuming they are logged in? Is it advisable to use openID for a situation like this? What are some of the downsides?
[ "This might seem obvious but have you seen the LDAP Authentication extension? We used it (with some modifications) and it works well.\nYou can also use in combination with e.g. Lockdown.\nSo my (limited) answers to your questions are:\n\nYes (I can't think why you would not want it in one place).\nOne downside is i...
[ 1 ]
[]
[]
[ "mediawiki", "python" ]
stackoverflow_0003712083_mediawiki_python.txt
Q: Can I prevent modifying an object in Python? I want to control global variables (or globally scoped variables) in a way that they are set only once in program initialization code, and lock them after that. I use UPPER_CASE_VARIABLES for global variables, but I want to have a sure way not to change the variable anyway. Does python provide that (or similar) feature? How do you control the globally scoped variables? A: ActiveState has a recipe titled Cᴏɴsᴛᴀɴᴛs ɪɴ Pʏᴛʜᴏɴ by the venerable Alex Martelli for creating a const module with attributes which cannot be rebound after creation. That sounds like what you're looking for except for the upcasing — but that could be added by making it check to see whether the attribute name was all uppercase or not. Of course, this can be circumvented by the determined, but that's the way Python is — and is considered to be a "good thing" by most folks. However, to make it a little more difficult, I suggest you don't bother adding the supposedly obvious __delattr__ method since people could then just delete names and then add them back rebound to different values. This is what I'm taking about: Put in const.py: # from http://code.activestate.com/recipes/65207-constants-in-python class _const: class ConstError(TypeError): pass # Base exception class. class ConstCaseError(ConstError): pass def __setattr__(self, name, value): if name in self.__dict__: raise self.ConstError("Can't change const.%s" % name) if not name.isupper(): raise self.ConstCaseError('const name %r is not all uppercase' % name) self.__dict__[name] = value # Replace module entry in sys.modules[__name__] with instance of _const # (and create additional reference to it to prevent its deletion -- see # https://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name) import sys _ref, sys.modules[__name__] = sys.modules[__name__], _const() if __name__ == '__main__': import __main__ as const # Test this module... try: const.Answer = 42 # Not OK to create mixed-case attribute name. except const.ConstCaseError as exc: print(exc) else: # Test failed - no ConstCaseError exception generated. raise RuntimeError("Mixed-case const names should't be allowed!") try: const.ANSWER = 42 # Should be OK, all uppercase. except Exception as exc: raise RuntimeError("Defining a valid const attribute should be allowed!") else: # Test succeeded - no exception generated. print('const.ANSWER set to %d raised no exception' % const.ANSWER) try: const.ANSWER = 17 # Not OK, attempt to change defined constant. except const.ConstError as exc: print(exc) else: # Test failed - no ConstError exception generated. raise RuntimeError("Shouldn't be able to change const attribute!") Output: const name 'Answer' is not all uppercase const.ANSWER set to 42 raised no exception Can't change const.ANSWER A: Python is a very open language and does not contain a final keyword. Python gives you more freedom to do things and assumes you know how things should work. Therefore, it is assumed that people using your code will know that SOME_CONSTANT should not be assigned a value at some random point in the code. If you really do want to, you can enclose the constant inside a getter function. def getConstant() return "SOME_VALUE" A: You could wrap your global variables in an object and override the object.__setattr__ method. You can then prevent setting attributes that are already set. However, this doesn't deal with complex objects that are passed by reference. You would need to make shallow/deep copies of those objects to be absolutely sure they can't be modified. If you are using new style classes you could override object.__getattribute__(self, name) to make the copies. class State(object): def __init__(self): pass def __setattr__(self, name, value): if name not in self.__dict__: self.__dict__[name] = value ** I usually don't worry so much if someone is going to try really hard to break my code. I find overriding __setattr__ is sufficient (especially if you throw an exception) to warn whoever is playing with the code that the goal for the State is to be read only. If someone still feels the need to modify the state then whatever undefined behavior they encounter isn't my fault.
Can I prevent modifying an object in Python?
I want to control global variables (or globally scoped variables) in a way that they are set only once in program initialization code, and lock them after that. I use UPPER_CASE_VARIABLES for global variables, but I want to have a sure way not to change the variable anyway. Does python provide that (or similar) feature? How do you control the globally scoped variables?
[ "ActiveState has a recipe titled Cᴏɴsᴛᴀɴᴛs ɪɴ Pʏᴛʜᴏɴ by the venerable Alex Martelli for creating a const module with attributes which cannot be rebound after creation. That sounds like what you're looking for except for the upcasing — but that could be added by making it check to see whether the attribute name was ...
[ 19, 8, 2 ]
[]
[]
[ "global_variables", "python" ]
stackoverflow_0003711657_global_variables_python.txt
Q: MPI4Py Scatter sendbuf Argument Type? I'm having trouble with the Scatter function in the MPI4Py Python module. My assumption is that I should be able to pass it a single list for the sendbuffer. However, I'm getting a consistent error message when I do that, or indeed add the other two arguments, recvbuf and root: File "code/step3.py", line 682, in subbox_grid i = mpi_communicator.Scatter(station_range, station_data) File "Comm.pyx", line 427, in mpi4py.MPI.Comm.Scatter (src/ mpi4py_MPI.c:44993) File "message.pxi", line 321, in mpi4py.MPI._p_msg_cco.for_scatter (src/mpi4py_MPI.c:14497) File "message.pxi", line 232, in mpi4py.MPI._p_msg_cco.for_cco_send (src/mpi4py_MPI.c:13630) File "message.pxi", line 36, in mpi4py.MPI.message_simple (src/ mpi4py_MPI.c:11904) ValueError: message: expecting 2 or 3 items Here is the relevant code snipped, starting a few lines above 682 mentioned above. for station in stations #snip--do some stuff with station station_data = [] station_range = range(1,len(station)) mpi_communicator = MPI.COMM_WORLD i = mpi_communicator.Scatter(station_range, nsm) #snip--do some stuff with station[i] nsm = combine(avg, wt, dnew, nf1, nl1, wti[i], wtm, station[i].id) station_data = mpi_communicator.Gather(station_range, nsm) I've tried a number of combinations initializing station_range, but I must not be understanding the Scatter argument types properly. Does a Python/MPI guru have a clarification this? A: If you want to move raw buffers (as with Gather), you provide a triplet [buffer, size, type]. Look at the demos for examples of this. If you want to send Python objects, you should use the higher level interface and call gather (note the lowercase) which uses pickle internally.
MPI4Py Scatter sendbuf Argument Type?
I'm having trouble with the Scatter function in the MPI4Py Python module. My assumption is that I should be able to pass it a single list for the sendbuffer. However, I'm getting a consistent error message when I do that, or indeed add the other two arguments, recvbuf and root: File "code/step3.py", line 682, in subbox_grid i = mpi_communicator.Scatter(station_range, station_data) File "Comm.pyx", line 427, in mpi4py.MPI.Comm.Scatter (src/ mpi4py_MPI.c:44993) File "message.pxi", line 321, in mpi4py.MPI._p_msg_cco.for_scatter (src/mpi4py_MPI.c:14497) File "message.pxi", line 232, in mpi4py.MPI._p_msg_cco.for_cco_send (src/mpi4py_MPI.c:13630) File "message.pxi", line 36, in mpi4py.MPI.message_simple (src/ mpi4py_MPI.c:11904) ValueError: message: expecting 2 or 3 items Here is the relevant code snipped, starting a few lines above 682 mentioned above. for station in stations #snip--do some stuff with station station_data = [] station_range = range(1,len(station)) mpi_communicator = MPI.COMM_WORLD i = mpi_communicator.Scatter(station_range, nsm) #snip--do some stuff with station[i] nsm = combine(avg, wt, dnew, nf1, nl1, wti[i], wtm, station[i].id) station_data = mpi_communicator.Gather(station_range, nsm) I've tried a number of combinations initializing station_range, but I must not be understanding the Scatter argument types properly. Does a Python/MPI guru have a clarification this?
[ "If you want to move raw buffers (as with Gather), you provide a triplet [buffer, size, type]. Look at the demos for examples of this. If you want to send Python objects, you should use the higher level interface and call gather (note the lowercase) which uses pickle internally.\n" ]
[ 6 ]
[]
[]
[ "mpi", "parallel_processing", "python" ]
stackoverflow_0000818362_mpi_parallel_processing_python.txt
Q: Google App Engine's db.UserProperty with rpxnow We have a Django project which runs on Google App Engine and used db.UserProperty in several models. We don't have an own User model. My boss would like to use RPXNow (Janrain) for authentication, but after I integrated it, the users.get_current_user() method returned None. It makes sense, because not Google authenticated me. But what should I use for db.UserProperty attributes? Is it possible to use rpxnow and still can have Google's User object as well? After this I tried to use OpenID authentication (with federated login) in my application, and it works pretty good: I still have users.get_current_user() object. As far as I know, rpxnow using openID as well, which means (for me) that is should be possible to get User objects with rpxnow. But how? Cheers, psmith A: I haven't tried it yet, but App Engine now supports Federated Login (OpenID) as an authentication mechanism. You can enable it from your dashboard. Read more here: http://code.google.com/googleapps/domain/sso/openid_reference_implementation.html Regardless of this, it is very easy -once you have integrated RPXNow- to link it to your application using the Polymodel, as follows: class InternalUser(polymodel.PolyModel): name = db.StringProperty(required=True) groups = db.ListProperty(db.Key) class GoogleUser(InternalUser): google_user = db.UserProperty(required=True) class OpenIDUser(InternalUser): unique_identifier = db.StringProperty(required=True) And then instead of using db.UserProperty you would use db.ReferenceProperty(required=True, reference_class=InternalUser). A: You can only get a User object if you're using one of the built-in authentication methods. User objects provide an interface to the Users API, which is handled by the App Engine infrastructure. If you're using your own authentication library, regardless of what protocol it uses, you will have to store user information differently.
Google App Engine's db.UserProperty with rpxnow
We have a Django project which runs on Google App Engine and used db.UserProperty in several models. We don't have an own User model. My boss would like to use RPXNow (Janrain) for authentication, but after I integrated it, the users.get_current_user() method returned None. It makes sense, because not Google authenticated me. But what should I use for db.UserProperty attributes? Is it possible to use rpxnow and still can have Google's User object as well? After this I tried to use OpenID authentication (with federated login) in my application, and it works pretty good: I still have users.get_current_user() object. As far as I know, rpxnow using openID as well, which means (for me) that is should be possible to get User objects with rpxnow. But how? Cheers, psmith
[ "I haven't tried it yet, but App Engine now supports Federated Login (OpenID) as an authentication mechanism. You can enable it from your dashboard.\nRead more here: http://code.google.com/googleapps/domain/sso/openid_reference_implementation.html\nRegardless of this, it is very easy -once you have integrated RPXNo...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python", "rpxnow" ]
stackoverflow_0003699751_google_app_engine_python_rpxnow.txt
Q: Python Regular Expression Question Say I have text 'C:\somedir\test.log' and I want to replace 'somedir' with 'somedir\logs'. So I want to go from 'C:\somedir\test.log' to 'C:\somedir\logs\test.log' How do I do this using the re library and re.sub? I've tried this so far: find = r'(C:\\somedir)\\.*?\.log' repl = r'C:\\somedir\\logs' print re.sub(find,repl,r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...') But I just get 'C:\somedir\logs' A: You should be using the os.path library to do this. Specifically, os.path.join and os.path.split. This way it will work on all operating systems and will account for edge cases. A: ikanobori is correct, but you should also not be using re for simple string substitution. r'C:\somedir\test.log'.replace('somedir', r'somedir\logs') A: You need to introduce a different grouping in order for the replace to work as you want, and then need to refer to that group with the replacement expression. See Python's re.sub documentation for another example. Try: find = r'C:\\somedir\\(.*?\.log)' repl = r'C:\\somedir\\logs\\\1' print re.sub(find,repl,r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...') This results in output: 'random text ... C:\somedir\logs\test.log more \nrandom \ntext C:\somedir\test.xls...' A: Alright, if you really want a way to do it with regular expressions, here's one: find = r'(C:\\somedir\\.*?\.log)' def repl(match): return match.groups()[0].replace('somedir', r'somedir\logs') s = r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...' print re.sub(find, repl, s)
Python Regular Expression Question
Say I have text 'C:\somedir\test.log' and I want to replace 'somedir' with 'somedir\logs'. So I want to go from 'C:\somedir\test.log' to 'C:\somedir\logs\test.log' How do I do this using the re library and re.sub? I've tried this so far: find = r'(C:\\somedir)\\.*?\.log' repl = r'C:\\somedir\\logs' print re.sub(find,repl,r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...') But I just get 'C:\somedir\logs'
[ "You should be using the os.path library to do this. Specifically, os.path.join and os.path.split.\nThis way it will work on all operating systems and will account for edge cases.\n", "ikanobori is correct, but you should also not be using re for simple string substitution.\nr'C:\\somedir\\test.log'.replace('some...
[ 4, 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003712445_python_regex.txt
Q: Convert string to tuple on Python Hello I have a tuple in string that I revive from a PostgreSQL function> I want to convert that to a tuple but it gives me an error with the real string inside the tuple an EOF error, the code it's like this. eval('(4125, <html> <body> Heloo There! <body> </html>)') , this is just an example of the HTML because the real code it's to big. I don't want to do a for because are many character so could put me very slow the system. I am open to all the ideas except the for or while. A: The problem is that the 'real' string isn't a string. '(4125, <html> <body> Heloo There! <body> </html>)' now remove the single quotes to get (4125, <html> <body> Heloo There! <body> </html>) now remove the parenthesis and the first element <html> <body> Heloo There! <body> </html> See, no string. And shame on you for using eval on a string from a database. Didn't your parents raise you better?
Convert string to tuple on Python
Hello I have a tuple in string that I revive from a PostgreSQL function> I want to convert that to a tuple but it gives me an error with the real string inside the tuple an EOF error, the code it's like this. eval('(4125, <html> <body> Heloo There! <body> </html>)') , this is just an example of the HTML because the real code it's to big. I don't want to do a for because are many character so could put me very slow the system. I am open to all the ideas except the for or while.
[ "The problem is that the 'real' string isn't a string.\n'(4125, <html>\n<body>\nHeloo There!\n<body>\n</html>)'\n\nnow remove the single quotes to get\n(4125, <html>\n<body>\nHeloo There!\n<body>\n</html>)\n\nnow remove the parenthesis and the first element\n<html>\n<body>\nHeloo There!\n<body>\n</html>\n\nSee, no ...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003712667_python.txt
Q: Use py2app with Matplotlib and its Tex formatting? Dvipng not found I have an application put together in py2app on OS X 10.6 which uses Matplotlib to generate graphs. (Using py2app version 0.5.3 and matplotlib version 0.99.3, if it matters.) I have the Tex formatting option enabled: ... from matplotlib import rc rc('text', usetex=True) ... The script works fine when executed in the command line, including the Tex formatting. The application is created with py2app: py2applet --make-setup MyApplication.py python setup.py py2app There are no errors in creating or opening the application. However, when I try to generate a plot in the application, I get the error: RuntimeError: Could not obtain dvipng version Is it because py2app is not including dvipng in the application itself? What's the best way to go about fixing this? A: By adding: OPTIONS = {'argv_emulation': True, 'packages':['matplotlib']} to my setup.py, I get this to work correctly when the application is opened from the command line. Strangely though, when opened by another means (double clicking in the applications folder, for example) I have the same problems I started with. Still looking for a full fix.
Use py2app with Matplotlib and its Tex formatting? Dvipng not found
I have an application put together in py2app on OS X 10.6 which uses Matplotlib to generate graphs. (Using py2app version 0.5.3 and matplotlib version 0.99.3, if it matters.) I have the Tex formatting option enabled: ... from matplotlib import rc rc('text', usetex=True) ... The script works fine when executed in the command line, including the Tex formatting. The application is created with py2app: py2applet --make-setup MyApplication.py python setup.py py2app There are no errors in creating or opening the application. However, when I try to generate a plot in the application, I get the error: RuntimeError: Could not obtain dvipng version Is it because py2app is not including dvipng in the application itself? What's the best way to go about fixing this?
[ "By adding:\nOPTIONS = {'argv_emulation': True, 'packages':['matplotlib']}\n\nto my setup.py, I get this to work correctly when the application is opened from the command line. Strangely though, when opened by another means (double clicking in the applications folder, for example) I have the same problems I started...
[ 1 ]
[]
[]
[ "latex", "matplotlib", "py2app", "python" ]
stackoverflow_0003704627_latex_matplotlib_py2app_python.txt
Q: Does Python have a method that returns all the attributes in a module? I already search for it on Google but I didn't have luck. A: in addition to the dir builtin that has been mentioned, there is the inspect module which has a really nice getmembers method. Combined with pprint.pprint you have a powerful combo from pprint import pprint from inspect import getmembers import linecache pprint(getmembers(linecache)) some sample output: ('__file__', '/usr/lib/python2.6/linecache.pyc'), ('__name__', 'linecache'), ('__package__', None), ('cache', {}), ('checkcache', <function checkcache at 0xb77a7294>), ('clearcache', <function clearcache at 0xb77a7224>), ('getline', <function getline at 0xb77a71ec>), ('getlines', <function getlines at 0xb77a725c>), ('os', <module 'os' from '/usr/lib/python2.6/os.pyc'>), ('sys', <module 'sys' (built-in)>), ('updatecache', <function updatecache at 0xb77a72cc>) note that unlike dir you get to see that actual values of the members. You can apply filters to getmembers that are similar to the onese that you can apply to dir, they can just be more powerful. For example, def get_with_attribute(mod, attribute, public=True): items = getmembers(mod) if public: items = filter(lambda item: item[0].startswith('_'), items) return [attr for attr, value in items if hasattr(value, attribute] A: import module dir(module) A: You're looking for dir: import os dir(os) ??dir dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes. A: As it has been correctly pointed out, the dir function will return a list with all the available methods in a given object. If you call dir() from the command prompt, it will respond with the methods available upon start. If you call: import module print dir(module) it will print a list with all the available methods in module module. Most times you are interested only in public methods (those that you are supposed to be using) - by convention, Python private methods and variables start with __, so what I do is the following: import module for method in dir(module): if not method.startswith('_'): print method That way you only print public methods (to be sure - the _ is only a convention and many module authors may fail to follow the convention) A: dir is what you need :)
Does Python have a method that returns all the attributes in a module?
I already search for it on Google but I didn't have luck.
[ "in addition to the dir builtin that has been mentioned, there is the inspect module which has a really nice getmembers method. Combined with pprint.pprint you have a powerful combo\nfrom pprint import pprint\nfrom inspect import getmembers\nimport linecache\n\npprint(getmembers(linecache))\n\nsome sample output:\n...
[ 8, 4, 0, 0, 0 ]
[]
[]
[ "attributes", "module", "python", "return" ]
stackoverflow_0003712885_attributes_module_python_return.txt
Q: thread Locking/unlocking in constructor/destructor in python I have a class that is only ever accessed externally through static methods. Those static methods then create an object of the class to use within the method, then they return and the object is presumably destroyed. The class is a getter/setter for a couple config files and now I need to place thread locks on the access to the config files. Since I have several different static methods that all need read/write access to the config files that all create objects in the scope of the method, I was thinking of having my lock acquires done inside of the object constructor, and then releasing in the destructor. My coworker expressed concern that it seems like that could potentially leave the class locked forever if something happened. And he also mentioned something about how the destructor in python was called in regards to the garbage collector, but we're both relatively new to python so that's an unknown. Is this a reasonable solution or should I just lock/unlock in each of the methods themselves? Class A(): rateLock = threading.RLock() chargeLock = threading.RLock() @staticmethod def doZStuff(): a = A() a.doStuff('Z') @staticmethod def doYStuff(): a = A() a.doStuff('Y') @synchronized(lock) def doStuff(self, type): if type == 'Z': otherstuff() elif type == 'B': evenmorestuff() Is it even possible to get it to work that way with the decorator on doStuff() instead of doZStuff() Update Thanks for the answers everyone. The problem I'm facing is mostly due to the fact that it doesn't really make sense to access my module asynchronously, but this is just part of an API. And the team accessing our stuff through the API was complaining about concurrency issues. So I don't need the perfect solution, I'm just trying to make it so they can't crash our side or get garbage data back A: Class A(): rateLock = threading.RLock() chargeLock = threading.RLock() def doStuff(self,ratefile,chargefile): with A.rateLock: with open(ratefile) as f: # ... with A.chargeLock: with open(chargefile) as f: # ... Using the with statement will guarantee that the (R)Lock is acquired and released in pairs. The release will be called even if there an exception occurs within the with-block. You might also want to think about placing your locks around the file access block with open(...) as ... as tightly as you can so that the locks are not held longer than necessary. Finally, the creation and garbage collection of a=A() will not affect the locks if (as above) the locks are class attributes (as opposed to instance attributes). The class attributes live in A.__dict__, rather than a.__dict__. So the locks will not be garbage collected until A itself is garbage collected. A: You are right with the garbage collection, so it is not a good idea. Look into decorators, for writing synchronized functions. Example: http://code.activestate.com/recipes/465057-basic-synchronization-decorator/ edit I'm still not 100% sure what you have in mind, so my suggestion may be wrong: class A(): lockZ = threading.RLock() lockY = threading.RLock() @staticmethod @synchroized(lockZ) def doZStuff(): a = A() a.doStuff('Z') @staticmethod @synchroized(lockY) def doYStuff(): a = A() a.doStuff('Y') def doStuff(self, type): if type == 'Z': otherstuff() elif type == 'B': evenmorestuff() A: However, if you HAVE TO acquire and release locks in constructors and destructors, then you really, really, really should give your design another chance. You should change your basic assumptions. In any application: a "LOCK" should always be held for a short time only - as short as possible. That means - in probably 90% of all cases, you will acquire the lock in the same method that will also release the lock. There should hardly be NEVER EVER a reason to lock/unlock an object in a RAII style. This is not what it was meant to become ;) Let me give you an ekxample: you manage some ressources, those res. can be read from many threads at once but only one thread can write to them. In a "naive" implementation you would have one lock per object, and whenever someone wants to write to it, then you will LOCK it. When multiple threads want to write to it, then you have it synchronyzed fairly, all safe and well, BUT: When thread says "WRITE", then we will stall, until the other threads decide to release the lock. But please understand that locks, mutex - all these primitives were created to synchronize only a few lines of your source code. So, instead of making the lock part of you writeable object, you have only a lock for the very short time where it really is required. You have to invest more time and thoughts in your interfaces. But, LOCKS/MUTEXES were never meant to be "held" for more than a few microseconds. A: I don't know which platform you are on, but if you need to lock a file, well, you should probably use flock() if it is available instead of rolling your own locking routines. Since you've mentioned that you are new to python, I must say that most of the time threads are not the solution in python. If your activity is CPU-bound, you should consider using multiprocessing. There is no concurrent execution because of GIL, remember? (this is true for most cases). If your activity is I/O bound, which I guess is the case, you should, perhaps, consider using an event-driven framework, like Twisted. That way you won't have to worry about deadlocks at all, I promise :) A: Releasing locks in the destruction of objects is risky as has already been mentioned because of the garbage collector, because deciding when to call the __del__() method on objects is exclusively decided by the GC (usually when the refcount reaches zero) but in some cases, if you have circular references, it might never be called, even when the program exits. If you are treating one specific configfile inside a class instance, then you might put a lock object from the Threading module inside it. Some example code of this: from threading import Lock class ConfigFile: def __init__(file): self.file = file self.lock = Lock() def write(self, data): self.lock.aquire() <do stuff with file> self.lock.release() # Function that uses ConfigFile object def staticmethod(): config = ConfigFile('myconfig.conf') config.write('some data') You can also use locks in a With statement, like: def write(self, data): with self.lock: <do stuff with file> And Python will aquire and release the lock for you, even in case of errors that happens while doing stuff with the file.
thread Locking/unlocking in constructor/destructor in python
I have a class that is only ever accessed externally through static methods. Those static methods then create an object of the class to use within the method, then they return and the object is presumably destroyed. The class is a getter/setter for a couple config files and now I need to place thread locks on the access to the config files. Since I have several different static methods that all need read/write access to the config files that all create objects in the scope of the method, I was thinking of having my lock acquires done inside of the object constructor, and then releasing in the destructor. My coworker expressed concern that it seems like that could potentially leave the class locked forever if something happened. And he also mentioned something about how the destructor in python was called in regards to the garbage collector, but we're both relatively new to python so that's an unknown. Is this a reasonable solution or should I just lock/unlock in each of the methods themselves? Class A(): rateLock = threading.RLock() chargeLock = threading.RLock() @staticmethod def doZStuff(): a = A() a.doStuff('Z') @staticmethod def doYStuff(): a = A() a.doStuff('Y') @synchronized(lock) def doStuff(self, type): if type == 'Z': otherstuff() elif type == 'B': evenmorestuff() Is it even possible to get it to work that way with the decorator on doStuff() instead of doZStuff() Update Thanks for the answers everyone. The problem I'm facing is mostly due to the fact that it doesn't really make sense to access my module asynchronously, but this is just part of an API. And the team accessing our stuff through the API was complaining about concurrency issues. So I don't need the perfect solution, I'm just trying to make it so they can't crash our side or get garbage data back
[ "Class A():\n rateLock = threading.RLock()\n chargeLock = threading.RLock()\n\n def doStuff(self,ratefile,chargefile):\n with A.rateLock:\n with open(ratefile) as f:\n # ...\n with A.chargeLock:\n with open(chargefile) as f:\n # ...\n\nUsing...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "locking", "multithreading", "python" ]
stackoverflow_0003712388_locking_multithreading_python.txt
Q: How to match all .sass request to a particular controller in pylons? I'm using pylons, and want to use clever css. I created a controller SassController to handle .sass requests, but in the config/routing.py, I don't know how to write the mapping. What I want is: client request: http://localhost:5000/stylesheets/questions/index.sass all such requests will be handled by SassController#index I tried: map.connect('/{path:.*}.sass', controller='sass', action='index') But found only: http://localhost:5000/xxx.sass will be handled, but http://localhost:5000/xxx/yyy.sass won't. What should I do now? A: The routing code using regular expressions so you can make it eat everything in the url regardless of slashes. The docs are here It'll look something like: map.connect(R'/{path:.*?}.sass', controller='SassController', action='index') #in the SassController def index(self, path): return path http://localhost:5000/blah/blah/something.sass will call SassController.index with path = blah/blah/something
How to match all .sass request to a particular controller in pylons?
I'm using pylons, and want to use clever css. I created a controller SassController to handle .sass requests, but in the config/routing.py, I don't know how to write the mapping. What I want is: client request: http://localhost:5000/stylesheets/questions/index.sass all such requests will be handled by SassController#index I tried: map.connect('/{path:.*}.sass', controller='sass', action='index') But found only: http://localhost:5000/xxx.sass will be handled, but http://localhost:5000/xxx/yyy.sass won't. What should I do now?
[ "The routing code using regular expressions so you can make it eat everything in the url regardless of slashes.\nThe docs are here\nIt'll look something like:\nmap.connect(R'/{path:.*?}.sass', controller='SassController', action='index') \n\n#in the SassController\ndef index(self, path):\n return path\n\nhttp://...
[ 0 ]
[]
[]
[ "pylons", "python", "routing", "sass" ]
stackoverflow_0003554936_pylons_python_routing_sass.txt
Q: Python, Django, using Import from inside of a class, can't seem to figure this out I want to use imports inside a class that is then inherited by another class so that I don't have to manually define my imports in each file. I am trying it like this but its not working, any advice is appreciated: class Djangoimports (): def __init__(self): from django.template import Context print Context class Init1 (Djangoimports): def __init__(self): Djangoimports.__init__(self) self.c = Context(self.constructor_dict) # just example of trying to use the imported "Context" >>>>> global name 'Context' is not defined I have tried variations of trying to use "self" but can't figure out how to appropriately use this with the import from as its not the same as a class attribute / method where I normally use 'self' A: This works fine for me. But you're better off doing this: >>> class Test(object): ... from functools import partial ... >>> Test().partial <type 'functools.partial'> Note that doing it your way, you have to initialize them on a per instance basis and assign to self, like so: def Test(object): def __init__(self): from functools import partial self.partial = partial either way, you can now access bar in other methods on that class or a derived one as self.bar. A: In Python, an import just adds to current namespace. The namespace is lost once you return from the function, but you can preserve the pointer appending it to 'self'. You can do: class Djangoimports (): def __init__(self): from django.template import Context self.Context = Context class Init1 (Djangoimports): def __init__(self): Djangoimports.__init__(self) self.c = self.Context(self.constructor_dict)
Python, Django, using Import from inside of a class, can't seem to figure this out
I want to use imports inside a class that is then inherited by another class so that I don't have to manually define my imports in each file. I am trying it like this but its not working, any advice is appreciated: class Djangoimports (): def __init__(self): from django.template import Context print Context class Init1 (Djangoimports): def __init__(self): Djangoimports.__init__(self) self.c = Context(self.constructor_dict) # just example of trying to use the imported "Context" >>>>> global name 'Context' is not defined I have tried variations of trying to use "self" but can't figure out how to appropriately use this with the import from as its not the same as a class attribute / method where I normally use 'self'
[ "This works fine for me.\nBut you're better off doing this:\n>>> class Test(object):\n... from functools import partial\n... \n>>> Test().partial\n<type 'functools.partial'>\n\nNote that doing it your way, you have to initialize them on a per instance basis and assign to self, like so:\ndef Test(object):\n ...
[ 5, 1 ]
[]
[]
[ "class", "django", "import", "python" ]
stackoverflow_0003713352_class_django_import_python.txt
Q: Python Image Directories Using PIL in python one must put the full directory for an image, so that the program runs properly. Is there any way to make that directory variable? So that it gets the programs current directory then looks for the images in that same folder? This is in Windows 7 BTW. A: You are looking for: os.getcwd
Python Image Directories
Using PIL in python one must put the full directory for an image, so that the program runs properly. Is there any way to make that directory variable? So that it gets the programs current directory then looks for the images in that same folder? This is in Windows 7 BTW.
[ "You are looking for: os.getcwd\n" ]
[ 1 ]
[]
[]
[ "python", "python_imaging_library", "windows_7" ]
stackoverflow_0003713443_python_python_imaging_library_windows_7.txt
Q: how do i generate a valid upc? does anyone know if it is possible to generate a valid upc? if so, how? is it possible to do it in excel / python / .net? the platform does not matter to me A: This should help: http://en.wikipedia.org/wiki/Universal_Product_Code It explains what all the digits are for (including the check digit). A: How about this? http://www.codeproject.com/KB/graphics/upc_a_barcode.aspx
how do i generate a valid upc?
does anyone know if it is possible to generate a valid upc? if so, how? is it possible to do it in excel / python / .net? the platform does not matter to me
[ "This should help: http://en.wikipedia.org/wiki/Universal_Product_Code\nIt explains what all the digits are for (including the check digit).\n", "How about this? http://www.codeproject.com/KB/graphics/upc_a_barcode.aspx\n" ]
[ 2, 1 ]
[]
[]
[ ".net", "barcode", "excel", "python" ]
stackoverflow_0003713529_.net_barcode_excel_python.txt
Q: Putting images in a Tkinter How can I place an image in a Tkinter GUI using the python standard library? A: I don't normally use Tkinter, but I'll take a shot at answering. According to Google, loading images in Tkinter has two main gotchas: It only accepts GIFs. (Example code for using PIL to convert to GIF while loading) You have to manually keep a reference to images due to an inability to refcount them. (solution) (explanation) The example code for loading non-GIF images should also work perfectly well as an example of the basic procedure for displaying images in Tkinter GUIs. If you'd prefer a more practical example, PySol is a suite of solitaire games written with Tkinter and PySolFC, its successor, demonstrates the same usage adapted to the new python-ttk Tkinter API which Python 2.7 added. A: You can Built-In the images on the code encoding it on Base64
Putting images in a Tkinter
How can I place an image in a Tkinter GUI using the python standard library?
[ "I don't normally use Tkinter, but I'll take a shot at answering. According to Google, loading images in Tkinter has two main gotchas:\n\nIt only accepts GIFs. (Example code for using PIL to convert to GIF while loading)\nYou have to manually keep a reference to images due to an inability to refcount them. (solutio...
[ 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003698900_python_tkinter.txt
Q: Django querysets - make sure results are retrieved only once I've got a simple function to get some additional data based on request.user: def getIsland(request): try: island = Island.objects.get(user=request.user) # Retrieve except Island.DoesNotExist: island = Island(user=request.user) # Doesn't exist, create default one island.save() island.update() # Run scheduled tasks return island # Return The problem is that the function gets called in many different places (middleware, templates, views ETC) and thus executes the query many times. Any way to help that? ie def getIsland(request): if HasBeenEvaluatedAlreadyOnThisRequest: return cached else: [...] A: Have you tried about using cache? Django has a wonderful cache system: http://docs.djangoproject.com/en/dev/topics/cache/ This would make your function look something like so: def getIsland(request): island = cache.get("island_"+request.user) if island == None: try: island = Island.objects.get(user=request.user) # Retrieve except Island.DoesNotExist: island = Island(user=request.user) # Doesn't exist, create default one island.save() island.update() # Run scheduled tasks cache.set("island_"+request.user, island, 60) return island # Return You will likely need to do some serialisation and deserialisation when caching stuff, but that's the general gist of it. The benefit is that the result of your query is now stored in RAM for x seconds and it doesn't matter which specific process accesses it. It's always there. Available for everyone. A: Quick and dirty: def getIsland(request): if hasattr(request, "_cached_island"): return request._cached_island try: island = Island.objects.get(user=request.user) # Retrieve except Island.DoesNotExist: island = Island(user=request.user) # Doesn't exist, create default one island.save() island.update() # Run scheduled tasks request._cached_island = island return island # Return A: If you have multiple processes running or multiple computers hitting the same database, then of course there is no way for you to reduce the number of queries running this. One thing you can try doing is using a threadlocal storage to hold a global "cache" of users. As an example: class UserStorage(threading.local): store = {} def getIsland(self, request): user_id = request.user.pk island = store.get(user_id) if island is None: island, created = Island.objects.get_or_create(user = user_id) store[user_id] = island island.update() return island However, you may notice that the Island object WILL NEVER BE UPDATED. Therefore, you must proceed with extreme caution. You may need to have a global timeout for this object, but then you are implementing your own cache solution, so why not use django's cache system with memcached or their threadlocal cache?
Django querysets - make sure results are retrieved only once
I've got a simple function to get some additional data based on request.user: def getIsland(request): try: island = Island.objects.get(user=request.user) # Retrieve except Island.DoesNotExist: island = Island(user=request.user) # Doesn't exist, create default one island.save() island.update() # Run scheduled tasks return island # Return The problem is that the function gets called in many different places (middleware, templates, views ETC) and thus executes the query many times. Any way to help that? ie def getIsland(request): if HasBeenEvaluatedAlreadyOnThisRequest: return cached else: [...]
[ "Have you tried about using cache?\nDjango has a wonderful cache system: http://docs.djangoproject.com/en/dev/topics/cache/\nThis would make your function look something like so:\ndef getIsland(request):\n island = cache.get(\"island_\"+request.user)\n if island == None:\n try:\n island = Island.objects.get(us...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003712697_django_python.txt
Q: How do I assign a numerical value to each uppercase Letter? How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values. EG. A = 1, B = 2, C = 3 (etc..) string = 'ABC' Then return the answer 6 (in this case). A: base = ord('A') - 1 mystring = 'ABC' print sum(ord(char) - base for char in mystring) A: You can use ord to get the ascii code, then subtract 64. def codevalue(char): return ord(char) - 64 A: import string letter_to_numeral = dict(zip(string.uppercase, range(1, len(string.uppercase) + 1) )) print letter_to_numeral >>> {'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26} def score_string(s): return sum([letter_to_numeral[character] for character in s]) score_string('ABC') >>> 6 A: Enumerate can do the numbering for you: import string numerology_table = dict((ch,num+1) for (num,ch) in enumerate(string.ascii_letters[:26].upper())) or even better, you can have enumerate start at 1 instead of the default of 0: numerology_table = dict((ch,num) for (num,ch) in enumerate(string.ascii_letters[:26].upper(), start=1)) A: def getvalue(mystring): letterdict = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(1,27))) return sum(letterdict[c] for c in mystring) A: If you are using Python3: result = 0 mystring = 'ABC' for char in mystring.encode('ascii'): result += char - 64 >>> result 6 A: Golfy answer certain to annoy your professor: >>> s = 'ABC' >>> sum(map(ord,s),-64*len(s)) 6 A: The most sensible answer is of course using ord as shown earlier. But for those who chose to construct a dictionary, I would rather just use the index in the string: >>> import string >>> mystring = 'ABC' >>> sum(string.uppercase.index(c) + 1 for c in mystring) 6 A: After you define the variables you can just return the answer or print the answer A = 1 B = 2 C = 3 total = A + B + C print (total) return total
How do I assign a numerical value to each uppercase Letter?
How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values. EG. A = 1, B = 2, C = 3 (etc..) string = 'ABC' Then return the answer 6 (in this case).
[ "base = ord('A') - 1\nmystring = 'ABC'\nprint sum(ord(char) - base for char in mystring)\n\n", "You can use ord to get the ascii code, then subtract 64.\ndef codevalue(char):\n return ord(char) - 64\n\n", "import string\n\nletter_to_numeral = dict(zip(string.uppercase, range(1, len(string.uppercase) + 1) ))\...
[ 11, 6, 4, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003711303_python_string.txt