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: Mongodb-engine and Django create custom ObjectId Is it possible to create a custom ObjectId in a django model that is being saved to a mongodb using mongodb-engine? I've tried to do this passing the string I want into the ObjectId type, Flight(_id=ObjectId(myid)) for example but then this gives me an error saying ...
Mongodb-engine and Django create custom ObjectId
Is it possible to create a custom ObjectId in a django model that is being saved to a mongodb using mongodb-engine? I've tried to do this passing the string I want into the ObjectId type, Flight(_id=ObjectId(myid)) for example but then this gives me an error saying that the string is not a valid id. Is it possible to o...
[ "For sure you can your custom objectId, check objectId documentation for that , but i don't unsdestand fot what you need it. \nInstead of ObjectId you can use any type that you want. So you can make _id string and insert any strting value instead of mongo ObjectId. But your custom _id must be unique for each member...
[ 0 ]
[]
[]
[ "django", "mongodb", "python" ]
stackoverflow_0005028665_django_mongodb_python.txt
Q: Return from inheritance How I update x.test to have values return from inheritance ? So I want x.test return ['test from B'', 'test from C'] class A() def __init__(self) self.test = [] return def coolThings(self): # do cool things here and print the new self.test pr...
Return from inheritance
How I update x.test to have values return from inheritance ? So I want x.test return ['test from B'', 'test from C'] class A() def __init__(self) self.test = [] return def coolThings(self): # do cool things here and print the new self.test print self.test class B(A) ...
[ "Inheritance creates relationships between classes, not objects. In your example the classes (A, B and C) are related, but the objects (x, y and z) are not.\nTell us what you're trying to do, and we should be able to help you come up with a good way to do it.\n", "There are two issues here: inheritance, and stati...
[ 2, 1, 0, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0005029401_inheritance_python.txt
Q: Django Data Migration, using South with Inheritance We are migrating the data in several instances of our Django project to a new schema. The old schema had: class Group(models.Model) class User(models.Model) And the new schema has: class AccessEntity(models.Model) class Group(AccessEntity) class User(AccessEnt...
Django Data Migration, using South with Inheritance
We are migrating the data in several instances of our Django project to a new schema. The old schema had: class Group(models.Model) class User(models.Model) And the new schema has: class AccessEntity(models.Model) class Group(AccessEntity) class User(AccessEntity) We are trying to use South to do a data migration f...
[ "not sure if I understand your question correctly, but the way multi-table model inheritance works ist that there will be an implicit one-to-one field in the parent and child models. So both User and Group would use an ID field of AccessEntity if AccessEntity has such a field. \nIf you create AccessEntity such that...
[ 2 ]
[]
[]
[ "database_migration", "django", "django_models", "django_south", "python" ]
stackoverflow_0005028180_database_migration_django_django_models_django_south_python.txt
Q: What's the best way to optimise the fixture-loading part of Django tests? my Django tests run really slowly, but it's not the test's fault. At the moment, the whole process takes 14s, but only 0.1s of that is running tests. The first few seconds are creating tables & indexes, the rest is applying the project's man...
What's the best way to optimise the fixture-loading part of Django tests?
my Django tests run really slowly, but it's not the test's fault. At the moment, the whole process takes 14s, but only 0.1s of that is running tests. The first few seconds are creating tables & indexes, the rest is applying the project's many fixtures. What's the best way to deal with this? I think there is a way of sp...
[ "You may use sqlite in-memory database for tests - it really fast\n", "\n\"but I need most of them to do most tests\"... \n\nSorry about this, but to speed things up you're going to have to do some thinking. \n\n\"I think there is a way of specifying which fixtures to load in each test\" \n\nThis is a disturbing...
[ 4, 4 ]
[]
[]
[ "django", "fixtures", "performance", "python", "testing" ]
stackoverflow_0005029415_django_fixtures_performance_python_testing.txt
Q: Joining concurrent Python Output I'm using something like this: find folder/ | xargs -n1 -P10 ./logger.py > collab Inside logger.py I am processing the files out outputting reformatted lines. So collab should look like {'filename' : 'file1', 'size' : 1000} {'filename' : 'file1', 'size' : 1000} {'filename' : 'file...
Joining concurrent Python Output
I'm using something like this: find folder/ | xargs -n1 -P10 ./logger.py > collab Inside logger.py I am processing the files out outputting reformatted lines. So collab should look like {'filename' : 'file1', 'size' : 1000} {'filename' : 'file1', 'size' : 1000} {'filename' : 'file1', 'size' : 1000} {'filename' : 'file...
[ "In general, there are issues that make it very hard to guarantee this won't happen, without delving into multi-process locking. However, you can usually reduce the problem a lot.\nThe most common cause of this is I/O buffering, within Python or libc. For example, it may be buffering 16k of output, and then writi...
[ 2, 1, 1 ]
[]
[]
[ "bash", "python", "xargs" ]
stackoverflow_0005022071_bash_python_xargs.txt
Q: Print a binary tree, python, in inorder Me and my friend are doing some school work with programming in Python 3.1 and are VERY stuck. We're programming a binary tree and it's working fine except when we want to print all the nodes in inorder in a way that would create a sentence (all the words in inorder just aft...
Print a binary tree, python, in inorder
Me and my friend are doing some school work with programming in Python 3.1 and are VERY stuck. We're programming a binary tree and it's working fine except when we want to print all the nodes in inorder in a way that would create a sentence (all the words in inorder just after one another in a row). We have been lookin...
[ "To print a binary tree, if you are printing a leaf you just print the value; otherwise, you print the left child then the right child.\ndef print_tree(tree):\n if tree:\n print tree.value\n print_tree(tree.left)\n print_tree(tree.right)\n\n", "print(tree.exists(\"visa\")) returns None, be...
[ 3, 1, 0, 0 ]
[]
[]
[ "binary_tree", "inorder", "printing", "python" ]
stackoverflow_0005029576_binary_tree_inorder_printing_python.txt
Q: Is there a good library for handling sieve mail filters in python? I'm currently writing a module for a customer to handle a user's sieve mail filter files. I am required to use python and much to my disappointment I could not find a nice library/package for handling sieve filters. Question is: Is there something ...
Is there a good library for handling sieve mail filters in python?
I'm currently writing a module for a customer to handle a user's sieve mail filter files. I am required to use python and much to my disappointment I could not find a nice library/package for handling sieve filters. Question is: Is there something like this?
[ "Milters is a mail filter library, not specifically Sieve. Also, here is an item on the python mailing list asking for people who want to implement RFC 3028 (Sieve language for mail filters). It's dated December 2009 and it doesn't look promising, but there are some ideas there. I think the answer to your question ...
[ 1 ]
[]
[]
[ "email", "filter", "python", "sieve_language" ]
stackoverflow_0005030186_email_filter_python_sieve_language.txt
Q: How can I embed Google maps into a wxPython program? I would like to create a program using wxPython that uses Google maps to display and select geographic data. Is there a proven, ready to use widget for this? A: There are no pre-made widgets that I'm aware of. I did find PySlip, which is similar to what you're...
How can I embed Google maps into a wxPython program?
I would like to create a program using wxPython that uses Google maps to display and select geographic data. Is there a proven, ready to use widget for this?
[ "There are no pre-made widgets that I'm aware of. I did find PySlip, which is similar to what you're talking about: http://code.google.com/p/pyslip/wiki/Introduction\nThere is a webkit port that's being worked on for wxPython as well. There's a preview build here that's kind of old:\nhttp://wxwebkit.wxcommunity.com...
[ 1 ]
[]
[]
[ "gis", "google_maps", "python", "wxpython" ]
stackoverflow_0005023434_gis_google_maps_python_wxpython.txt
Q: create subprocess object from already running process I would like to create an subprocess.Popen object from an already running process... Is that possible somehow? Another idea would be to serialize (pickle) the subprocess object and write it to a database so that if the main process restarts it could get the sub...
create subprocess object from already running process
I would like to create an subprocess.Popen object from an already running process... Is that possible somehow? Another idea would be to serialize (pickle) the subprocess object and write it to a database so that if the main process restarts it could get the subprocess.Popen objects back from the database. I'm unsure if...
[ "create an subprocess.Popen object from an already running process\nDo you mean from an already running sub-process? The only way I know of to pass objects between processes is to pickle them and write them out either to a file or a database as you suggested.\nTypically, sub-processes cannot be spawned from already...
[ 2, 2 ]
[]
[]
[ "popen", "process", "python" ]
stackoverflow_0005029880_popen_process_python.txt
Q: PHP var becoming negative I have this code : <?php $integer = 33963677451; $integer &= 0xFFFFFFFF; echo $integer; ?> But, when I execute it, the output is -396060917 The same function in Python if __name__ == '__main__': integer = 33963677451 integer &= 0xFFFFFFFF print integer The output is 389890...
PHP var becoming negative
I have this code : <?php $integer = 33963677451; $integer &= 0xFFFFFFFF; echo $integer; ?> But, when I execute it, the output is -396060917 The same function in Python if __name__ == '__main__': integer = 33963677451 integer &= 0xFFFFFFFF print integer The output is 3898906379 It seems PHP can't store ...
[ "That value is too big for an integer, python dynamically casts that into a long variable. INT_MAX defines how big your integer can be before it switches over into a double. If you want to manipulate large numbers without quirks use GMPLIB a multiple precision arithmetic library.\n", "Your 33,963,677,451 is above...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "integer", "php", "python" ]
stackoverflow_0005030190_integer_php_python.txt
Q: Is it acceptable to subclass c_void_p in ctypes? I am interfacing with a library that returns opaque pointers. Is it acceptable to subclass c_void_p to represent this in ctypes and provide for type checking for this particular flavor of c_void_p? A: An easy way to do this type checking might be to create some ar...
Is it acceptable to subclass c_void_p in ctypes?
I am interfacing with a library that returns opaque pointers. Is it acceptable to subclass c_void_p to represent this in ctypes and provide for type checking for this particular flavor of c_void_p?
[ "An easy way to do this type checking might be to create some arbitrary ctypes.Structure\nclass _Opaque(ctypes.Structure):\n pass\n\nDeclare the return type of the relevant functions to be a pointer to this structure\nlib.f.restype = ctypes.POINTER(_Opaque)\n\nand either the argument type of a function which acc...
[ 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005030730_ctypes_python.txt
Q: Manually validate a django session id is currently authenticated I need to have a function tell me if a Django session-id is currently authenticated or not. I understand this is already built into Django and I have that working just fine. But I have an external app that gets passed a session id, and when it passes...
Manually validate a django session id is currently authenticated
I need to have a function tell me if a Django session-id is currently authenticated or not. I understand this is already built into Django and I have that working just fine. But I have an external app that gets passed a session id, and when it passes the session-id string back to Django I need to validate that this ses...
[ "You can do it like this (not tested, but it shows you a possible way):\nfrom django.utils.importlib import import_module\nfrom django.conf import settings\nfrom django.contrib.auth import get_user\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KE...
[ 8, 5 ]
[]
[]
[ "django", "django_authentication", "django_sessions", "django_users", "python" ]
stackoverflow_0005030984_django_django_authentication_django_sessions_django_users_python.txt
Q: Fabric methods exceptions I try to make Fabric func, which checks if Apache installed: from fabric.api import * def check_apache(): try: result = local('httpd -v', capture=True) except: print "check_apache exception" But if httpd is not installed I get: $ fab check_apache Fatal error: lo...
Fabric methods exceptions
I try to make Fabric func, which checks if Apache installed: from fabric.api import * def check_apache(): try: result = local('httpd -v', capture=True) except: print "check_apache exception" But if httpd is not installed I get: $ fab check_apache Fatal error: local() encountered an error (ret...
[ "You can set env.warn_only to True or use the setting context manager. See http://docs.fabfile.org/0.9.3/api/core/context_managers.html?highlight=warn#fabric.context_managers.settings\n" ]
[ 1 ]
[]
[]
[ "exception", "fabric", "python" ]
stackoverflow_0005030864_exception_fabric_python.txt
Q: Most efficient way to get several hashes in Redis? So I've already read this post about there not being an MGET analog for Redis hashes. One of the answers said to use MULTI/EXEC to do the operation in bulk, and that does work for lists and regular keys, but not for hashes, unfortunately. Right now, however, I'm d...
Most efficient way to get several hashes in Redis?
So I've already read this post about there not being an MGET analog for Redis hashes. One of the answers said to use MULTI/EXEC to do the operation in bulk, and that does work for lists and regular keys, but not for hashes, unfortunately. Right now, however, I'm doing a call over the wire for every single hash I want t...
[ "The most efficient way would be using a pipeline.\nAssuming you want everything for a given key and know all the keys already:\nimport redis\n\nr = redis.Redis(host='localhost', port=6379, db=0)\np = r.pipeline()\nfor key in keys:\n p.hgetall(key)\n\nfor h in p.execute():\n print h\n\nMore information about ...
[ 44 ]
[]
[]
[ "database_design", "optimization", "python", "redis" ]
stackoverflow_0004929202_database_design_optimization_python_redis.txt
Q: Interactive figure with OO Matplotlib Using Matplotlib via the OO API is easy enough for a non-interactive backend: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) ax.plot([...
Interactive figure with OO Matplotlib
Using Matplotlib via the OO API is easy enough for a non-interactive backend: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) ax.plot([1,2,3]) canvas.print_figure('test.png') B...
[ "Well, you need to be using a backend that supports interaction! \nbackend_agg is not interactive. backend_tkagg (or one of the other similar backends) is. \nOnce you're using an interactive backend, you need to do something more like this:\nimport matplotlib.backends.backend_tkagg as backend\nfrom matplotlib.fi...
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005030920_matplotlib_python.txt
Q: Updating a binding that is bound to object[property] (Binding.IndexerName weirdness) This emerged from my related question. I currently have the following binding: myBinding = Binding("[foo]") myBinding.Mode = System.Windows.Data.BindingMode.TwoWay myBinding.Source = obj acheckbox.SetBinding(CheckBox.IsC...
Updating a binding that is bound to object[property] (Binding.IndexerName weirdness)
This emerged from my related question. I currently have the following binding: myBinding = Binding("[foo]") myBinding.Mode = System.Windows.Data.BindingMode.TwoWay myBinding.Source = obj acheckbox.SetBinding(CheckBox.IsCheckedProperty, myBinding) acheckbox.DataContext = obj This will look at obj[foo]. The UI...
[ "According to mamadero2 in this thread Item[index] only works in Silverlight 4.\n(I never would have imagined that Silverlight supports something that WPF does not)\n" ]
[ 1 ]
[]
[]
[ "binding", "inotifypropertychanged", "ironpython", "python", "wpf" ]
stackoverflow_0005031196_binding_inotifypropertychanged_ironpython_python_wpf.txt
Q: Python - Cleanest way to override __init__ where an optional kwarg must be used after the super() call? I love how beautiful python looks/feels and I'm hoping this can be cleaner (readability is awesome). What's a clean way to accept an optional keyword argument when overriding a subclassed init where the optional...
Python - Cleanest way to override __init__ where an optional kwarg must be used after the super() call?
I love how beautiful python looks/feels and I'm hoping this can be cleaner (readability is awesome). What's a clean way to accept an optional keyword argument when overriding a subclassed init where the optional kwarg has to be used after the super() call? I have a django form where I'd like to accept an optional user...
[ "I usually just do essentially what you're doing here. However, you can shorten/clean up your code by supplying a default argument to dict.pop:\n def __init__(self, *args, **kwargs):\n user = kwargs.pop('user', None)\n super(BaseCheckoutForm, self).__init__(*args, **kwargs)\n if user is not None:\n ...
[ 60 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005031711_django_python.txt
Q: How to time web request in CherryPy? I would like to time how long it takes for CherryPy to return a page when given a request. How may I go about it? A: You can write a decorator: import datetime import cherrypy def request_timer(f, *args, **kwargs): def _request_time(f, *args, **kwargs): begin = d...
How to time web request in CherryPy?
I would like to time how long it takes for CherryPy to return a page when given a request. How may I go about it?
[ "You can write a decorator:\nimport datetime\nimport cherrypy\n\ndef request_timer(f, *args, **kwargs):\n def _request_time(f, *args, **kwargs):\n begin = datetime.datetime.now()\n response = f(*args, **kwargs)\n end = datetime.datetime.now()\n print cherrypy.log('time took for reques...
[ 1, 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0005028668_cherrypy_python.txt
Q: Post-process request event in Pyramid/Pylons Is there an event or some kind of work with middlelayer where the request is already sent to the user, but we still have the information so we can do stuff on the DB later? A: As you probably already know about, you can do before request handing with: http://docs.pylo...
Post-process request event in Pyramid/Pylons
Is there an event or some kind of work with middlelayer where the request is already sent to the user, but we still have the information so we can do stuff on the DB later?
[ "As you probably already know about, you can do before request handing with:\nhttp://docs.pylonsproject.org/projects/pyramid/1.0/narr/events.html#configuring-an-event-listener-imperatively\nTo handle post-request stuff (without using middleware) you need to add a finished callback to the request which is demonstrat...
[ 3, 1 ]
[]
[]
[ "pylons", "pyramid", "python" ]
stackoverflow_0005010863_pylons_pyramid_python.txt
Q: How to get the App Engine SDK to track file changes in directories added via sys.path? I am currently experiencing an issue with the Google AppEngine SDK where directories added using sys.path don't have their changes recognized by the SDK. Requiring the SDK be restarted in order for the modified files to have any...
How to get the App Engine SDK to track file changes in directories added via sys.path?
I am currently experiencing an issue with the Google AppEngine SDK where directories added using sys.path don't have their changes recognized by the SDK. Requiring the SDK be restarted in order for the modified files to have any effect. This is particularly a problem with frameworks that make use of sys.path, such as t...
[ "I've been dealing with file monitoring for some time and wrote\na library to do this. Hence a shameless plug:\nWrite a wrapper script around the dev_appserver module entry point\nto restart it using a library like:\nhttps://github.com/gorakhargosh/watchdog \nor the nosy script at\nhttps://github.com/gorakhargosh/w...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005032179_google_app_engine_python.txt
Q: Django manage.py only returning list of subcommands and options I'm sure I'm overlooking something very simple, but I've tried multiple times and still run into the same problem. I have installed Python 2.7.1 and Django 1.2.4 on Windows Vista. I create a project using django-admin startproject projectname. It succ...
Django manage.py only returning list of subcommands and options
I'm sure I'm overlooking something very simple, but I've tried multiple times and still run into the same problem. I have installed Python 2.7.1 and Django 1.2.4 on Windows Vista. I create a project using django-admin startproject projectname. It successfully creates the folders and files needed. I then try running man...
[ "have you run manage.py runserver and if you have, then try python manage.py runserver?\n" ]
[ 1 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0005032139_django_manage.py_python.txt
Q: appending non-unique rows to another database using python Hey all, I have two databases. One with 145000 rows and approx. 12 columns. I have another database with around 40000 rows and 5 columns. I am trying to compare based on two columns values. For example if in CSV#1 column 1 says 100-199 and column two says ...
appending non-unique rows to another database using python
Hey all, I have two databases. One with 145000 rows and approx. 12 columns. I have another database with around 40000 rows and 5 columns. I am trying to compare based on two columns values. For example if in CSV#1 column 1 says 100-199 and column two says Main St(meaning that this row is contained within the 100 block ...
[ "\nA csv file is NOT a database. A csv file is just rows of text-chunks; a proper database (like PostgreSQL or Mysql or SQL Server or SQLite or many others) gives you proper data types and table joins and indexes and row iteration and proper handling of multiple matches and many other things which you really don't ...
[ 2 ]
[]
[]
[ "append", "csv", "python" ]
stackoverflow_0005031444_append_csv_python.txt
Q: Why does Learn Python The Hard Way suggest to "Read your .py file backwards."? I am reading Learn Python The Hard Way and I am really curious what he means by Read your .py file backwards A: Exercise 41 (page 117) explains it better. This snippet: cities['_find']=find_city city_found=cities['_find'](cities,stat...
Why does Learn Python The Hard Way suggest to "Read your .py file backwards."?
I am reading Learn Python The Hard Way and I am really curious what he means by Read your .py file backwards
[ "Exercise 41 (page 117) explains it better. This snippet:\ncities['_find']=find_city\ncity_found=cities['_find'](cities,state)\n\nreads like this when read backwards:\n\n\nstate and city are...\npassed as parameters to...\na function at...\n_find inside...\nthe dict cities...\nand finally assigned to city_found.\n\n...
[ 14, 5 ]
[]
[]
[ "python" ]
stackoverflow_0004461540_python.txt
Q: Using objectify to get items with a different namespace prefix <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:dd="http://example.com/ns/1.0" xml:lang="en-US"> <entry> <content type="html">Hello World!</content> <dd:country_code>USA</dd:country_code> </entry> I would...
Using objectify to get items with a different namespace prefix
<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:dd="http://example.com/ns/1.0" xml:lang="en-US"> <entry> <content type="html">Hello World!</content> <dd:country_code>USA</dd:country_code> </entry> I would like to use lxml.objectify to access both 'Hello World!' and 'USA'....
[ "With this setup:\nimport lxml.objectify as objectify\nimport io\n\ncontent='''\\\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:dd=\"http://example.com/ns/1.0\" xml:lang=\"en-US\">\n<entry>\n <content type=\"html\">Hello World!</content>\n <dd:country_code>USA<...
[ 1 ]
[]
[]
[ "lxml", "objectify", "python", "xml" ]
stackoverflow_0005030664_lxml_objectify_python_xml.txt
Q: Plus + Character disappears For some reason when I render a template that contains the + sign it disappears, no errors or anything just gone. I am rendering it like this rc = RequestContext(request, template_context_dict) html_content = smart_str(Template(updated_template_source).render(rc)) it is still there wh...
Plus + Character disappears
For some reason when I render a template that contains the + sign it disappears, no errors or anything just gone. I am rendering it like this rc = RequestContext(request, template_context_dict) html_content = smart_str(Template(updated_template_source).render(rc)) it is still there when I check the request and rc, bu...
[ "Maybe it's something to do with autoescape. \nMaybe try\n{% autoescape on %}\n {{ body }}\n{% endautoescape %}\n\nand see if it still doesn't render.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0005029787_django_django_forms_django_templates_python.txt
Q: Python 3 Syntax Changes So my work which had used older Python 2 is doing some code updating, anyways I am just learning python and am actually pretty new here, but what are the major syntax changes that went from 2-->3 Or is there really even that much syntax changes at all (like I know print got changed, but wha...
Python 3 Syntax Changes
So my work which had used older Python 2 is doing some code updating, anyways I am just learning python and am actually pretty new here, but what are the major syntax changes that went from 2-->3 Or is there really even that much syntax changes at all (like I know print got changed, but what else MAJOR) Thanks
[ "What’s New In Python 3.0:\nhttp://docs.python.org/release/3.0.1/whatsnew/3.0.html\nPEP: 3000 - Python 3000:\nhttp://www.python.org/dev/peps/pep-3000/\nPEP: 3099 - Things that will Not Change in Python 3000:\nhttp://www.python.org/dev/peps/pep-3099/\n", "Did you read this: Overview of Syntax Changes ?\n", "The ...
[ 11, 5, 4, 0 ]
[]
[]
[ "python", "python_2.x", "python_3.x", "syntax" ]
stackoverflow_0005031625_python_python_2.x_python_3.x_syntax.txt
Q: What are html templating alternatives for Django? Please note I'm coming from a Ruby & Node.js world and would like to use something concise and not neccessarily complex. Would be great to use haml but it's not required. I was looking at Jinja2 but it seems to be a better implementation of roughly the same idea as...
What are html templating alternatives for Django?
Please note I'm coming from a Ruby & Node.js world and would like to use something concise and not neccessarily complex. Would be great to use haml but it's not required. I was looking at Jinja2 but it seems to be a better implementation of roughly the same idea as standard templates which seem IMHO overengineered a bi...
[ "Templating in Python lists a bunch.\n", "I think the closest thing you are going to find is something like Brevé\nHAML:\n#profile\n .left.column\n #date= print_date\n #address= current_user.address\n .right.column\n #email= current_user.email\n #bio= current_user.bio\n\nBrevé\ndiv ( id = 'profile' ...
[ 6, 2 ]
[]
[]
[ "html", "model_view_controller", "python", "templates" ]
stackoverflow_0005031994_html_model_view_controller_python_templates.txt
Q: Hosting Mercurial with IIS 6 I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following this post I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config. However, when I trying to open the http://hostname/hg/hgwe...
Hosting Mercurial with IIS 6
I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following this post I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config. However, when I trying to open the http://hostname/hg/hgwebdir.cgi I got an error “The speci...
[ "Some more things that I needed to fix:\n\nWhere the various HOWTOs say to use c:\\whatever\\Python26\\python.exe -u \"%s\" \"%s\" instead use c:\\whatever\\Python26\\python.exe -u -O -B \"%s\" \"%s\" -O causes it to also look for .pyo files (not just .py or .pyc, which at least in my version weren't present). -B...
[ 6, 2, 2, 1, 1 ]
[]
[]
[ "iis_6", "mercurial", "python" ]
stackoverflow_0001191136_iis_6_mercurial_python.txt
Q: Should I use Python 2.7 32 bit or 64 bit with Windows 7 I am setting up Django, and am trying to decide whether to use the 32 bit or 64 bit version of Python 2.7 on my Windows 7 machine. I've seen the issues with the 64 bit installer, but the real question is whether or not all of the necessary libraries are avail...
Should I use Python 2.7 32 bit or 64 bit with Windows 7
I am setting up Django, and am trying to decide whether to use the 32 bit or 64 bit version of Python 2.7 on my Windows 7 machine. I've seen the issues with the 64 bit installer, but the real question is whether or not all of the necessary libraries are available for 64 bit, or whether one version has any other issues ...
[ "if you need more than 4gb of RAM to work with:\n return 64\nelse:\n return 32\n\n", "I recommend the 32-bit one unless you are going to exhaust the address space. Many third-party modules like OpenCV and Numpy are considerably easier to install with 32-bit Python. (You can build those modules from source t...
[ 28, 27 ]
[]
[]
[ "django", "python", "windows_7" ]
stackoverflow_0005032956_django_python_windows_7.txt
Q: In Python, how do I know when a process is finished? From within a Python GUI (PyGTK) I start a process (using multiprocessing). The process takes a long time (~20 minutes) to finish. When the process is finished I would like to clean it up (extract the results and join the process). How do I know when the proc...
In Python, how do I know when a process is finished?
From within a Python GUI (PyGTK) I start a process (using multiprocessing). The process takes a long time (~20 minutes) to finish. When the process is finished I would like to clean it up (extract the results and join the process). How do I know when the process has finished? My colleague suggested a busy loop withi...
[ "I think as a part of making python multi-platform, simple things like SIGCHLD must be done yourself. Agreed, this is a little more work when all you want to do is know when the child is done, but it really isn't THAT painful. Consider the following that uses a child process to do the work, two multiprocessing.Ev...
[ 11, 5, 2, 2, 1 ]
[]
[]
[ "multiprocessing", "multithreading", "parallel_processing", "python", "user_interface" ]
stackoverflow_0004995419_multiprocessing_multithreading_parallel_processing_python_user_interface.txt
Q: Cythonize a Python function to make it faster Few weeks ago I asked a question on increasing the speed of a function written in Python. At that time, TryPyPy brought to my attention the possibility of using Cython for doing so. He also kindly gave an example of how I could Cythonize that code snippet. I want to do...
Cythonize a Python function to make it faster
Few weeks ago I asked a question on increasing the speed of a function written in Python. At that time, TryPyPy brought to my attention the possibility of using Cython for doing so. He also kindly gave an example of how I could Cythonize that code snippet. I want to do the same with the code below to see how fast I can...
[ "As a general note, you can see exactly what C code Cython generates for every source line by running the cython command with the -a \"annotate\" option. See the Cython documentation for examples. This is extremely helpful when trying to find bottlenecks in a function's body.\nAlso, there's the concept of \"early...
[ 7, 1 ]
[]
[]
[ "cython", "performance", "python" ]
stackoverflow_0004872715_cython_performance_python.txt
Q: VLC Python Bindings -- Error 193 Have downloaded VLC.py, and placed it in my VLC install directory, where libvlc.dll is also present On typing import vlc I get the following error Traceback (most recent call last): File "C:\Program Files (x86)\VideoLAN\VLC\vlc.py", line 88, in dll = ctypes.CDLL('libv...
VLC Python Bindings -- Error 193
Have downloaded VLC.py, and placed it in my VLC install directory, where libvlc.dll is also present On typing import vlc I get the following error Traceback (most recent call last): File "C:\Program Files (x86)\VideoLAN\VLC\vlc.py", line 88, in dll = ctypes.CDLL('libvlc.dll') File "C:\Python27\lib\cty...
[ "Reposting my comment as an answer, since it fixed the problem:\n\nI'm going to guess that the problem is trying to load a 32-bit DLL from a 64-bit process. You may be able to fix it by using a 32-bit Python build.\n\n" ]
[ 3 ]
[]
[]
[ "python", "vlc" ]
stackoverflow_0005007455_python_vlc.txt
Q: How to publish (in a server) a pydev app using eclipse? I'm new with Eclipse and in the field of web applications. I used eclipse to wrote a django application that works well inside the development server integrated in django. Now, using Eclipse, I want to export my app to work with an apache2 server. I've instal...
How to publish (in a server) a pydev app using eclipse?
I'm new with Eclipse and in the field of web applications. I used eclipse to wrote a django application that works well inside the development server integrated in django. Now, using Eclipse, I want to export my app to work with an apache2 server. I've installed the server and configured it inside eclipse (Defining the...
[ "You are probably using django development server (the manage.py runsrever) with eclipse. Eclipse or any other ide has little to do with deployment of your web application.\nDjango documentation explains how to deploy you application on appache and wsgi quite well.\nBasically you will need to reproduce your eclipse...
[ 2 ]
[]
[]
[ "django", "eclipse", "pydev", "python", "web_applications" ]
stackoverflow_0005032859_django_eclipse_pydev_python_web_applications.txt
Q: Is there a reason why Python's ctypes.CDLL cannot automatically generate restype and argtypes from C header files? For example, it would be nice to be able to do this: from ctypes import CDLL mylib = CDLL('/my/path/mylib.so',header='/some/path/mylib.h') instead of from ctypes import * mylib = CDLL('/my/path/mylib...
Is there a reason why Python's ctypes.CDLL cannot automatically generate restype and argtypes from C header files?
For example, it would be nice to be able to do this: from ctypes import CDLL mylib = CDLL('/my/path/mylib.so',header='/some/path/mylib.h') instead of from ctypes import * mylib = CDLL('/my/path/mylib.so') mylib.f.restype = c_double mylib.f.argtypes = [c_double, c_double] mylib.g.restype = c_int mylib.g.argtypes = [c_d...
[ "I asked myself the same question and before I traveled down that road too far, I ran into ctypesgen:\nhttp://code.google.com/p/ctypesgen/\nIt will handle all of this for you, although you will need to do a little learning up front. We use ctypesgen to generate one version of the Python bindings for the Subversion...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0005033162_python.txt
Q: uWSGI with Cherokee: first steps Has anyone tried using uWSGI with Cherokee? Can you share your experiences and what documents you relied upon the most? I am trying to get started from the documentation on both (uWSGI and Cherokee) websites. Nothing works yet. I am using Ubuntu 10.04. Edit: To clarify, Cherokee h...
uWSGI with Cherokee: first steps
Has anyone tried using uWSGI with Cherokee? Can you share your experiences and what documents you relied upon the most? I am trying to get started from the documentation on both (uWSGI and Cherokee) websites. Nothing works yet. I am using Ubuntu 10.04. Edit: To clarify, Cherokee has been working fine. I am getting the...
[ "Yep, I just recently set this up in Ubuntu Lucid for a Pylons app. \nFirst, I grabbed the latest cherokee from the team PPA.\nhttps://launchpad.net/~cherokee-webserver/+archive/ppa\nNext I installed the uwsgi latest into my virtualenv my app lives in via Pip which the uwsgi docs walk you through. \nhttp://projects...
[ 2, 2, 1 ]
[]
[]
[ "cherokee", "python", "uwsgi", "wsgi" ]
stackoverflow_0003030936_cherokee_python_uwsgi_wsgi.txt
Q: "y" or "yes" -- expectations not met In the following code, answer() works as expected and returns true if input is "y" and false when not, but in answer2(), it always returns true. Can someone explain why this is the case? def answer(): answer = raw_input() if answer == "y": return True else: ...
"y" or "yes" -- expectations not met
In the following code, answer() works as expected and returns true if input is "y" and false when not, but in answer2(), it always returns true. Can someone explain why this is the case? def answer(): answer = raw_input() if answer == "y": return True else: return False def answer2(): ...
[ "The expression, \"y\" or \"yes\" will evaluate to \"y\". What you want is:\nif answer in ('y', 'yes'):\n return True\n\n", "I'm not a Python expert, but I suspect in answer2 it should be:\nif answer == \"y\" or answer == \"yes\": # <- notice the extra: or \"yes\"\n\nIn other words, I suspect it's currently p...
[ 7, 5, 4, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005033448_python.txt
Q: How to translate double-UTF-8-decoder code in Python to Lua I have this legacy code snippet, which (apparently) decodes double-encoded UTF-8 text back to normal UTF-8: # Run with python3! import codecs import sys s=codecs.open('doubleutf8.dat', 'r', 'utf-8').read() sys.stdout.write( s ...
How to translate double-UTF-8-decoder code in Python to Lua
I have this legacy code snippet, which (apparently) decodes double-encoded UTF-8 text back to normal UTF-8: # Run with python3! import codecs import sys s=codecs.open('doubleutf8.dat', 'r', 'utf-8').read() sys.stdout.write( s .encode('raw_unicode_escape') .decode('utf-8')...
[ "You can use lua-iconv, the Lua binding to the iconv library. With it you can convert between character encodings as much as you like.\nIt is also available in LuaRocks.\nEdit: using this answer I have been able to correctly decode the data using the following Lua code:\nrequire 'iconv'\n-- convert from utf8 to lat...
[ 3 ]
[]
[]
[ "lua", "python", "unicode", "utf_8" ]
stackoverflow_0005032344_lua_python_unicode_utf_8.txt
Q: How do I create a fixed-length, mutable array of Python objects in Cython? I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that ...
How do I create a fixed-length, mutable array of Python objects in Cython?
I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is exactly the right size (if it starts allocating extra elements, the ...
[ "I don't know about the best solution, but here's a solution:\nfrom cpython.ref cimport PyObject, Py_XINCREF, Py_XDECREF\n\nDEF SIZE = 32\n\ncdef class TrieNode:\n cdef PyObject *members[SIZE]\n\n def __cinit__(self):\n cdef object temp_object\n for i in range(SIZE):\n temp_object = i...
[ 5, 1, 0 ]
[]
[]
[ "arrays", "cython", "python", "python_c_extension", "trie" ]
stackoverflow_0004834036_arrays_cython_python_python_c_extension_trie.txt
Q: Store specific value in javascript when multiple forms are present I've got a list of 10-20 objects on each page creating these forms: <div id="routeTable"> {% for route in route_list %} <div id="routeDone"> <form class="doneForm" action="/route/complete/" method="post"> <input type="hidden" name="ro...
Store specific value in javascript when multiple forms are present
I've got a list of 10-20 objects on each page creating these forms: <div id="routeTable"> {% for route in route_list %} <div id="routeDone"> <form class="doneForm" action="/route/complete/" method="post"> <input type="hidden" name="route_id" value="{{ route.route_id }}" /> <input type="hidden" name=...
[ "Try to change \nvar route_id = $(this).attr('input[name=route_id]').val()\n\nto\nvar route_id = $(this).find('input[name=route_id]').val()\n\nThe reason being that input[name=route_id] is not an attribute, but a selector that represent a tag input and an attribute on that tag [name=route_id].\nYou could also do \n...
[ 1, 0 ]
[]
[]
[ "django", "html", "javascript", "python" ]
stackoverflow_0005034069_django_html_javascript_python.txt
Q: Python super method and calling alternatives I see everywhere examples that super-class methods should be called by: super(SuperClass, instance).method(args) Is there any disadvantage to doing: SuperClass.method(instance, args) A: Consider the following situation: class A(object): def __init__(self): ...
Python super method and calling alternatives
I see everywhere examples that super-class methods should be called by: super(SuperClass, instance).method(args) Is there any disadvantage to doing: SuperClass.method(instance, args)
[ "Consider the following situation:\nclass A(object):\n def __init__(self):\n print('Running A.__init__')\n super(A,self).__init__()\nclass B(A):\n def __init__(self):\n print('Running B.__init__') \n # super(B,self).__init__()\n A.__init__(self) \n\nclass C(A):\n d...
[ 114, 9 ]
[]
[]
[ "class", "python", "super" ]
stackoverflow_0005033903_class_python_super.txt
Q: In Python, should I use else after a return in an if block? First, I couldn't find an answer to this in PEP 8. That doesn't mean it isn't in there. Feel free to point me at it. Which style do you prefer? The first one: if spam: # Do stuff. return eggs else: # Maybe do other stuff. return parrots o...
In Python, should I use else after a return in an if block?
First, I couldn't find an answer to this in PEP 8. That doesn't mean it isn't in there. Feel free to point me at it. Which style do you prefer? The first one: if spam: # Do stuff. return eggs else: # Maybe do other stuff. return parrots or the second one: if spam: # Do stuff. return eggs # Mayb...
[ "The first one!\nExplicit is better than implicit.\n", "It depends, if you would return parrots, when you do not return eggs, then the first one is more clear.\nBut if you are trying to catch an error or something like that, the second one is better.\n", "The second one! Less is more, and more is better.\n", ...
[ 13, 13, 8, 6, 4, 2, 0 ]
[ "I don't know python, but I do :\nreturn spam if eggs else parrots\n\nEdit : I didn't notice the Do stuff part. In that case, I would create another method or function (whatever it is called in python) for each branch. \n" ]
[ -8 ]
[ "coding_style", "python" ]
stackoverflow_0005033906_coding_style_python.txt
Q: extracting paragraph in python using lxml I would like to extract paragraphs in html by python. I used lxml module but it doesn't do exactly what I am looking for. print html.parse(url).xpath('//p')[1].text_content() <span id="midArticle_1"></span><p>Here is the First Paragraph.</p><span id="midArticle_2"></span>...
extracting paragraph in python using lxml
I would like to extract paragraphs in html by python. I used lxml module but it doesn't do exactly what I am looking for. print html.parse(url).xpath('//p')[1].text_content() <span id="midArticle_1"></span><p>Here is the First Paragraph.</p><span id="midArticle_2"></span><p>Here is the second Paragraph.</p><span id="m...
[ "print html.parse(url).xpath('//p/text()')\n\nOutput\n['Here is the First Paragraph.', 'Here is the second Paragraph.', \n 'Paragraph Three.\"']\n\n" ]
[ 4 ]
[]
[]
[ "html_parsing", "lxml", "paragraphs", "python" ]
stackoverflow_0005034351_html_parsing_lxml_paragraphs_python.txt
Q: python regex match line if exist or not I have a little problem with a regex. Here is a sample of the text to parse : output = """ country : USA zzzzzzz continent : Americ eeeeeee ------ country : China zzzzzzz continent : Asia planet : Earth ------- country : Izbud zzzzzzz continent : Gladiora zzzzzzz zzzzzzz pla...
python regex match line if exist or not
I have a little problem with a regex. Here is a sample of the text to parse : output = """ country : USA zzzzzzz continent : Americ eeeeeee ------ country : China zzzzzzz continent : Asia planet : Earth ------- country : Izbud zzzzzzz continent : Gladiora zzzzzzz zzzzzzz planet : Mars """ I want to parse this and retu...
[ "I'm going to suggest what I would do, which would be something that tries to avoid using such complex regex's. Probably something like:\nwhile true:\n line = readline()\n if line == \"----------\":\n # Do cleanup stuff\n continue\n elif 'country' in line.split():\n country = line.spli...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "line", "python", "regex" ]
stackoverflow_0005032626_line_python_regex.txt
Q: Project structuring and file implementation in Python I am having a bit of troubles getting a grasp on how to structure my Python projects. I have read jcalderone: Filesystem structure of a Python project and been looking at the source code of CouchApp, but I'm still feeling very puzzled. I understand how the file...
Project structuring and file implementation in Python
I am having a bit of troubles getting a grasp on how to structure my Python projects. I have read jcalderone: Filesystem structure of a Python project and been looking at the source code of CouchApp, but I'm still feeling very puzzled. I understand how the files should be structured, but I don't understand why. I would...
[ "\nname the directory something related to your project. When you do releases, you should include a version number suffix: Twisted-2.5.\n\nNot sure why this is unclear. It seems obvious. It all has to be in one directory. \nWhy do things have to be in one directory? Because everyone says so, that's why.\n\ncreat...
[ 1, 0, 0 ]
[]
[]
[ "project_structure", "python" ]
stackoverflow_0005033904_project_structure_python.txt
Q: What is a general process/concept to determine what to add to PYTHONPATH to resolve import issues? I keep running into problems with Unresolved imports in my Django project (in Eclipse w/ PyDev). After googling for a while on a given issue I can generally find the right thing to add to PYTHONPATH to solve the pro...
What is a general process/concept to determine what to add to PYTHONPATH to resolve import issues?
I keep running into problems with Unresolved imports in my Django project (in Eclipse w/ PyDev). After googling for a while on a given issue I can generally find the right thing to add to PYTHONPATH to solve the problem. But it seems like I'm missing some concept or process by which I can definitively say "obviously ...
[ "If you are using eclipse, she can automatically configure python interpreter (includes all libraries which are installed system-wide). You probably have done this step.\nIf you are still facing import problems you probably did not installed libraries system-wide. Or you have modified python paths and removed defau...
[ 3, 1, 1 ]
[]
[]
[ "django", "pydev", "python" ]
stackoverflow_0005033542_django_pydev_python.txt
Q: Where is my ipy.exe? I've got clean install of Windows 7 Ultimate, VS 2010 professional, and latest IronPython installed. In VS I can create an IronPython project just fine (seems like the install is ok), but when I try to run the project (a simple print), I get this error message: Interpreter "C:\Program Files\.....
Where is my ipy.exe?
I've got clean install of Windows 7 Ultimate, VS 2010 professional, and latest IronPython installed. In VS I can create an IronPython project just fine (seems like the install is ok), but when I try to run the project (a simple print), I get this error message: Interpreter "C:\Program Files\...\0.4\ipy.exe" does not ex...
[ "Right click on project - In the properties, provide the Interpreter path to whereever your ipy.exe is located.\nC:\\Program Files\\IronPython 2.7\\ipy.exe?\n" ]
[ 3 ]
[]
[]
[ "ironpython", "ironpython_studio", "python", "visual_studio_2010" ]
stackoverflow_0005034665_ironpython_ironpython_studio_python_visual_studio_2010.txt
Q: How safe is recursion in Python? I'm working on an AI homework, and despite my professor's suggestions, I have no intention of writing this assignment in lisp. However, I do want to write it recursively, the better to keep it concise and simple. Here is my question: Am I running a major risk of running out of sta...
How safe is recursion in Python?
I'm working on an AI homework, and despite my professor's suggestions, I have no intention of writing this assignment in lisp. However, I do want to write it recursively, the better to keep it concise and simple. Here is my question: Am I running a major risk of running out of stack space if I perform a search over a ...
[ "\nHow deep does the Python stack go?\n\nThe default recursion limit in python is 1000 frames. You can use sys.setrecursionlimit(n) to change that at your own risk. \nIf you're set on using python, I would suggest using a pattern more suited to the language. If you want to use the recursive style search, and need a...
[ 24, 5, 3, 2, 2 ]
[]
[]
[ "python", "recursion", "stack" ]
stackoverflow_0005034772_python_recursion_stack.txt
Q: How do I know when a child process died? In my class I run 4 process. from multiprocessing import Process procs = ( Process(target=ClassOne, name='ClassOne'), Process(target=ClassTwo, name='ClassTwo'), Process(target=ClassThree, name='ClassThree'), Process(...
How do I know when a child process died?
In my class I run 4 process. from multiprocessing import Process procs = ( Process(target=ClassOne, name='ClassOne'), Process(target=ClassTwo, name='ClassTwo'), Process(target=ClassThree, name='ClassThree'), Process(target=ClassFour, name='ClassFour'), ...
[ "Just define a signal handler for SIGCHLD, inspect the frame returned by the just dead child to retrieve the information you need about it ... and if necessary exit() the parent too :)\n", "It is possible to use os.waitpid() passing -1 as the first argument and 0 as the second one. \n\nThe first argument means th...
[ 3, 3, 1, 0 ]
[ "Here is a Windows solution. It uses WaitForMultipleObjects API call. For Unix os.waitpid may do the job.\nimport multiprocessing as mp\nimport ctypes\n\n\nSYNCHRONIZE = 0x00100000\nINFINITE = -1\n\n\ndef mbox(msg):\n ctypes.windll.user32.MessageBoxW(0, msg, u'spam', 0)\n\n\nif __name__ == '__main__':\n\n # start...
[ -2 ]
[ "ipc", "multiprocessing", "process", "python", "synchronization" ]
stackoverflow_0003675675_ipc_multiprocessing_process_python_synchronization.txt
Q: installing simplejson on the google appengine Super nub question time! I am trying to use simplejson on the google appengine. In a terminal on my machine I have simplejson installed and working. But my when I try to import it in a script running on the appengine I get an error saying no such library exists. If ope...
installing simplejson on the google appengine
Super nub question time! I am trying to use simplejson on the google appengine. In a terminal on my machine I have simplejson installed and working. But my when I try to import it in a script running on the appengine I get an error saying no such library exists. If open the interactive console on my machine (from the l...
[ "Look in django package: \nfrom django.utils import simplejson as json\nobj = json.loads(json_string)\n\nSince Sdk 1.4.2 Json can be imported with the following statement:\nimport simplejson\n\nNote that on Python 2.7 runtime you can use the native Json library.\n", "You no longer need to use the django packag...
[ 14, 10 ]
[]
[]
[ "google_app_engine", "python", "simplejson" ]
stackoverflow_0002711605_google_app_engine_python_simplejson.txt
Q: Accessing global attributes from inside a macro in Jinja2 I've been using macros in Jinja2 extensively and find them very DRY-ish; but there is one thing bothering me: how to access global stuff from macros? It would be really neat if I could somehow access url_for() natively from a macro. A: You can make any ca...
Accessing global attributes from inside a macro in Jinja2
I've been using macros in Jinja2 extensively and find them very DRY-ish; but there is one thing bothering me: how to access global stuff from macros? It would be really neat if I could somehow access url_for() natively from a macro.
[ "You can make any callable available in the Jinja environment:\njinja_env = Environment(...)\njinja_env.globals['url_for'] = url_for\n\nFor example, this output u'foobar' in a shell:\nfrom jinja2 import Environment\nenv = Environment()\nenv.globals['foo'] = lambda: \"foobar\"\nenv.from_string('{% macro bar() %}{{ f...
[ 8 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0005034437_jinja2_python.txt
Q: Run a terminal command and saving the values returned using Python/Django? I have a question regarding the use of Python. How do i run a command line command using Python? And after running the command, how do i save the returned values? For example: user@home:~$: ls -l drwxr-xr-x 3 root root 4096 ..[etc] home -r...
Run a terminal command and saving the values returned using Python/Django?
I have a question regarding the use of Python. How do i run a command line command using Python? And after running the command, how do i save the returned values? For example: user@home:~$: ls -l drwxr-xr-x 3 root root 4096 ..[etc] home -rw-r--r-- 1 user user 357 ..[etc] examples.doc So what i intend to do, is to run...
[ "You need to use subprocess -- http://docs.python.org/library/subprocess.html and http://docs.python.org/library/subprocess.html:\nfrom subprocess import Popen, PIPE\nstdout, stderr = Popen(['echo', 'Hello World!'], shell=False, stdout=PIPE)\nprint stdout.split('\\n')\n\n", "reece's answer almost works, but you n...
[ 2, 2, 1, 0 ]
[]
[]
[ "command_line", "django", "linux", "python" ]
stackoverflow_0003383148_command_line_django_linux_python.txt
Q: Python String Argument Parsing I am working with the cmd class in python and it passes me all of my arguments as one big string. What is the best way to tokenize this arg string into an array of args[]. Example: args = 'arg arg1 "arg2 with quotes" arg4 arg5=1' result = split_args(args) And it would look like: r...
Python String Argument Parsing
I am working with the cmd class in python and it passes me all of my arguments as one big string. What is the best way to tokenize this arg string into an array of args[]. Example: args = 'arg arg1 "arg2 with quotes" arg4 arg5=1' result = split_args(args) And it would look like: result = [ 'arg', 'arg1...
[ "import shlex\nshlex.split('arg arg1 \"arg2 with quotes\" arg4 arg5=1')\n\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0005035702_python.txt
Q: Can I read from the AppEngine BlobStore using the remote api I am trying to read (and subsequently save) blobs from the blobstore using the remote api. I get the error: "No api proxy found for service "blobstore"" when I execute the read. Here is the stub code: for b in bs.BlobInfo.all().fetch(100): b...
Can I read from the AppEngine BlobStore using the remote api
I am trying to read (and subsequently save) blobs from the blobstore using the remote api. I get the error: "No api proxy found for service "blobstore"" when I execute the read. Here is the stub code: for b in bs.BlobInfo.all().fetch(100): blob_reader = bs.BlobReader(str(b.key)) file = blob_reader....
[ "We recently added blobstore support to remote_api. Make sure you're using the latest version of the SDK, and your error should go away.\n" ]
[ 1 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0005034360_blobstore_google_app_engine_python.txt
Q: Is SimpleXMLRPCServer single threaded? Possible Duplicate: Python XMLRPC with concurrent requests I'm writing a python application which will act as xml-rpc server, using SimpleXMLRPCServer class. Now my question is: what happens if 2 or more clients send a request at the same time? Are they queued? Do I have th...
Is SimpleXMLRPCServer single threaded?
Possible Duplicate: Python XMLRPC with concurrent requests I'm writing a python application which will act as xml-rpc server, using SimpleXMLRPCServer class. Now my question is: what happens if 2 or more clients send a request at the same time? Are they queued? Do I have the guarantee that if two clients call the sa...
[ "I believe the library implementation of SimpleXMLRPCServer is indeed single-threaded. You have to add a mixin to make it serve requests in a multi-threaded way:\nfrom SocketServer import ThreadingMixIn\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\n\nclass MyXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):\n...
[ 8, 1 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0005033222_python_xml_rpc.txt
Q: How to make RTS units I want to make units fight in space just to try out some stuff it would need to print whats going on and results. I'm planing on loading each unit from a separate file or similar (units will be modifiable so i think it should be better this way, no need to keep each unit stats for instancing)...
How to make RTS units
I want to make units fight in space just to try out some stuff it would need to print whats going on and results. I'm planing on loading each unit from a separate file or similar (units will be modifiable so i think it should be better this way, no need to keep each unit stats for instancing). I'm not sure how i would ...
[ "There are a bunch of different ways of handling this, depending on exactly what you are trying to save and how you want to use it.\nIf you want to save basic unit-type stats so they can be easily modified, a plain-text file or csv file would work nicely. (If you have a copy of the game Alpha Centauri, look at the ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005035460_python.txt
Q: Google App Engine log username with custom auth I use a custom authentication for my python Google App Engine app. There is a "username" field in the log for every request, which is empty now. Is it possible to add the name of the authenticated user to the log? I would not like to add an "user: %s" % user.name man...
Google App Engine log username with custom auth
I use a custom authentication for my python Google App Engine app. There is a "username" field in the log for every request, which is empty now. Is it possible to add the name of the authenticated user to the log? I would not like to add an "user: %s" % user.name manually to all of my logging.xxx statements. Thanks.
[ "Add a single logging.debug call in your authentication code to log the current user. Logs are shown aggregated by request, so you'll always be able to see the user associated with that request.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "logging", "python" ]
stackoverflow_0005027371_google_app_engine_logging_python.txt
Q: Why does Jython not find this module? Possible Duplicate: How to run a python script from java? I am running a Python script using Jython and got this error: Exception in thread "main" Traceback (innermost last): File "C:\Facebook\LoginPython\Facebook.py", line 5, in ? ImportError: no module named cookielib Why...
Why does Jython not find this module?
Possible Duplicate: How to run a python script from java? I am running a Python script using Jython and got this error: Exception in thread "main" Traceback (innermost last): File "C:\Facebook\LoginPython\Facebook.py", line 5, in ? ImportError: no module named cookielib Why doesn't this work?
[ "A little bit more about using Jython - had my share of problems with that as well. Note that this may not be the best way to do it, but it works fine for me.\nI assume you want to call a function foo in module bar from your Java code that takes a string argument and returns a string:\n PythonInterpreter interpr...
[ 2, 1 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0005035735_java_jython_python.txt
Q: Python/Tkinter: Are Tkinter StringVar (IntVar, etc) thread safe? Are Tkinter StringVar (IntVar, FloatVar, etc) thread safe, eg. can a background thread read or write to these objects? Or must I use a Queue to pass information between my background thread and my main Tkinter GUI thread and have my main Tkinter thre...
Python/Tkinter: Are Tkinter StringVar (IntVar, etc) thread safe?
Are Tkinter StringVar (IntVar, FloatVar, etc) thread safe, eg. can a background thread read or write to these objects? Or must I use a Queue to pass information between my background thread and my main Tkinter GUI thread and have my main Tkinter thread pop the Queue and update the application's StringVar's accordingly?...
[ "Definitely go the Queue route. Nothing in Tkinter is setup for being threadsafe :(\n" ]
[ 0 ]
[]
[]
[ "multithreading", "python", "tkinter", "user_interface" ]
stackoverflow_0004058878_multithreading_python_tkinter_user_interface.txt
Q: Python Parameter pass to prevent sql injection. Why is this giving an error? from django.db import connection, transaction def pk_dt_catalog(p_CAT_ID,p_COMMONS_ID): c1 = connection.cursor() sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME FROM DT_CATALOG" sql = sql + " WHERE CAT_ID = %s ...
Python Parameter pass to prevent sql injection. Why is this giving an error?
from django.db import connection, transaction def pk_dt_catalog(p_CAT_ID,p_COMMONS_ID): c1 = connection.cursor() sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME FROM DT_CATALOG" sql = sql + " WHERE CAT_ID = %s AND COMMONS_ID = %s " param =(p_CAT_ID, p_COMMONS_ID) c1...
[ "In your code, you're using %s which is python substition string syntax, which expects the substitution values on the same line, e.g.\nsql = sql + \" WHERE CAT_ID = %s\n AND COMMONS_ID = %s \" % (p_CAT_ID, p_COMMONS_ID)\n\nHowever, this (as stated already) is not the best way because (a) it can be a ...
[ 12 ]
[]
[]
[ "oracle", "python" ]
stackoverflow_0005035580_oracle_python.txt
Q: Automatic Resizing in Python's tkinter In the following method, I am trying to create a frame, put a label and text widget inside of it, and place them inside of another text widget. There are two problems with the results. How should it be changed to: Have the inner text objects have the correct height based on ...
Automatic Resizing in Python's tkinter
In the following method, I am trying to create a frame, put a label and text widget inside of it, and place them inside of another text widget. There are two problems with the results. How should it be changed to: Have the inner text objects have the correct height based on the inserted text? Get the frame and text to...
[ ".grid methods have always been a bit of a hassle for me to get resizing/stretching correctly.\nFor your code, I would change the .grid calls to the following .pack calls:\nframe.pack(expand=1, fill='both')\nname.pack(fill='both', side='left')\ntext.pack(expand=1, fill='both')\n\nYou can then drop your .grid_{row,c...
[ 3, 2 ]
[]
[]
[ "python", "resize", "text", "tkinter" ]
stackoverflow_0005035824_python_resize_text_tkinter.txt
Q: Python: Twitter Streaming and pycurl problems I am having problems with pycurl in conjunction with Twitter's Streaming API filter stream. What is happening when I run the code below it seems to barf on the perform call. I know this because I placed print statements before and after the perform call. I am using Pyt...
Python: Twitter Streaming and pycurl problems
I am having problems with pycurl in conjunction with Twitter's Streaming API filter stream. What is happening when I run the code below it seems to barf on the perform call. I know this because I placed print statements before and after the perform call. I am using Python 2.6.1 and I am on a Mac if that matters. #!/usr...
[ "First, try turning on verbosity to help debug:\n self.conn.setopt(pycurl.VERBOSE ,1)\n\nIt looks like you aren't setting the basic auth mode:\n self.conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)\n\nAlso according to the documentation, you need to provide a POST of the parameters to the API, not pass th...
[ 2, 1 ]
[]
[]
[ "pycurl", "python", "twitter" ]
stackoverflow_0004289038_pycurl_python_twitter.txt
Q: Django-python: how to pass argument from child class to parent class? class MaleManager(models.Manager): def get_query_set(self): return super('here should be EmployeeManager', self).get_query_set().filter(sex='male') # Need to pass class name EmployeeManager to MaleManager class EmployeeManager(MaleMan...
Django-python: how to pass argument from child class to parent class?
class MaleManager(models.Manager): def get_query_set(self): return super('here should be EmployeeManager', self).get_query_set().filter(sex='male') # Need to pass class name EmployeeManager to MaleManager class EmployeeManager(MaleManager): def get_query_set(self): return super(EmployeeManager, s...
[ "If for, whatever reason, what you've described actually does make sense, you might be looking for the self.__class__ property.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005036822_django_django_models_python.txt
Q: distinct classes using `with` in Python If you have the following class: class Foo(object): def __init__(name): self.name = name And you use it like this in a file called check_foo.py with Foo("naming it"): print Foo.name with Foo("naming another"): print Foo.name If you import check_foo an...
distinct classes using `with` in Python
If you have the following class: class Foo(object): def __init__(name): self.name = name And you use it like this in a file called check_foo.py with Foo("naming it"): print Foo.name with Foo("naming another"): print Foo.name If you import check_foo and run dir(check_foo) you will only get a sin...
[ "I'm not sure if this is the sort of hackery that you are looking for...\nimport inspect\n\nclass renameable(object):\n def rename_me(self, new_name):\n for stack_frame in inspect.stack()[1:]:\n frame_object = stack_frame[0] # frame is the first object in the tuple\n for (name, value) in frame_object....
[ 1 ]
[]
[]
[ "class", "metaclass", "python", "with_statement" ]
stackoverflow_0005036837_class_metaclass_python_with_statement.txt
Q: In SQLAlchemy, can you filter a polymorphically associated model by the type of its associated record? I'm using a polymorphic association in SQLAlchemy as described in this example. It can also be found in the examples directory in the SQLAlchemy source code. Given this setup, I want to query for all Addresses t...
In SQLAlchemy, can you filter a polymorphically associated model by the type of its associated record?
I'm using a polymorphic association in SQLAlchemy as described in this example. It can also be found in the examples directory in the SQLAlchemy source code. Given this setup, I want to query for all Addresses that are associated with Users. Not a user but any user. In raw SQL, I could do that like this: select addre...
[ "ad-hoc joins using the ORM are described at:\nhttp://www.sqlalchemy.org/docs/orm/tutorial.html#querying-with-joins\nfor address in sess.query(Address).join(Address.association).filter_by(type='users'):\n print \"Street\", address.street, \"Member\", address.member\n\n" ]
[ 2 ]
[]
[]
[ "polymorphic_associations", "python", "sqlalchemy" ]
stackoverflow_0005036434_polymorphic_associations_python_sqlalchemy.txt
Q: Django - Rebuild a query string without one of the variables I have a Django view that processes a GET request. I want to rebuild the query string to include all variables except for one. I was initially using list comprehension: >>> from django.http import QueryDict >>> q = QueryDict('a=2&b=4&c=test') // <--- mak...
Django - Rebuild a query string without one of the variables
I have a Django view that processes a GET request. I want to rebuild the query string to include all variables except for one. I was initially using list comprehension: >>> from django.http import QueryDict >>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET >>> z = QueryDict('').copy() >>> z.u...
[ "Django puts the GET request variables into a dictionary for you, so request.GET is already a QueryDict. You can just do this:\nz = request.GET.copy()\ndel z['a']\n\nNote that dictionaries in python (and django QueryDicts) don't have a del() method, you have to use python's built in del() function. QueryDicts are...
[ 12, 5 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0005036498_django_django_views_python.txt
Q: Can SQLAlchemy do a non-destructive alter of the db comparing the current model with db schema? Basically I'm looking for an equivalent of DataMapper.auto_upgrade! from the Ruby world. In other words: change the model run some magic -> current db schema is investigated and changed to reflect the model profit Of ...
Can SQLAlchemy do a non-destructive alter of the db comparing the current model with db schema?
Basically I'm looking for an equivalent of DataMapper.auto_upgrade! from the Ruby world. In other words: change the model run some magic -> current db schema is investigated and changed to reflect the model profit Of course, there are cases when it's impossible for such alteration to be non-desctructive, eg. when you...
[ "Sqlalchemy-migrate (http://packages.python.org/sqlalchemy-migrate/) is intended to help do these types of operations.\n" ]
[ 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0005036118_orm_python_sqlalchemy.txt
Q: Using Blobstore Python API over HTTPS generates 405 error when redirecting back Don't know if it's I'm doing it wrong or if there's a bug (I would think so, seen others having the same problem) in the blobstore.create_upload_url method. In my app.yaml I have for some url's the property secure: always and the actio...
Using Blobstore Python API over HTTPS generates 405 error when redirecting back
Don't know if it's I'm doing it wrong or if there's a bug (I would think so, seen others having the same problem) in the blobstore.create_upload_url method. In my app.yaml I have for some url's the property secure: always and the action attribute of the form element starts with https:// but when it's return from the AP...
[ "This issue has been fixed by SDK 1.4.2. I just tested it and it is working fine now.\nSee issue in tracker here:\nhttp://code.google.com/p/googleappengine/issues/detail?id=3463\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004323248_google_app_engine_python.txt
Q: Is there anyway I can access File from Online SVN in python? I've made a python module file and uploaded in the SVN Repo (say string_utl.py which does string related operation). Is the anyway that I can access the the file Direclty for the SVN. Though I checkout the file Locally from the SVN to my computer and acc...
Is there anyway I can access File from Online SVN in python?
I've made a python module file and uploaded in the SVN Repo (say string_utl.py which does string related operation). Is the anyway that I can access the the file Direclty for the SVN. Though I checkout the file Locally from the SVN to my computer and access it from there. But that not the point. I'm thinking of a local...
[ "Just install the pysvn module and then use normal SVN checkout, update, commit, etc.\nYou can't directly access the SVN backend datastore so please don't try.\n", "If you are using python3,the url handling code is urllib.request.urlopen (BTW, it should not have said to use urllib2.urlopen). sys.path.append takes...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "svn", "sys.path", "urllib" ]
stackoverflow_0005025579_python_svn_sys.path_urllib.txt
Q: Pixels and geometrical shapes - Python/PIL I'm trying to build a basic heatmap based on points. Each point has a heat radius, and therefore is represented by a circle. Problem is that the circle needs to be converted in a list of pixels colored based on the distance from the circle's center. Finding it hard to fi...
Pixels and geometrical shapes - Python/PIL
I'm trying to build a basic heatmap based on points. Each point has a heat radius, and therefore is represented by a circle. Problem is that the circle needs to be converted in a list of pixels colored based on the distance from the circle's center. Finding it hard to find an optimal solution for many points, what I h...
[ "Instead of doing it pixel-by-pixel, use a higher level interface with anti-aliasing, like the aggdraw module and its ellipse(xy, pen, brush) function.\nLoop over the number of color steps you want (lets say, radius/2) and use 255/number_of_steps*current_step as the alpha value for the fill color.\n", "For plotti...
[ 3, 1, 1, 0 ]
[]
[]
[ "math", "python", "python_imaging_library" ]
stackoverflow_0005016904_math_python_python_imaging_library.txt
Q: Numpy Lookup (Map, or Point) I have a large numpy array: array([[32, 32, 99, 9, 45], # A [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) and a large-ish array of unique values in a particular order: array([ 99, 32, 45, 9]) # B How can I quickly (no python dictionar...
Numpy Lookup (Map, or Point)
I have a large numpy array: array([[32, 32, 99, 9, 45], # A [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) and a large-ish array of unique values in a particular order: array([ 99, 32, 45, 9]) # B How can I quickly (no python dictionaries, no copies of A, no python loo...
[ "Here you go\nA = array([[32, 32, 99, 9, 45], # A\n [99, 45, 9, 45, 32],\n [45, 45, 99, 99, 32],\n [ 9, 9, 32, 45, 99]])\n\nB = array([ 99, 32, 45, 9])\n\nii = np.argsort(B)\nC = np.digitize(A.reshape(-1,),np.sort(B)) - 1\n\nOriginally I suggested: \nD = np.choose(C,ii).reshape(A.shape)\n\nBut I realized ...
[ 8, 7 ]
[]
[]
[ "indexing", "numpy", "python" ]
stackoverflow_0005036816_indexing_numpy_python.txt
Q: Using cPickle to serialize a large dictionary causes MemoryError I'm writing an inverted index for a search engine on a collection of documents. Right now, I'm storing the index as a dictionary of dictionaries. That is, each keyword maps to a dictionary of docIDs->positions of occurrence. The data model looks some...
Using cPickle to serialize a large dictionary causes MemoryError
I'm writing an inverted index for a search engine on a collection of documents. Right now, I'm storing the index as a dictionary of dictionaries. That is, each keyword maps to a dictionary of docIDs->positions of occurrence. The data model looks something like: {word : { doc_name : [location_list] } } Building the inde...
[ "cPickle needs to use a bunch of extra memory because it does cycle detection. You could try using the marshal module if you are sure your data has no cycles\n", "There's the other pickle library you could try. Also there might be some cPickle settings you could change.\nOther options: Break your dictionary into...
[ 10, 0, 0 ]
[]
[]
[ "inverted_index", "pickle", "python", "serialization" ]
stackoverflow_0005037432_inverted_index_pickle_python_serialization.txt
Q: How do you input 2 files then output them in python? I have a code written for a webpage and I need to know how to take 2 data files and import them into an array then output the data in a table on my html site. the 2 data files are txt files that are on my computer A: Well I'm going to take a guess that you wan...
How do you input 2 files then output them in python?
I have a code written for a webpage and I need to know how to take 2 data files and import them into an array then output the data in a table on my html site. the 2 data files are txt files that are on my computer
[ "Well I'm going to take a guess that you want to just create an html table that has 1 line per data line in the text file.\nfile1=open(\"input1.txt\",'rU')\nfile2=open(\"input2.txt\",'rU')\nlines = file1.readlines() + file2.readlines()\nhtml = \"<html>\\n<body>\\n<table>\"\nfor line in lines:\n html += \"<tr><td>\...
[ 0 ]
[]
[]
[ "html", "input", "python" ]
stackoverflow_0005036601_html_input_python.txt
Q: auto import all sub modules in a folder then invoke same name functions - python runtime inspect related I have an open folder on my computer, OpenFunctions\ ____Template.py function1.py function2.py ...... functionx.py This folder is experimental purpose for extend the ability of the whole a...
auto import all sub modules in a folder then invoke same name functions - python runtime inspect related
I have an open folder on my computer, OpenFunctions\ ____Template.py function1.py function2.py ...... functionx.py This folder is experimental purpose for extend the ability of the whole app can doing. So let’s just think it is a quick and dry trying, no security consideration in this case. My pur...
[ "To address your last question first: to dynamically import modules in recent versions of Python, use importlib.import_module(), that's what it is for. If you're on an older version of Python, you should use __import__ instead (but check the idiosyncracies of that direct approach in the docs - there's a reason the ...
[ 2 ]
[]
[]
[ "autorun", "import", "inspect", "module", "python" ]
stackoverflow_0005037468_autorun_import_inspect_module_python.txt
Q: Ajax and Django forms I'd like to add Ajax to my admin form for editing a model. The model has a list field. I would like the Ajax to create a list of inputs with add and remove buttons, automatically calling back to the server when the user clicks "add" or "remove". What I'm stuck on is: how does the widget know...
Ajax and Django forms
I'd like to add Ajax to my admin form for editing a model. The model has a list field. I would like the Ajax to create a list of inputs with add and remove buttons, automatically calling back to the server when the user clicks "add" or "remove". What I'm stuck on is: how does the widget know what the backing model is?...
[ "I am doing something similar to this (although not in an admin form). I'm not sure if it is a recommended way of doing things...but it does seem to work for me.\nI have an action set on a html form in the template that calls a view which basically has the sole task of updating the data in the database and returni...
[ 0, 0 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0004716301_ajax_django_javascript_python.txt
Q: IOError: [Errno 13] Permission denied when trying to read an file in google app engine I want to read an XML file and parse it, for that I had used SAX parser which requires file as input to parse. For that I had stored my XML file in Entity called XMLDocs with following property XMLDocs Entity Name name : Prope...
IOError: [Errno 13] Permission denied when trying to read an file in google app engine
I want to read an XML file and parse it, for that I had used SAX parser which requires file as input to parse. For that I had stored my XML file in Entity called XMLDocs with following property XMLDocs Entity Name name : Property of string type content : property of blob type (will contain my xml file) Reason I had...
[ "It probably thinks that the data string you are providing is a filename.\nYou may be able to pass it a file-like object which wraps the data, for example instead of this:\nparser.parse(str(q.content))\n\nTry this:\nparser.parse(StringIO.StringIO(str(q.content)))\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005038418_google_app_engine_python.txt
Q: What is the simplest URL shortener application one could write in python for the Google App Engine? Services like bit.ly are great for shortening URL’s that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine? A...
What is the simplest URL shortener application one could write in python for the Google App Engine?
Services like bit.ly are great for shortening URL’s that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine?
[ "That sounds like a challenge!\nfrom google.appengine.ext import db\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import run_wsgi_app\n\nclass ShortLink(db.Model):\n url = db.TextProperty(required=True)\n\nclass CreateLinkHandler(webapp.RequestHandler):\n def post(self):\n link = S...
[ 29, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001405786_google_app_engine_python.txt
Q: Cities/Province/Cantons list with coords? where can I get a list of that? I need the coords of the distrits and cantons of Costa Rica, is there a place to get those? thanks in advance A: geonames.org is a public database of all cities/towns with a population over 1000. The data for each city includes geo coordin...
Cities/Province/Cantons list with coords?
where can I get a list of that? I need the coords of the distrits and cantons of Costa Rica, is there a place to get those? thanks in advance
[ "geonames.org is a public database of all cities/towns with a population over 1000. The data for each city includes geo coordinates and administrative division, which I believe would be your districts, provinces or cantons.\n", "Check out the Costa Rica link here - it may suit your needs.\nI found it with this se...
[ 4, 1, 0 ]
[]
[]
[ "coordinates", "database", "geolocation", "gis", "python" ]
stackoverflow_0004961469_coordinates_database_geolocation_gis_python.txt
Q: Why does the Django Atom1Feed use atom:updated instead of atom:published? I made an Atom feed in Django using a class that looks something like this: class AtomFeed(Feed): feed_type = feedgenerator.Atom1Feed # ... def item_pubdate(self, post): return datetime.datetime(post.date.year, post.da...
Why does the Django Atom1Feed use atom:updated instead of atom:published?
I made an Atom feed in Django using a class that looks something like this: class AtomFeed(Feed): feed_type = feedgenerator.Atom1Feed # ... def item_pubdate(self, post): return datetime.datetime(post.date.year, post.date.month, post.date.day) The resulting XML for an item: <entry> <title>..</t...
[ "You are not missing anything. The Atom RFC is correct, and this is a known bug in Django; see this Django bug.\nIt looks like a relatively simple fix, so feel free to get in there and patch it! ^_^\n" ]
[ 1 ]
[]
[]
[ "atom_feed", "django", "feed", "python" ]
stackoverflow_0004143113_atom_feed_django_feed_python.txt
Q: Easier way to access the OSX defaults system through Python and Ruby? Recently I have become a fan of storing various settings used for my testing scripts in the OSX defaults system as it allows me to keep various scripts in git and push them to github without worrying about leaving passwords/settings/etc hardcode...
Easier way to access the OSX defaults system through Python and Ruby?
Recently I have become a fan of storing various settings used for my testing scripts in the OSX defaults system as it allows me to keep various scripts in git and push them to github without worrying about leaving passwords/settings/etc hardcoded into the script. When writing a shell script using simple bash commands, ...
[ "You´ll want to use PyObjC: have a look at this article at mactech.com (in specific: scroll down to \"Accessing plists Via Python\"). And this article from oreilly on PyObjC.\nRun this, for example:\nfrom Foundation import *\nstandardUserDefaults = NSUserDefaults.standardUserDefaults()\npersistentDomains = standard...
[ 3 ]
[]
[]
[ "macos", "python", "ruby" ]
stackoverflow_0005038339_macos_python_ruby.txt
Q: How to conserve the integrity of the string from a database response using Python i am using py-postgresql as the driver the database, when make a select to a string with non-ASCII characters, the response replace the character with "�" what can i make to change this to the correct character? This is my code: clas...
How to conserve the integrity of the string from a database response using Python
i am using py-postgresql as the driver the database, when make a select to a string with non-ASCII characters, the response replace the character with "�" what can i make to change this to the correct character? This is my code: class decodify: def __init__(self): db = pgDriver.connect(user = 'demo', passw...
[ "Are you setting a client_encoding ? In theory py-postgresql should use the correct client_encoding automatically. Either you are setting it to something wrong, or there is something wrong on how it detects it, in which case you have to set it. The question is then to what. :)\n", "What character encoding are you...
[ 1, 0, 0, 0 ]
[]
[]
[ "postgresql", "python", "python_3.x", "unicode" ]
stackoverflow_0005037537_postgresql_python_python_3.x_unicode.txt
Q: Can my django app act as a header-stripping proxy? Public Soundcloud track urls force a download upon browsing to them by utilizing a Content-Disposition header (I think.. ) which triggers a download for a known mime-type. Is there a way to proxy (create a passthrough for) these urls and strip this header from my ...
Can my django app act as a header-stripping proxy?
Public Soundcloud track urls force a download upon browsing to them by utilizing a Content-Disposition header (I think.. ) which triggers a download for a known mime-type. Is there a way to proxy (create a passthrough for) these urls and strip this header from my request. I want to avoid serving the mp3 myself but I d...
[ "Technically it is entirely possible that you could request the file from the server and connect that incoming data to an output stream response in your view, thereby allowing you to control the headers that your client's browser receives so that it does not ask them to save the file.\nI'm going to recommend agains...
[ 2, 0 ]
[]
[]
[ "django", "mp3", "proxy", "python", "soundcloud" ]
stackoverflow_0005014485_django_mp3_proxy_python_soundcloud.txt
Q: Can I sort text by its numeric value in Python? I have dict in Python with keys of the following form: mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc...
Can I sort text by its numeric value in Python?
I have dict in Python with keys of the following form: mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, ...
[ "You can sort the keys the way that you want, by splitting them on '.' and then converting each of the components into an integer, like this:\nsorted(mydict.keys(), key=lambda a:map(int,a.split('.')))\n\nwhich returns this:\n['0',\n '1',\n '2.0',\n '2.1',\n '3',\n '4.0.0',\n '4.0.1',\n '5',\n '10',\n '11.0',\n '11....
[ 19, 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "sorting", "string" ]
stackoverflow_0001534542_python_sorting_string.txt
Q: Is wxPython good for a Hardware Simulator? For a computer architecture assignment, I am trying to replace a C++ library called "Sim" with something in Python. I am already using MyHDL for the simulator, but the C++ program has a nice interactive feature that lets students see the components connected together (gat...
Is wxPython good for a Hardware Simulator?
For a computer architecture assignment, I am trying to replace a C++ library called "Sim" with something in Python. I am already using MyHDL for the simulator, but the C++ program has a nice interactive feature that lets students see the components connected together (gates, inputs, outputs, flip flops, etc.) and toggl...
[ "wxPython or pyside (Qt python bindings) are both ideal for this.\nwx is a little better if you have any MFC experience, Qt is perhaps a more modern design.\n", "It sounds like you're simulating logic circuits? Depending on the kind of UI you are looking for, I'd say that wxPython could definitely do the job. Yo...
[ 1, 1, 0 ]
[]
[]
[ "computer_architecture", "python", "wxpython" ]
stackoverflow_0005038022_computer_architecture_python_wxpython.txt
Q: Handle tag in python sgmllib I'm trying to parse a page using my python script. But <nobr> tag along with '&' is giving me trouble. Here the actual html. <A HREF="http://enpass.in/algo/c12.html" CLASS="style"> <NOBR>Simulation for 1st & 2nd path</NOBR></A> Now my handle_data function of my parser(using sgmllib)...
Handle tag in python sgmllib
I'm trying to parse a page using my python script. But <nobr> tag along with '&' is giving me trouble. Here the actual html. <A HREF="http://enpass.in/algo/c12.html" CLASS="style"> <NOBR>Simulation for 1st & 2nd path</NOBR></A> Now my handle_data function of my parser(using sgmllib) is not able to handle the data pro...
[ "You need to encode the ampersand, like &amp; to become valid HTML.\n" ]
[ 0 ]
[]
[]
[ "html", "python", "sgml", "urllib2" ]
stackoverflow_0005039023_html_python_sgml_urllib2.txt
Q: how to import py file from different upper folder? All, File structure: \ util utils.py modules __init__.py modules1.py submodule __init__.py submodule.py I want to know how to import utils.py in those __init__.py for example, now I run the python interpreter in \ level, I run import modules...
how to import py file from different upper folder?
All, File structure: \ util utils.py modules __init__.py modules1.py submodule __init__.py submodule.py I want to know how to import utils.py in those __init__.py for example, now I run the python interpreter in \ level, I run import modules, I suppose the code from ..util.utils import * may work...
[ "If you are developping a python package (what you are obviously doing, as you have init.py), then the most simple way to import your module is just via the package.\nFor example, if your package is called mypackage, then:\nimport mypackage.utils\n\n" ]
[ 1 ]
[]
[]
[ "import", "path", "python" ]
stackoverflow_0005039326_import_path_python.txt
Q: Is it possible to hook up a more robust HTML parser to Python mechanize? I am trying to parse and submit a form on a website using mechanize, but it appears that the built-in form parser cannot detect the form and its elements. I suspect that it is choking on poorly formed HTML, and I'd like to try pre-parsing it ...
Is it possible to hook up a more robust HTML parser to Python mechanize?
I am trying to parse and submit a form on a website using mechanize, but it appears that the built-in form parser cannot detect the form and its elements. I suspect that it is choking on poorly formed HTML, and I'd like to try pre-parsing it with a parser better designed to handle bad HTML (say lxml or BeautifulSoup) a...
[ "I had a problem where a form field was missing from a form, I couldn't find any malformed html but I figured that was the cause so I used BeautifulSoup's prettify function to parse it and it worked.\nresp = br.open(url)\nsoup = BeautifulSoup(resp.get_data())\nresp.set_data(soup.prettify())\nbr.set_response(resp)\n...
[ 10, 3, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001782368_mechanize_python.txt
Q: Testing a server using Python script I want to do conformance testing of thttpd server. I need to use the python scripts to test it. Can you please share a script to test the transmission and reception of data to the server? Also, what kind of possible tests need to be performed? Are there any specific parameters ...
Testing a server using Python script
I want to do conformance testing of thttpd server. I need to use the python scripts to test it. Can you please share a script to test the transmission and reception of data to the server? Also, what kind of possible tests need to be performed? Are there any specific parameters to be tested?
[ "This can be done simply using the builtin urllib\nurllib.urlopen(yourserveraddress).read()\n\nYou can also do other things with urllib2 that allow you to test more functionality.\nIf you want some more intence tests then you might want to build a twisted reactor to test all your functionality.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005039570_python.txt
Q: Real Time File Transfer using python script I want to create an application which needs from time to time do file transfer (I want to write the server as well as the client). What is the best way to do this file transfer? Thanks in advance.. Nimmy... A: Pyftpdlib as a server. and any linux box as a client. A: ...
Real Time File Transfer using python script
I want to create an application which needs from time to time do file transfer (I want to write the server as well as the client). What is the best way to do this file transfer? Thanks in advance.. Nimmy...
[ "Pyftpdlib as a server.\nand any linux box as a client.\n", "FTP Tunneled over SSH.\nUse twisted and a good linux shell.\n" ]
[ 0, 0 ]
[]
[]
[ "file", "python", "rtp" ]
stackoverflow_0005038255_file_python_rtp.txt
Q: from new import classobj in Python 3.1 How can I change the given python 2.x statement to get it compiled on 3.1. The code line that not works. from new import classobj The error is "There is no module new". A: You could use the type function: X = type('X', (object,), {'a': 1}) A: In Python 2.x new.classobj ...
from new import classobj in Python 3.1
How can I change the given python 2.x statement to get it compiled on 3.1. The code line that not works. from new import classobj The error is "There is no module new".
[ "You could use the type function:\nX = type('X', (object,), {'a': 1})\n\n", "In Python 2.x new.classobj is the type of old-style types. There are no old-style types in Python 3.x. To port your code from Python 2.x to Python 3.x you first need to bring it up to the latest Python 2.x standards, and in that case it ...
[ 4, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005039452_python.txt
Q: Design pattern used in projects Hi I am learning Design patterns these days. I want to read design pattern used in various projects and how it is implemented. Implementation is helpful to connect the design pattern in broader picture and why they deiced to use that pattern. Problem with open source projects are th...
Design pattern used in projects
Hi I am learning Design patterns these days. I want to read design pattern used in various projects and how it is implemented. Implementation is helpful to connect the design pattern in broader picture and why they deiced to use that pattern. Problem with open source projects are they are not documented properly. Can ...
[ "boost, a very well written and documented library implements several design patterns. it's quite a large library, and these implementations are used in the libraries.\nhttp://www.boost.org\nboost is found in many projects, but loki's also worth reading:\nhttp://sourceforge.net/projects/loki-lib/\nthe original auth...
[ 5, 2, 2 ]
[]
[]
[ "c++", "design_patterns", "java", "python" ]
stackoverflow_0005039196_c++_design_patterns_java_python.txt
Q: In Django, a way for user to upload file to server, then move to Amazon S3? I have a web project where users are uploading .wav files. I want to generate a waveform image from the .wav file once it's uploaded. But generally for storage, I want to use Amazon S3. Thing is, I want to use something like TimeSide (http...
In Django, a way for user to upload file to server, then move to Amazon S3?
I have a web project where users are uploading .wav files. I want to generate a waveform image from the .wav file once it's uploaded. But generally for storage, I want to use Amazon S3. Thing is, I want to use something like TimeSide (http://code.google.com/p/timeside/wiki/PythonApi) to generate the waveform image from...
[ "It would make sense to do the work on your side and then upload to Amazon S3. You should be able to use Boto, or any other library by importing the library.\n", "I agree, the work should be done on the server upon upload. If its just S3, i believe this one would do: http://aws.amazon.com/code/134?_encoding=UTF8&...
[ 1, 1 ]
[]
[]
[ "amazon_s3", "django", "python", "wav", "waveform" ]
stackoverflow_0005035203_amazon_s3_django_python_wav_waveform.txt
Q: huff model in gis how would be the simplest version of the Huff model for territorial and economic analysis? sig using algorithms that I recommend or free libraries for working with files both vector and raster OGR A: There are some options within ArcGIS environment that might be of some help: Python script her...
huff model in gis
how would be the simplest version of the Huff model for territorial and economic analysis? sig using algorithms that I recommend or free libraries for working with files both vector and raster OGR
[ "There are some options within ArcGIS environment that might be of some help:\n\nPython script here \nSANET tool for network analysis here\n\n", "Also linked to/asked on GIS.SE https://gis.stackexchange.com/questions/6219/open-source-gis-implementation-of-the-huff-model \nScript for R - http://www.reymann.eu/wp-c...
[ 1, 1 ]
[]
[]
[ "gis", "modeling", "python", "raster" ]
stackoverflow_0002837870_gis_modeling_python_raster.txt
Q: xor each byte with 0x71 I needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems. f = open('a.out', 'r') f.read(1) So I ended up doing the same in C. #include <stdio.h> int main() { ...
xor each byte with 0x71
I needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems. f = open('a.out', 'r') f.read(1) So I ended up doing the same in C. #include <stdio.h> int main() { char buffer[1] = {0}; FIL...
[ "If you want to treat something as an array of bytes, then usually you want a bytearray as it behaves as a mutable array of bytes:\nb = bytearray(open('a.out', 'rb').read())\nfor i in range(len(b)):\n b[i] ^= 0x71\nopen('b.out', 'wb').write(b)\n\nIndexing a byte array returns an integer between 0x00 and 0xff, an...
[ 18 ]
[ "Try this:\nmy_num = int(f.read(1))\n\nAnd then xor the number stored in my_num.\n" ]
[ -2 ]
[ "binaryfiles", "hex", "python" ]
stackoverflow_0005037762_binaryfiles_hex_python.txt
Q: what is this url mean in django this is my code : (r'^q/(?P<terminal_id>[^/]+)/(?P<cmd_type>[^/]+)/?$', 'send_query_cmd'), the view is : def send_query_cmd(request, terminal_id, cmd_type): waht about ?p mean . i dont know what is this url mean , thanks A: (?P<id>REGEXP) is the syntax for python regular exp...
what is this url mean in django
this is my code : (r'^q/(?P<terminal_id>[^/]+)/(?P<cmd_type>[^/]+)/?$', 'send_query_cmd'), the view is : def send_query_cmd(request, terminal_id, cmd_type): waht about ?p mean . i dont know what is this url mean , thanks
[ "(?P<id>REGEXP) is the syntax for python regular expression named group capturing.\nhttp://docs.python.org/library/re.html ->> scroll down to (?P...\nAs for what the P stands for.. parameter? python? Origin sounds fun. \nAnyways, these same regular expressions are what the django URL resolver uses to match a URL to...
[ 5, 0 ]
[]
[]
[ "django", "python", "regex", "url" ]
stackoverflow_0005036885_django_python_regex_url.txt
Q: What is the history of the import statement? I know of two languages that use import statement: Java and Python. And we all know the import antigravity joke. Which language really introduced this statement? Was it one of the two, or another one altogether? When? A: import is just one way to specify dependency o...
What is the history of the import statement?
I know of two languages that use import statement: Java and Python. And we all know the import antigravity joke. Which language really introduced this statement? Was it one of the two, or another one altogether? When?
[ "import is just one way to specify dependency on some other class/module. Some way of specifying that has been present in many, many languages.\nIn fact import in Java and import in Python do two entirely different things:\n\nIn Java import only provides the ability to refer to a type (or field/method, if using imp...
[ 11, 1 ]
[]
[]
[ "import", "java", "programming_languages", "python" ]
stackoverflow_0005039972_import_java_programming_languages_python.txt
Q: comparing outputs from command.getoutput(cmd) I have the following code that is working apart from one problem. Im trying to compare the two outputs from commands.getoutput(cmd) but im getting syntax errors. I understand that this is probably inherently wrong, but could someone point what im doing wrong def Diff...
comparing outputs from command.getoutput(cmd)
I have the following code that is working apart from one problem. Im trying to compare the two outputs from commands.getoutput(cmd) but im getting syntax errors. I understand that this is probably inherently wrong, but could someone point what im doing wrong def DiffGenerator(): try: sys.argv[1] except: print "N...
[ "You might want to consider subprocess\nhttp://docs.python.org/library/subprocess.html\nsubprocess.Popen(['ls','-a'], stdout = subprocess.PIPE, stdin = subprocess.PIPE)\nresults = subprocess.communicate()[0] #where [0] is the stdout and [1] is the stderr\n\nEDIT: \nAlso can you please expand out your try except loo...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005039904_python.txt
Q: Querying csv with raw_input in Python I'm new to programming but I decided to take on python. I have this csv file about logged hours by users that looks roughly like this (but containing around 200 rows): User,Project,Hours User1,ProjectA,5 User1,ProjectB,10 User2,ProjectA,7 User2,ProjectB,12` I'd like ...
Querying csv with raw_input in Python
I'm new to programming but I decided to take on python. I have this csv file about logged hours by users that looks roughly like this (but containing around 200 rows): User,Project,Hours User1,ProjectA,5 User1,ProjectB,10 User2,ProjectA,7 User2,ProjectB,12` I'd like to extract data from it, through several ra...
[ "You could build a dict from the rows of the csv. \nteams = {}\nreader = csv.reader(open(\"loggedhours.csv\", \"rb\"))\nfor team in reader:\n teams[team[0]] = (team[1], team[2])\n\ndef print_teamnumbers():\n for user in teams:\n print \"%s: %s\" % (user, teams[user])\n\ndef specific_lookup(user_id):\n ...
[ 2, 2, 0 ]
[]
[]
[ "csv", "python", "raw_input" ]
stackoverflow_0005040119_csv_python_raw_input.txt
Q: Does a StopIteration exception automatically propagate upward through my iterator? I'm implementing an iterator in Python that wraps around another iterator and post-processes that iterator's output before passing it on. Here's a trivial example that takes an iterator that returns strings and prepends FILTERED BY ...
Does a StopIteration exception automatically propagate upward through my iterator?
I'm implementing an iterator in Python that wraps around another iterator and post-processes that iterator's output before passing it on. Here's a trivial example that takes an iterator that returns strings and prepends FILTERED BY MYITER: to each one: class MyIter(object): """A filter for an iterator that returns ...
[ "In this case the StopIteration exception will be propagated.\n", "What happened when you tried it? :-)\nBut yes, StopIteration exception are not special and will propagate until something traps them. The next() method does not trap them, and self.inner_iterator.next() will raise a StopIteration when there is not...
[ 1, 1, 1 ]
[]
[]
[ "iterator", "python", "termination" ]
stackoverflow_0005039087_iterator_python_termination.txt
Q: How do I convert characters like ":" to ":" in python? Possible Duplicate: Convert XML/HTML Entities into Unicode String in Python In html sources, there are tons of chars like "&# 58;" or "&# 46;" (have to put space between &# and numbers or these chars would be considered as ":" or "."), my questions is, how d...
How do I convert characters like ":" to ":" in python?
Possible Duplicate: Convert XML/HTML Entities into Unicode String in Python In html sources, there are tons of chars like "&# 58;" or "&# 46;" (have to put space between &# and numbers or these chars would be considered as ":" or "."), my questions is, how do you convert them to what they supposed to be in python? I...
[ "I am not sure there is built-in library or not, but here is quick and dirty way to do with regex\n>>> import re\n>>> re.sub(\"&#(\\d+);\",lambda x:unichr(int(x.group(1),10)),\"&#58; or &#46;\")\nu': or .'\n\n", "Something like this will handle most entity definitions (assuming Python 2.x). It handles decimal, he...
[ 5, 2 ]
[]
[]
[ "character_encoding", "python", "special_characters" ]
stackoverflow_0005040914_character_encoding_python_special_characters.txt
Q: MySQLDB code to create wordpress DB tables I need to create wordpress databases using mysqldb connected to a mysql server but using the SQLAlchemy code. The SQL for the table is as follows: CREATE TABLE IF NOT EXISTS `wp_links` ( `link_id` bigint(20) unsigned NOT NULL auto_increment, `link_url` varchar(255) NO...
MySQLDB code to create wordpress DB tables
I need to create wordpress databases using mysqldb connected to a mysql server but using the SQLAlchemy code. The SQL for the table is as follows: CREATE TABLE IF NOT EXISTS `wp_links` ( `link_id` bigint(20) unsigned NOT NULL auto_increment, `link_url` varchar(255) NOT NULL default '', `link_name` varchar(255) NO...
[ "Looking at the MYSQL documentation:\n\nKEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.\n\nso therefore I would look at\nhttp://www.sqlalchemy.org/docs/core/sch...
[ 0 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0005041168_mysql_python_sqlalchemy.txt