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...
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 tr...
[ "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...
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"...
[ "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. ...
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 Syste...
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/...
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,*/...
[ "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 th...
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 templ...
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' ...
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, ...
[ "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 cl...
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 ...
[ "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 d...
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...
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...
[ "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 eleme...
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 elem...
[ "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 >>>...
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...
[ "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 mem...
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 p...
[ "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 libra...
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 librar...
[ "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, un...
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...
[ "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...
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: ...
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:\Docume...
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"...
[ "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... How...
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...
[ "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...
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 ...
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}", ...
[ "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? A...
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 i...
[ "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._...
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 shou...
[ "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...
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.imag...
[ "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...
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,...
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], ...
[ "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...
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...
[ "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...
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 ...
[ "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 onl...
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() ...
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...
[ "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.con...
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)....
[ "\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 PH...
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 gener...
[ "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) ...
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 ov...
[ "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 ?...
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__(se...
[ "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 "be...
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 M...
[ "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 tes...
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: objc...
[ "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....
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, u...
[ "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.Mod...
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.Cha...
[ "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...
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...
[ "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...
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, Ge...
[ "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 p...
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 firs...
[ "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): retu...
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', FakeF...
[ "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 c...
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 ...
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 ...
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 lin...
[ "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 ...
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, bu...
[ "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 (BeautifulSou...
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 lo...
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......
[ "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 ....
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 b...
[ "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 m...
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 py2...
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 : h...
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 entri...
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 ...
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 w...
[ "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...
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 re...
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(...
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 fr...
[ "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 extra...
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 e...
[ "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 ...
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-...
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 ...
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...
[ "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 Relate...
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 definiti...
[ "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 th...
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...
[ "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...
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 t...
[ "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 t...
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 ti...
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...
[ "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 invo...
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 cl...
[ "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 AB...
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 ca...
[ ">>> 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 = ses...
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 = sessio...
[ "__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 (her...
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 ...
[ "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 ho...
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 t...
[ "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 ...
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...
[ "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, ...
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',...
[ "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 usi...
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=[...
[ "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 Ch...
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...
[ "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...
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 xuniqueCombinatio...
[ "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 nam...
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,...
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 ha...
[ "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 pr...
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 ...
[ "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): # s...
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.CharF...
[ "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) Specifical...
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 ...
[ "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 scre...
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 ar...
[ "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 an...
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) feat...
[ "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 roo...
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 sub...
[ "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 returne...
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 authentica...
[ "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...
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,re...
[ "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 ju...
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 r...
[ "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 ...
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 c...
[ "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 ...
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 cou...
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 acces...
[ "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/...
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#i...
[ "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 Djangoimpor...
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...
[ "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 looki...
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 t...
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 w...
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, cre...
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 t...
[ "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' p...
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