content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python virtualbox API Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address A: Looking into some PyVB Source and API doc would be good idea. A: This might sound really snide but: Let...
Python virtualbox API
Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address
[ "Looking into some PyVB Source and API doc would be good idea.\n", "This might sound really snide but: Let me Google that for you\n... though I have to admit that I had to try the fourth link from my results to find something that looked like it might actually be useful. Also it looks like you'll get quite a bit...
[ 1, 1 ]
[]
[]
[ "python", "virtualbox" ]
stackoverflow_0002212286_python_virtualbox.txt
Q: where does defined the Table 'test.sphinx_test_file'? look the end line:ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist") Traceback (most recent call last): File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 280, in run self.finish_response() File "D:\Python2...
where does defined the Table 'test.sphinx_test_file'?
look the end line:ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist") Traceback (most recent call last): File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 280, in run self.finish_response() File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line ...
[ "Did you run syncdb after adding the app (I'm guessing the app is named sphinx) to your settings.py?\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002211579_django_python.txt
Q: How can I get a total count of a model's related objects and the model's children's related objects? In Django, I've got a Checkout model, which is a ticket for somebody checking out equipment. I've also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the check...
How can I get a total count of a model's related objects and the model's children's related objects?
In Django, I've got a Checkout model, which is a ticket for somebody checking out equipment. I've also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the checkout belongs to an OrganizationalUnit on our campus. The OrganizationalUnit has a self relation, so several...
[ "What you need is a recursive function that traverse OrganizationalUnit relation tree and gets number of related Checkouts for each OrganizationalUnit. So your code will look like this:\ndef count_checkouts(ou):\n checkout_count = ou.checkouts.count()\n for kid in ou.children.all():\n checkout_count += co...
[ 3, 3, 0 ]
[]
[]
[ "django", "django_select_related", "many_to_many", "models", "python" ]
stackoverflow_0002150644_django_django_select_related_many_to_many_models_python.txt
Q: virtualbox and python API 0 vote down I have installed virtualbox . but i cant import the module xpcom. but the synaptic package shows that it is installed. what could be wrong? -ASK A: To be able to import xpcom, you would need to install pyxpcom extension, and build instructions are here. In Synaptic Package ...
virtualbox and python API
0 vote down I have installed virtualbox . but i cant import the module xpcom. but the synaptic package shows that it is installed. what could be wrong? -ASK
[ "To be able to import xpcom, you would need to install pyxpcom extension, and build instructions are here.\nIn Synaptic Package Manager, it would be python-xpcom\n" ]
[ 1 ]
[]
[]
[ "python", "xpcom" ]
stackoverflow_0002212706_python_xpcom.txt
Q: Convention for checking the existence of a Django model? What is the accepted way of checking a model's existence in a Django app? I've seen this method used: def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: ret...
Convention for checking the existence of a Django model?
What is the accepted way of checking a model's existence in a Django app? I've seen this method used: def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: return False Is there a built-in function suited for this purpos...
[ "Bare excepts should not be used. Instead the model's DoesNotExist inner exception or django.core.exceptions.ObjectDoesNotExist should be caught.\nBeyond that, either this or using len(SomeModel.objects.filter(...)) are acceptable.\n", "As an additional note, you could make a general purpose function out of it wi...
[ 2, 2, 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002211530_django_django_models_python.txt
Q: Python IRC Client When I run the script: import socket from time import strftime time = strftime("%H:%M:%S") irc = 'irc.tormented-box.net' port = 6667 channel = '#tormented' sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) print sck.recv(4096) sck.send('NICK supaBOT\r\n') sck.send...
Python IRC Client
When I run the script: import socket from time import strftime time = strftime("%H:%M:%S") irc = 'irc.tormented-box.net' port = 6667 channel = '#tormented' sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) print sck.recv(4096) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT ...
[ "This means that message has no spaces in it, so when it's split by a space, you get a list containing a single element - you are trying to access the second element of this list. You should insert a check for this case.\nEDIT: In reply to your comment: how you add the check depends on the logic of your program. Th...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002212727_python.txt
Q: Web CMS Performance: pages/second (Joomla, Drupal, Plone, WP) Note: I am not into web programming, so forgive my ignorance in case the question is trivial. Also, please don't comment about "how flawed" the out-of-box comparison of these products is. The question is not about how they compete against each other, ra...
Web CMS Performance: pages/second (Joomla, Drupal, Plone, WP)
Note: I am not into web programming, so forgive my ignorance in case the question is trivial. Also, please don't comment about "how flawed" the out-of-box comparison of these products is. The question is not about how they compete against each other, rather about the reason behind the incredible slowness of ALL of them...
[ "\nA CMS should just query a DB and churn out the data packed into nice templates. \n\nNot so much. Major, modern CMS systems are incredibly complex beasts. A typical page isn't merely body text and a title, but also dynamic category-based content queries that aggregate info across many site areas; not to mention s...
[ 3, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "benchmarking", "content_management_system", "php", "python" ]
stackoverflow_0002120443_benchmarking_content_management_system_php_python.txt
Q: What is a nicer alternative to a namedtuples _replace? Take this code: >>> import urlparse >>> parts = urlparse.urlparse('http://docs.python.org/library/') >>> parts = parts._replace(path='/3.0'+parts.path) parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is the...
What is a nicer alternative to a namedtuples _replace?
Take this code: >>> import urlparse >>> parts = urlparse.urlparse('http://docs.python.org/library/') >>> parts = parts._replace(path='/3.0'+parts.path) parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do: >>> parts = parts[:2]...
[ "The reason methods of namedtuple start with an initial underscore is only to prevent name collisions. They should not be considered to be for internal use only:\n\nTo prevent conflicts with field names, the method and attribute names start with an underscore.\n\n" ]
[ 22 ]
[]
[]
[ "namedtuple", "python" ]
stackoverflow_0002213102_namedtuple_python.txt
Q: A reliable way to determine if ntfs permissions were inherited I have a somewhat obscure question here. What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited. How I tried to solve this: using winapi bindings for python (win32security module, ...
A reliable way to determine if ntfs permissions were inherited
I have a somewhat obscure question here. What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited. How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just th...
[ "You can use the .Net framework \nSystem.Security.AccessControl\n\nThis covers ACL and DACL and SACL.\n", "I think the original poster is seeing behavior detailed in\nThis newsgroup posting\nNote that the control flags set on the container can change simply by un-ticking and re-ticking the inheritance box in the ...
[ 1, 1, 0 ]
[]
[]
[ "acl", "file_permissions", "ntfs", "python", "winapi" ]
stackoverflow_0000910696_acl_file_permissions_ntfs_python_winapi.txt
Q: Load blob image data into QPixmap I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field ...
Load blob image data into QPixmap
I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database: def dump_image(imgfile...
[ "You can use the QImage.fromData static method to load an image from a string and then convert it to a pixmap:\n image_data = get_image_data_from_blob()\n qimg = QtGui.QImage.fromData(image_data)\n pixmap = QtGui.QPixmap.fromImage(qimg)\n\n", "The approach suggested by Ants Aasma works and actually it is also OK ...
[ 11, 4, 0 ]
[]
[]
[ "blob", "image", "pyqt", "python", "qpixmap" ]
stackoverflow_0001300908_blob_image_pyqt_python_qpixmap.txt
Q: Python: Why is IDLE so slow? IDLE is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger. However, code executed under IDLE is insanely slow. By insanely I mean 3 orders of magnitude slow: bash time echo "for i in r...
Python: Why is IDLE so slow?
IDLE is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger. However, code executed under IDLE is insanely slow. By insanely I mean 3 orders of magnitude slow: bash time echo "for i in range(10000): print 'x'," | python ...
[ "The problem is the text output not the debugger.\nI just tried it on my Q6600 (3GHz overclocked) System and my numbers are even worse.\nBut its easy to see that they are going down the more output text is added.\nI tried to run it with \n1000 iterations => 7,8 sec\n2000 iterations => 28,5 sec\n3000 iterations => 7...
[ 31, 10 ]
[]
[]
[ "performance", "python", "python_idle" ]
stackoverflow_0002212722_performance_python_python_idle.txt
Q: Django model class methods for predefined values I'm working on some Django-code that has a model like this: class Status(models.Model): code = models.IntegerField() text = models.CharField(maxlength=255) There are about 10 pre-defined code/text-pairs that are stored in the database. Scattered around th...
Django model class methods for predefined values
I'm working on some Django-code that has a model like this: class Status(models.Model): code = models.IntegerField() text = models.CharField(maxlength=255) There are about 10 pre-defined code/text-pairs that are stored in the database. Scattered around the codebase I see code like this: status = Status.obj...
[ "You should perhaps implement this by defining a custom manager for your class, and adding two manager methods on that manager (which I believe is the preferred way for adding table-level functionality for any model). However, another way of doing it is by throwing in two class methods on your class that query and ...
[ 49 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002213309_django_django_models_python.txt
Q: Hooking str.__getitem__ in Python Is there a way of hooking str.__getitem__? Example: I'd like to be capable of do: >>> "this is a string"[[1,3,4]] 'hs ' passing a list to [] and get the items in that list. A more realistic example: class STR(str): pass class INT(int): pass It's easy to make that STR("a...
Hooking str.__getitem__ in Python
Is there a way of hooking str.__getitem__? Example: I'd like to be capable of do: >>> "this is a string"[[1,3,4]] 'hs ' passing a list to [] and get the items in that list. A more realistic example: class STR(str): pass class INT(int): pass It's easy to make that STR("a string")[1] or STR("a string")[INT(1)]...
[ "Why hook an often-used internal function when you can \ndef get_characters (s, l):\n return \"\".join(s[i] for i in l)\n\n>>> get_characters(\"this is a string\", [1,3,4])\n\"hs \"\n\n", "Methods on objects defined in C cannot be monkeypatched. The best you can do is to use an external function to complete the ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002213325_python.txt
Q: Mac 10.6 Universal Binary scipy: cephes/specfun "_aswfa_" symbol not found I can't get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1. My python setup With the help of this answer, I built a 32/64 bit intel universal binary of python 2.6...
Mac 10.6 Universal Binary scipy: cephes/specfun "_aswfa_" symbol not found
I can't get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1. My python setup With the help of this answer, I built a 32/64 bit intel universal binary of python 2.6.4 with the intention of using the arch command to select between the architectu...
[ "Have you tried using scipy compiled using macports?\nsudo port install scipy +universal\n\n(of course you must have the rest of the chain, python, py26-numpycompiled with the same option)\nI get:\n$ arch -x86_64 /opt/local/bin/python -c \"import scipy.interpolate; print 'success'\"\nsuccess\n\n$ arch -i386 /opt/lo...
[ 3, 1 ]
[]
[]
[ "architecture", "osx_snow_leopard", "python", "scipy", "universal_binary" ]
stackoverflow_0002155986_architecture_osx_snow_leopard_python_scipy_universal_binary.txt
Q: Why str has no __radd__ method in Python? str has other methods like __rmod__, __rsub__ or __rmul__ int did have a __radd__ method Weird, and I'd like to know why. Example radd beeing called when first term HAS add method: >>> class STR(str): ... def __radd__(self, other): ... print "jeje" ... ...
Why str has no __radd__ method in Python?
str has other methods like __rmod__, __rsub__ or __rmul__ int did have a __radd__ method Weird, and I'd like to know why. Example radd beeing called when first term HAS add method: >>> class STR(str): ... def __radd__(self, other): ... print "jeje" ... return other.__add__(self) ... >>> 'aa...
[ "__radd__ is used when the first term of the addition does not implement __add__. In the case of int, addition is well defined by its mathematical definition, and so int tries to coerce the other term into a number. \nwith str, there is no such well defined meaning, and the developers of python have decided that ...
[ 5, 2 ]
[]
[]
[ "implementation", "python" ]
stackoverflow_0002213329_implementation_python.txt
Q: How to store python classes into a database with Django? I have two files: choices.py class SomeChoice: name = u"lorem" class AnotherChoice: name = u"ipsum" # etc... models.py from django.db import models import choices class SomeModel(models.Model): CHOICES = ( (1, choices.SomeChoice.name)...
How to store python classes into a database with Django?
I have two files: choices.py class SomeChoice: name = u"lorem" class AnotherChoice: name = u"ipsum" # etc... models.py from django.db import models import choices class SomeModel(models.Model): CHOICES = ( (1, choices.SomeChoice.name), (2, choices.AnotherChoice.name), # etc... ...
[ "You could use pickle to store instances of the classes, but then it would be uglier, and you don't need to store the classes in the database in this case, so don't (you want to avoid hitting the database as much as possible).\nTo avoid repeating the IDs in two places, you could change the code to something like th...
[ 4, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "storing_information" ]
stackoverflow_0002213402_database_django_django_models_python_storing_information.txt
Q: Access a subset of functions of a Python class Using a class that has an xmlrpc proxy as one of it's object's properties def __init__(self): self.proxy = ServerProxy(...) # ... I'm trying to ease the use of some of the proxy's functions. Only a subset of the proxy functions are supposed to be used and I t...
Access a subset of functions of a Python class
Using a class that has an xmlrpc proxy as one of it's object's properties def __init__(self): self.proxy = ServerProxy(...) # ... I'm trying to ease the use of some of the proxy's functions. Only a subset of the proxy functions are supposed to be used and I thus thought of creating a set of tiny wrapper functi...
[ "I'm not 100% sure if this is what you want, but it works:\ndef proxy_wrapper(name, docstring):\n def wrapper(self, *args, **kwargs):\n return self.proxy.__getattribute__(name)(*args, **kwargs)\n wrapper.__doc__ = docstring\n wrapper._is_wrapper = True\n return wrapper\n\nclass Something(object):...
[ 3, 2 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0002213289_python_xml_rpc.txt
Q: Reading request parameters in Python I am very new to python and having to get into this stuff for a simple program to integrate with an ASP.NET application that I am building. The pseudo code is as follows. Get two parameters from request. (A ASP.NET will be calling this url by POST and sending two parameters) I...
Reading request parameters in Python
I am very new to python and having to get into this stuff for a simple program to integrate with an ASP.NET application that I am building. The pseudo code is as follows. Get two parameters from request. (A ASP.NET will be calling this url by POST and sending two parameters) Internally execute some business logic and ...
[ "Here is a good beginner's tutorial for mod_python.\nAs far as I understand your question you have a mod_python-based script and you want to read a POST parameter. Therefore you only have to use the form object which is automatically provided by mod_python:\nmyparameter = form.getfirst(\"name_of_the_post_parameter\...
[ 5, 0 ]
[]
[]
[ "mod_python", "parameters", "python", "request" ]
stackoverflow_0002213191_mod_python_parameters_python_request.txt
Q: Changing the hour with datetime.replace() in python Given that foo is a valid datetime object in python, One can change the hour represented in a datestamp (foo) by doing something something like: foo2 = foo.replace( hour=5 ) Rather then replacing the hour with a particular value ( as is done above )..is it po...
Changing the hour with datetime.replace() in python
Given that foo is a valid datetime object in python, One can change the hour represented in a datestamp (foo) by doing something something like: foo2 = foo.replace( hour=5 ) Rather then replacing the hour with a particular value ( as is done above )..is it possible to increment the time in foo by say, 5 hours ? Som...
[ "That's what timedelta is for:\n>>> import datetime\n>>> d = datetime.datetime(2010, 12, 25, 18, 25)\n>>> d + datetime.timedelta(hours = 8)\ndatetime.datetime(2010, 12, 26, 2, 25)\n\n" ]
[ 26 ]
[]
[]
[ "datetime", "macos", "python" ]
stackoverflow_0002213682_datetime_macos_python.txt
Q: How to avoid computation every time a python module is reloaded I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I sa...
How to avoid computation every time a python module is reloaded
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload do...
[ "Just to clarify: the code in the body of a module is not executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.\nHowever, if your problem is the time it t...
[ 17, 4, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0000195626_nltk_python.txt
Q: how do people normally deal with class variables in django? I can't see any provision for this in the django docs, so how do people go about doing this. My specific case is this. I have a shopping cart, each cart instance has an invoice number field, however the invoice number is only generated if the cart goes to...
how do people normally deal with class variables in django?
I can't see any provision for this in the django docs, so how do people go about doing this. My specific case is this. I have a shopping cart, each cart instance has an invoice number field, however the invoice number is only generated if the cart goes to a paid status, so not all shopping cart instances will have an i...
[ "The default primary key will already be a unique monotonic integer (even in SQLite if you don't delete any records), so you can just use that for it.\n", "You can create a field in a model and state it as primary key or use your current primary key if you are migrating a legacy database primary_key=True.\nDjango...
[ 1, 0, 0 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0002213595_django_models_python.txt
Q: pyparsing question This code works: from pyparsing import * zipRE = "\d{5}(?:[-\s]\d{4})?" fooRE = "^\!\s+.*" zipcode = Regex( zipRE ) foo = Regex( fooRE ) query = ( zipcode | foo ) tests = [ "80517", "C6H5OH", "90001-3234", "! sfs" ] for t in tests: try: results = query.parseString( t ) ...
pyparsing question
This code works: from pyparsing import * zipRE = "\d{5}(?:[-\s]\d{4})?" fooRE = "^\!\s+.*" zipcode = Regex( zipRE ) foo = Regex( fooRE ) query = ( zipcode | foo ) tests = [ "80517", "C6H5OH", "90001-3234", "! sfs" ] for t in tests: try: results = query.parseString( t ) print t,"->", results ...
[ "You could use zipcode and foo separately, so that you know which one the string matches.\nzipresults = zipcode.parseString( t )\nfooresults = foo.parseString( t )\n\n", "I do not have the pyparsing module, but Regex must be a class, not a function.\nWhat you can do is subclass from it and override methods as req...
[ 3, 2, 2 ]
[]
[]
[ "parsing", "pyparsing", "python", "text_parsing" ]
stackoverflow_0002212860_parsing_pyparsing_python_text_parsing.txt
Q: SQL LIKE in Django/Python I'm trying to run a query like this: SELECT * FROM MyTable WHERE FirstName LIKE '%[user inputted value here]%' OR LastName LIKE '%[that same user inputted value]%' AND UserID = some number When I run the query using cursor.execute(), the inputted values ar...
SQL LIKE in Django/Python
I'm trying to run a query like this: SELECT * FROM MyTable WHERE FirstName LIKE '%[user inputted value here]%' OR LastName LIKE '%[that same user inputted value]%' AND UserID = some number When I run the query using cursor.execute(), the inputted values are going to be escaped and quote...
[ "Use foo__contains=realvaluehere in your queries.\n", "Hmm, looks like I overestimated the escapy-ness of the API. This works exactly how I want it to\n# add wildcards to query, these are **not** escaped\nq = \"%\" + q + \"%\"\ncursor = connection.cursor()\ncursor.execute(\"SELECT * \n FROM MyTable...
[ 2, 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0002211695_django_python_sql.txt
Q: How can _meta.local_fields not match the table schema in the database? I'm completely confused about why _meta.local_fields returns more fields than the database table contains. The User model inherits from contrib.auth.models.User. $ mysql -u user -p database Enter password: Reading table information for com...
How can _meta.local_fields not match the table schema in the database?
I'm completely confused about why _meta.local_fields returns more fields than the database table contains. The User model inherits from contrib.auth.models.User. $ mysql -u user -p database Enter password: Reading table information for completion of table and column names You can turn off this feature to get a q...
[ "It would have been helpful if you showed the Django model that is related to this problem. From the field names in your SQL this model appears to inherit from contrib.auth.models.User, is that true? If so, did you happen to duplicate a field name defined in the User model?\nUpdate: To put it more bluntly, I was as...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002213716_django_django_models_python.txt
Q: Is everything greater than None? Is there a Python built-in datatype, besides None, for which: >>> not foo > None True where foo is a value of that type? How about Python 3? A: None is always less than any datatype in Python 2 (see object.c). In Python 3, this was changed; now doing comparisons on things withou...
Is everything greater than None?
Is there a Python built-in datatype, besides None, for which: >>> not foo > None True where foo is a value of that type? How about Python 3?
[ "None is always less than any datatype in Python 2 (see object.c).\nIn Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a TypeError. From the 3.0 \"what's new\" updates:\n\nPython 3.0 has simplified the rules for ordering comparisons:\nThe ordering compariso...
[ 96, 30 ]
[]
[]
[ "python", "python_datamodel" ]
stackoverflow_0002214194_python_python_datamodel.txt
Q: What's the pythonic way of declaring variables? Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs becau...
What's the pythonic way of declaring variables?
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name? How would you av...
[ "It's a silly artifact of Python's inspiration by \"teaching languages\", and it serves to make the language more accessible by removing the stumbling block of \"declaration\" entirely. For whatever reason (probably represented as \"simplicity\"), Python never gained an optional stricture like VB's \"Option Explici...
[ 15, 12, 9, 5, 4, 3, 2 ]
[ "Variable declaration does not prevent bugs. Any more than lack of variable declaration causes bugs.\nVariable declarations prevent one specific type of bug, but it creates other types bugs.\nPrevent. Writing code where there's an attempt to set (or change) a variable with the wrong type of data.\nCauses. Stupid...
[ -1 ]
[ "python" ]
stackoverflow_0002213531_python.txt
Q: (django initial setup) Django installation is redirecting all traffic to django page, fix? I'm a complete newbie to Django. I've been trying to get it working on my Ubuntu server. everytime someone my server, it redirects to the "Congratulations on your first Django-powered page." It completely ignores the index.h...
(django initial setup) Django installation is redirecting all traffic to django page, fix?
I'm a complete newbie to Django. I've been trying to get it working on my Ubuntu server. everytime someone my server, it redirects to the "Congratulations on your first Django-powered page." It completely ignores the index.html file in the www directory. Why is that? Is there a away to make it so that it only goes to t...
[ "\n\"It completely ignores the index.html\n file in the www directory. Why is\n that?\"\n\nBecause you installed django and django takes over from that point. You should probably change the <Location> path to \"testproject\" instead of \"/\" as obviously the latter means root/homepage. Though I'm not sure this wi...
[ 1 ]
[]
[]
[ "apache", "apache_config", "django", "mod_python", "python" ]
stackoverflow_0002214645_apache_apache_config_django_mod_python_python.txt
Q: Django: Can the value of ForeignKey be None? I have a model called SimplePage in which I have this line: category = models.ForeignKey('Category', related_name='items', blank=True, null=True) I assumed this will allow me to have SimplePage instances that do not have a Category. But for...
Django: Can the value of ForeignKey be None?
I have a model called SimplePage in which I have this line: category = models.ForeignKey('Category', related_name='items', blank=True, null=True) I assumed this will allow me to have SimplePage instances that do not have a Category. But for some reason, when I try to create a SimplePage in...
[ "Could it possibly be that you added the null=True attribute after doing the syncdb for that model? Django won't change database tables, only create them. Check in your database if NULL is allowed for that column and change it manually.\nEdit: starting with Django 1.7, this answer and the comments are not really va...
[ 9 ]
[]
[]
[ "database", "django", "foreign_keys", "python" ]
stackoverflow_0002214909_database_django_foreign_keys_python.txt
Q: Secure Python intepreter? Is there a secure Python intepreter? Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc. Does such a secure Python VM exist? A: I know of ...
Secure Python intepreter?
Is there a secure Python intepreter? Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc. Does such a secure Python VM exist?
[ "I know of no such \"secure interpreter\" that is openly distributed (obviously Google has one that it uses in App Engine, though with somewhat different restrictions from those you desire, e.g., certain files can be opened, in a read-only way). There are some claims for it, though, e.g. here, though I can't verif...
[ 7, 2, 2, 1, 1, 0 ]
[ "I've been toying with this lately. My requirements include Python 3.x which immediately takes solutions like Jython and IronPython off the table. I'd be hesitant to take that route anyway, as I've never trusted user-mode language VMs.\nThat being the case, for my purposes the best solution so far is to take it out...
[ -1, -1 ]
[ "interpreter", "python", "security", "virtual_machine" ]
stackoverflow_0001695014_interpreter_python_security_virtual_machine.txt
Q: How to get rid of pygame surfaces? In the following code, there is not just one circle on the screen at any given point in time. I want to fix this to make it so that it looks like there is only one circle, instead of leaving a smudge trail where ever the mouse cursor has been. import pygame,sys from pygame.locals...
How to get rid of pygame surfaces?
In the following code, there is not just one circle on the screen at any given point in time. I want to fix this to make it so that it looks like there is only one circle, instead of leaving a smudge trail where ever the mouse cursor has been. import pygame,sys from pygame.locals import * pygame.init() screen = pygame...
[ "You need to specifically erase the circle before you blit it again. Depending on how complicated your scene is, you may have to try different methods. Generally what I do is have a \"background\" surface that a blit to the screen every frame and then blit the sprites/other surfaces in their new positions (blits in...
[ 6 ]
[]
[]
[ "geometry_surface", "pygame", "python" ]
stackoverflow_0002215227_geometry_surface_pygame_python.txt
Q: Parsing XML with BeautifulSoup and handling missing element I am using BeautifulSoup to parse XML: xml = """<person> <first_name>Matt</first_name> </person>""" soup = BeautifulStoneSoup(xml) first_name = soup.find('first_name').string last_name = soup.find('last_name').string But I have a problem when there is n...
Parsing XML with BeautifulSoup and handling missing element
I am using BeautifulSoup to parse XML: xml = """<person> <first_name>Matt</first_name> </person>""" soup = BeautifulStoneSoup(xml) first_name = soup.find('first_name').string last_name = soup.find('last_name').string But I have a problem when there is no last_name, because it chokes. Sometimes the feed has it, and s...
[ "last_name = soup.find('last_name') and soup.find('last_name').string\n\nVery silly, but it does meet your equally silly stated restriction (no if). A bit less silly:\nlast_name_node = soup.find('last_name')\nlast_name = last_name_node and last_name_node.string\n\nand:\nlast_name = getattr(soup.find('last_name'), ...
[ 4 ]
[]
[]
[ "beautifulsoup", "exception_handling", "python", "xml" ]
stackoverflow_0002215429_beautifulsoup_exception_handling_python_xml.txt
Q: Django - Determine field type of a variable passed to a template tag I would like to write a Django template tag to which I can pass a variable. I would like the template tag to behave differently depending on what type of model field the variable was derived from (CharField, BooleanField, IntegerField, etc.) as w...
Django - Determine field type of a variable passed to a template tag
I would like to write a Django template tag to which I can pass a variable. I would like the template tag to behave differently depending on what type of model field the variable was derived from (CharField, BooleanField, IntegerField, etc.) as well as other information used in the field's definition (max_length, etc.)...
[ "You can use python's type function to determine the class type.\nif type(field) == models.CharField:\n #CharField specific code\nelif type(field) == models.IntegerField:\n #IntegerField specific code\n\n" ]
[ 5 ]
[]
[]
[ "django", "field", "python", "templatetags", "variables" ]
stackoverflow_0002215484_django_field_python_templatetags_variables.txt
Q: efficiently knowing if intersection of two list is empty or not, in python Suppose I have two lists, L and M. Now I want to know if they share an element. Which would be the fastest way of asking (in python) if they share an element? I don't care which elements they share, or how many, just if they share or not. F...
efficiently knowing if intersection of two list is empty or not, in python
Suppose I have two lists, L and M. Now I want to know if they share an element. Which would be the fastest way of asking (in python) if they share an element? I don't care which elements they share, or how many, just if they share or not. For example, in this case L = [1,2,3,4,5,6] M = [8,9,10] I should get False, a...
[ "Or more concisely\nif set(L) & set(M):\n # there is an intersection\nelse:\n # no intersection\n\nIf you really need True or False\nbool(set(L) & set(M))\n\nAfter running some timings, this seems to be a good option to try too\nm_set=set(M)\nany(x in m_set for x in L)\n\nIf the items in M or L are not hasha...
[ 57, 5, 3 ]
[ "That's the most generic and efficient in a balanced way I could come up with (comments should make the code easy to understand):\nimport itertools, operator\n\ndef _compare_product(list1, list2):\n \"Return if any item in list1 equals any item in list2 exhaustively\"\n return any(\n itertools.starmap(...
[ -1 ]
[ "intersection", "list", "performance", "python" ]
stackoverflow_0002197482_intersection_list_performance_python.txt
Q: Difference Between Modulus Implementation in Python Vs Java I've noticed differing implementations of the modulus operator in Python and Java. For example, in Python: >>> print -300 % 800 >>> 500 Whereas in Java: System.out.println(-300 % 800); -300 This caught me off guard, since I thought something as basic as...
Difference Between Modulus Implementation in Python Vs Java
I've noticed differing implementations of the modulus operator in Python and Java. For example, in Python: >>> print -300 % 800 >>> 500 Whereas in Java: System.out.println(-300 % 800); -300 This caught me off guard, since I thought something as basic as modulus was universally interpreted the same way. I'm a fan of P...
[ "I prefer C's interpretation (also used in Python), where % is indeed a modulus operator. Good discussion in the wikipedia page and the links from it (including one bit about why taking instead the sign of the dividend can lead to one silly bug unless one's careful;-).\n", "Now try this:\n>>> print 300 % -800\n-...
[ 6, 4, 1, 0 ]
[]
[]
[ "java", "modulo", "python" ]
stackoverflow_0002215318_java_modulo_python.txt
Q: Matplotlib: Formatting dates on the x-axis in a 3D Bar graph Given this 3D bar graph sample code, how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis_date() function without success. I also tried using plot_date(), which doesn't appear to work fo...
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph
Given this 3D bar graph sample code, how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis_date() function without success. I also tried using plot_date(), which doesn't appear to work for 3D bar graphs. Here is a modified version of the sample code to ...
[ "There might be some confusion here, the Axes3D has the properties w_xaxis, w_yaxis and w_zaxis for the axises instead of the usual x-axis, y-axis, etc.\nTested in python 3.8.11, matplotlib 3.4.3\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.dates a...
[ 16 ]
[]
[]
[ "data_analysis", "graph", "matplotlib", "numpy", "python" ]
stackoverflow_0002195983_data_analysis_graph_matplotlib_numpy_python.txt
Q: Conditional output in Sphinx Documentation I'm writing some documentation with Sphinx and I'd like to print out a certain block of text only for HTML documentation, not for LaTeX documentation. Something tells me I should be able to do this with sphinx.ext.ifconfig but I can't figure out how. Does anyone know how ...
Conditional output in Sphinx Documentation
I'm writing some documentation with Sphinx and I'd like to print out a certain block of text only for HTML documentation, not for LaTeX documentation. Something tells me I should be able to do this with sphinx.ext.ifconfig but I can't figure out how. Does anyone know how to do this?
[ "No extension is required. Just use the only directive. \n(old link, from original 2010 post)\nhttps://web.archive.org/web/20100129001557/http://sphinx.pocoo.org/markup/misc.html#including-content-based-on-tags\n(latest link)\nhttps://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#including-con...
[ 28 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002215518_python_python_sphinx.txt
Q: In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)? This is Python question. I have a variable A >>> A <Swig Object of type 'uint16_t *' at 0x8c66fa0> >>> help(A) class PySwigObject(object) Swig object carries a C/C++ instance pointer The instance referred by A is a contig...
In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)?
This is Python question. I have a variable A >>> A <Swig Object of type 'uint16_t *' at 0x8c66fa0> >>> help(A) class PySwigObject(object) Swig object carries a C/C++ instance pointer The instance referred by A is a contiguous array uint16[3] and the problem is to gain access to that array from Python. In Python, h...
[ "After more reading and trying stuff out, the answers are as follows:\n\n1. The wrapped pointer in PySwigObject A is available as A.__long__() .\n\n2. A raw pointer can be cast into an indexable type using ctypes as follows\n\nimport ctypes\npA = ctypes.cast( A.__long__(), ctypes.POINTER( ctypes.c_uint16 ) )\n\nTh...
[ 8 ]
[]
[]
[ "ctypes", "python", "swig" ]
stackoverflow_0002209395_ctypes_python_swig.txt
Q: Are there any free alternatives to the Ranorex library (Python, Windows)? I am interested in the Python one. I wish to automate some GUI under Windows. What is the best open source library for that with no strings attached? Thanks. A: Try pyWinAuto. A: There's WATSUP, but I've not tried it yet myself. I've als...
Are there any free alternatives to the Ranorex library (Python, Windows)?
I am interested in the Python one. I wish to automate some GUI under Windows. What is the best open source library for that with no strings attached? Thanks.
[ "Try pyWinAuto.\n", "There's WATSUP, but I've not tried it yet myself.\nI've also heard of pyWinAuto, although the link I have is to pyWinAuto on SourceForge.\n" ]
[ 2, 1 ]
[]
[]
[ "automation", "python", "user_interface", "windows" ]
stackoverflow_0002215154_automation_python_user_interface_windows.txt
Q: What is this traceback error in Python? Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/ea/ea-repos/hell/life/views.py" in linkedin_auth 137. token = oauth_l...
What is this traceback error in Python?
Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/ea/ea-repos/hell/life/views.py" in linkedin_auth 137. token = oauth_linkedin.get_unauthorised_request_token() File...
[ "Look at this answer to see if it helps you:\nhttplib CannotSendRequest error in WSGI\n" ]
[ 1 ]
[]
[]
[ "django", "oauth", "python", "url" ]
stackoverflow_0002216259_django_oauth_python_url.txt
Q: PostgreSQL problem in Django I have a Django application and I'm using postgres. I try to execute the bollowing line in one of my tests: print BillingUser.objects.all() And I get the following error: "current transaction is aborted, commands ignored until end of transaction block." My postresql log: ERROR: du...
PostgreSQL problem in Django
I have a Django application and I'm using postgres. I try to execute the bollowing line in one of my tests: print BillingUser.objects.all() And I get the following error: "current transaction is aborted, commands ignored until end of transaction block." My postresql log: ERROR: duplicate key value violates unique ...
[ "Ok... looking at the PostgreSQL log, it does look that you are doing a wrong insert that will abort the transaction... now, looking at your code I think the problems lies here:\nat lines 78-81\n currency = Currency.objects.all()[2]\n if not Wallet.objects.filter(user=user):\n wallet = Wallet(user=user...
[ 1, 0, 0 ]
[]
[]
[ "django", "postgresql", "python", "sql" ]
stackoverflow_0002175615_django_postgresql_python_sql.txt
Q: wxpython GUI having static Japanese text and chinese static text We want to support localization of the static text (labels, button labels, etc) to Japanese and Chinese in wxpython. We want only static text within the GUI elements to be changed, hard coding of Japanese or Chinese characters in the label(static tex...
wxpython GUI having static Japanese text and chinese static text
We want to support localization of the static text (labels, button labels, etc) to Japanese and Chinese in wxpython. We want only static text within the GUI elements to be changed, hard coding of Japanese or Chinese characters in the label(static text fields) would do the work for us. Any help on how to pursue this wou...
[ "see: wx.GetTranslation\nhttp://wiki.wxpython.org/Internationalization\nWhat I do, is use _ = wx.GetTranslation at the top of my scripts, and enclose any strings in _(\"My String\")\nI use this batch script: http://code.google.com/p/gui2exe/source/browse/trunk/scripts/gen_lang to run the mki18n.py script found on ...
[ 0 ]
[]
[]
[ "python", "unicode", "wxpython" ]
stackoverflow_0002214694_python_unicode_wxpython.txt
Q: Adding values in a tuple that is in a list in python I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)] Is there a function that can sum up the values in the list ...
Adding values in a tuple that is in a list in python
I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)] Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18....
[ ">>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n\n>>> sum(map(sum,l))\n18\n\n>>> l[0]=(1,2,3,)\n>>> l\n[(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]\n>>> sum(map(sum,l))\n23\n\n"...
[ 7, 4, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0002216450_list_python_tuples.txt
Q: How to make a relation between tables using SQLAlchemy? Using SQLAlchemy, given tables such as these: locations_table = Table('locations', metadata, Column('id', Integer, primary_key=True), Column('name', Text), ) players_table = Table('players', metadata, Column('id', Integer, ...
How to make a relation between tables using SQLAlchemy?
Using SQLAlchemy, given tables such as these: locations_table = Table('locations', metadata, Column('id', Integer, primary_key=True), Column('name', Text), ) players_table = Table('players', metadata, Column('id', Integer, primary_key=True), Column('email', Text), C...
[ "Use sqlalchemy's relation feature:\nhttp://www.sqlalchemy.org/docs/ormtutorial.html#building-a-relation\n", "This should work for you:\nmapper(Player, players_table, properties={'location'=relation(Location, uselist=False, backref=backref('players'))})\nThat way you can access the location directly as you won't ...
[ 3, 1 ]
[]
[]
[ "orm", "python", "relation", "sqlalchemy" ]
stackoverflow_0002216887_orm_python_relation_sqlalchemy.txt
Q: gstreamer playbin - setting uri on windows I am trying to play some audio files with the CLI example on this site: http://pygstdocs.berlios.de/pygst-tutorial/playbin.html http://pygstdocs.berlios.de/pygst-tutorial/playbin.html I am on windows and it is giving error while reading the file. I specified the followin...
gstreamer playbin - setting uri on windows
I am trying to play some audio files with the CLI example on this site: http://pygstdocs.berlios.de/pygst-tutorial/playbin.html http://pygstdocs.berlios.de/pygst-tutorial/playbin.html I am on windows and it is giving error while reading the file. I specified the following path: $ python cliplayer.py C:\\voice.mp3 0:0...
[ "As you may have suspected, this code is rather badly written:\nfor filepath in sys.argv[1:]:\n # ...\n self.player.set_property(\"uri\", \"file://\" + filepath)\n\nUse something like this:\n'file:' + urllib.pathname2url(filepath)\n\nand (in the command line) specify the file path in normal Windows notation, ...
[ 9, 4 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0002216064_gstreamer_python.txt
Q: Django URL configuration Assume I have 3 Models: City, Area, Entry. Each city has several Areas and each area can have several entries BUT for "now", there can be will be only one active Entry and it will be shown. So in logic: Note that each city, area, entry will be using slug variable of related model class For...
Django URL configuration
Assume I have 3 Models: City, Area, Entry. Each city has several Areas and each area can have several entries BUT for "now", there can be will be only one active Entry and it will be shown. So in logic: Note that each city, area, entry will be using slug variable of related model class Format will be in such: www.mysit...
[ "It should probably look like something like that:\nurlpatterns = patterns('',\n (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/$', 'yourapp.views.areaview'),\n (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/(?P<entry>[a-z-]+)/$', 'yourapp.views.entryview'),\n)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0002217149_django_django_urls_python.txt
Q: Python regex for reading CSV-like rows I want to parse incoming CSV-like rows of data. Values are separated with commas (and there could be leading and trailing whitespaces around commas), and can be quoted either with ' or with ". For example - this is a valid row: data1, data2 ,"data3'''", 'data4""',,,data...
Python regex for reading CSV-like rows
I want to parse incoming CSV-like rows of data. Values are separated with commas (and there could be leading and trailing whitespaces around commas), and can be quoted either with ' or with ". For example - this is a valid row: data1, data2 ,"data3'''", 'data4""',,,data5, but this one is malformed: data1, da...
[ "While the csv module is the right answer here, a regex that could do this is quite doable:\nimport re\n\nr = re.compile(r'''\n \\s* # Any whitespace.\n ( # Start capturing here.\n [^,\"']+? # Either a series of non-comma non-quote characters.\n | ...
[ 12, 7, 4, 2, 1, 0 ]
[]
[]
[ "csv", "python", "regex" ]
stackoverflow_0002212933_csv_python_regex.txt
Q: Mock Y of (from X import Y) in doctest (python) I'm trying to create a doctest with mock of function that resides in a separate module and that is imported as bellow from foomodule import foo def bar(): """ >>> from minimock import mock >>> mock('foo', nsdicts=(bar.func_globals,), returns=5) >>> b...
Mock Y of (from X import Y) in doctest (python)
I'm trying to create a doctest with mock of function that resides in a separate module and that is imported as bellow from foomodule import foo def bar(): """ >>> from minimock import mock >>> mock('foo', nsdicts=(bar.func_globals,), returns=5) >>> bar() Called foo() 10 """ return foo()...
[ "You've just met one of the many reasons that make it best to never import object from \"within\" modules -- only modules themselves (possibly from within packages). We've made this rule part of our style guidelines at Google (published here) and I heartily recommend it to every Python programmer.\nThat being said...
[ 4, 2 ]
[]
[]
[ "doctest", "mocking", "python", "testing" ]
stackoverflow_0002216828_doctest_mocking_python_testing.txt
Q: Possible to use GCJ to produce library callable from Python? Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes? I'm interested in toxilibs for now, but if anybody knows a toy example that would be great ! A: If you want Java-Python hooks, you'd be far better of...
Possible to use GCJ to produce library callable from Python?
Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes? I'm interested in toxilibs for now, but if anybody knows a toy example that would be great !
[ "If you want Java-Python hooks, you'd be far better off using Jython and then calling across the boundary that way. \nHowever, yes, it's possible to call an external library from Java; but you don't need GCJ to do that. Rather, you can just bring up a JVM instance inside your Python runtime and then invoke your met...
[ 1 ]
[]
[]
[ "ctypes", "gcj", "java", "python" ]
stackoverflow_0002203728_ctypes_gcj_java_python.txt
Q: How to convert ip address to DWORD? Hey, how can I convert ip address to DWORD using python ? I searched a while but didn't found anything useful. Thanks for the helpers! A: Don't roll your own solution. Use the socket library. import socket socket.inet_pton(socket.AF_INET, "127.0.0.1") It will throw exception...
How to convert ip address to DWORD?
Hey, how can I convert ip address to DWORD using python ? I searched a while but didn't found anything useful. Thanks for the helpers!
[ "Don't roll your own solution. Use the socket library.\nimport socket\nsocket.inet_pton(socket.AF_INET, \"127.0.0.1\")\n\nIt will throw exceptions when it can't properly parse the address, and writing your own parsers for things is just a recipe for problems down the line.\nDoing it this way also makes it easier t...
[ 4, 0, -1 ]
[]
[]
[ "dword", "ip_address", "python" ]
stackoverflow_0002217612_dword_ip_address_python.txt
Q: Python 2.6 multiprocessing.Queue compatible with threads? I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the ...
Python 2.6 multiprocessing.Queue compatible with threads?
I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's __init_...
[ "I didn't experiment with multi-processing in 2.6 yet, but I played a lot with pyprocessing (as it was called in 2.5).\nI can see that you are looking for a number of processes with each spawning a set of threads respectively.\nSince you are using the multiprocessing module, I will suggest use multi process and not...
[ 4, 2, 1 ]
[ "Thanks for the quick response. I am passing the multiprocessing.Queue instances as arguments to each Process as you illustrate. The failure seems to occur in the threads. I am creating them by subclassing threading.Thread and passing the queue to the 'init' method of each thread instance. This seems to be the a...
[ -1 ]
[ "multiprocessing", "python", "python_2.6" ]
stackoverflow_0000342556_multiprocessing_python_python_2.6.txt
Q: Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy) I have a conjunctive probability mass function array, with shape, for example (1,2,3,4,5,6) and I want to calculate the probability table, conditional to a value for some of the dimensions (export the cpts), for decisio...
Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy)
I have a conjunctive probability mass function array, with shape, for example (1,2,3,4,5,6) and I want to calculate the probability table, conditional to a value for some of the dimensions (export the cpts), for decision-making purposes. The code I came up with at the moment is the following (the input is the dictionar...
[ "Ok, found the answer myself after playing a little with numpy's in-place array manipulations.\nChanged the last 3 lines in the loop to:\n d = conditionalize(d, dim, val)\n\nwhere conditionalize is defined as:\n def conditionalize(arr, dim, val):\n arr = arr.swapaxes(dim, 0)\n shape = arr.shape[...
[ 1 ]
[]
[]
[ "arrays", "numpy", "probability", "python", "recarray" ]
stackoverflow_0002199940_arrays_numpy_probability_python_recarray.txt
Q: Sort by field in ForeignKey model I have created a Django model called Person, which has got a 'user' ForeignKey to django.contrib.auth.models.User How can I set the ordering on class Person to self.user.first_name, self.user.last_name? A: class Meta: ordering = ['user__first_name', 'user__last_name'] Shoul...
Sort by field in ForeignKey model
I have created a Django model called Person, which has got a 'user' ForeignKey to django.contrib.auth.models.User How can I set the ordering on class Person to self.user.first_name, self.user.last_name?
[ "class Meta:\n ordering = ['user__first_name', 'user__last_name']\n\nShould do the trick iirc\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002218121_django_python.txt
Q: Override Python's 'in' operator? If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g. class MyClass(object): ... m = MyClass() if 54 in m: ... A: MyClass.__contains__(self, item) A: A more complete answer is: class MyClass(object): ...
Override Python's 'in' operator?
If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g. class MyClass(object): ... m = MyClass() if 54 in m: ...
[ "MyClass.__contains__(self, item)\n", "A more complete answer is:\nclass MyClass(object):\n\n def __init__(self):\n self.numbers = [1,2,3,4,54]\n\n def __contains__(self, key):\n return key in self.numbers\n\nHere you would get True when asking if 54 was in m:\n>>> m = MyClass()\n>>> 54 in m\n...
[ 325, 263 ]
[]
[]
[ "in_operator", "operator_overloading", "operators", "python" ]
stackoverflow_0002217001_in_operator_operator_overloading_operators_python.txt
Q: convention to represent the exit status and actual result in XMLRPC in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process. when it comes to xmlrpc, no INOUT/OUT parameter, is there any best practice/conventions to represe...
convention to represent the exit status and actual result in XMLRPC
in the C world, a function can return error code to represent the exit status, and use INOUT/OUT parameter to carry the actual fruit of the process. when it comes to xmlrpc, no INOUT/OUT parameter, is there any best practice/conventions to represent the exit status and actual result? the context is i am trying to writ...
[ "One simple way to implement this in Python is with a tuple. Have your function return a tuple of: (status, result) where the status can be numeric or a string, and the result can be any Python data structure you fancy.\nHere's an example, adapted from the module documentation. Server code:\nfrom SimpleXMLRPCServer...
[ 1, 1 ]
[]
[]
[ "exit_code", "function", "python", "xml_rpc" ]
stackoverflow_0002217072_exit_code_function_python_xml_rpc.txt
Q: python equivalent of '#define func() ' or how to comment out a function call in python my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.) for example: import logging logging.root.setLevel(logging.DEBUG) logging.debug('hello') j = 0 for i in range(10): j += i ...
python equivalent of '#define func() ' or how to comment out a function call in python
my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.) for example: import logging logging.root.setLevel(logging.DEBUG) logging.debug('hello') j = 0 for i in range(10): j += i logging.debug('i %d j %d' % (i,j)) print(j) logging.debug('bye') i want to #define these...
[ "Python does not have a preprocessor, although you could run your python source through an external preprocessor to get the same effect - e.g. sed \"/logging.debug/d\" will strip out all the debug logging commands. This is not very elegant though - you will end up needing some sort of build system to run all your ...
[ 17, 2, 1, 0, 0, 0, 0, 0 ]
[ "You can't skip function calls. You could redefine these as empty though, e.g. by creating another logging object that provides the same interface, but with empty functions.\nBut by far the cleanest approach is to ignore the low priority log messages (as you suggested):\nlogging.root.setLevel(logging.CRITICAL)\n\n"...
[ -1 ]
[ "comments", "preprocessor", "python" ]
stackoverflow_0002006190_comments_preprocessor_python.txt
Q: Profiling of Python threads I am trying to figure out how to measure the performance of several python threads in my application. I currently have several tasks that are executing on different threads based on user input and I would like to measure the execution time, maybe even memory consumption of each of the t...
Profiling of Python threads
I am trying to figure out how to measure the performance of several python threads in my application. I currently have several tasks that are executing on different threads based on user input and I would like to measure the execution time, maybe even memory consumption of each of the threads. I have tried to use cProf...
[ "There are a few different ways to tackle this problem. cProfile is great and comes with Python, however many people see multi-threaded profiling as an issue. One way of getting around this is by running separate instances of cProfile for each thread and then combining the results using Stats.add.\nShould that not ...
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002218330_multithreading_python.txt
Q: Unable to access ID property from a datastore entity Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) : class Question(db.Mo...
Unable to access ID property from a datastore entity
Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) : class Question(db.Model): text = db.StringProperty() answers = db.Stri...
[ "According to the documentation, there is no id() instance method defined for Model subclasses.\nTry {{ question.key }} instead.\nAlso note that the key is not created until the entity is saved to the datastore.\n\nEdit: more info based on OP's edit:\nSince we're really after the numeric ID, we could do something ...
[ 11, 5 ]
[]
[]
[ "entity", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002218693_entity_google_app_engine_google_cloud_datastore_python.txt
Q: time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff! How does time.localtime() work exactly? I can call up the "array" (tupple, I think it is called - because it is immutable?) and reference/index components of it. For example: >>> time.localtime()[0] 2010 But if I do: p...
time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff!
How does time.localtime() work exactly? I can call up the "array" (tupple, I think it is called - because it is immutable?) and reference/index components of it. For example: >>> time.localtime()[0] 2010 But if I do: print time.localtime() time.struct_time(tm_year=2010, tm_mon=2, tm_mday=7, tm_hour=14, tm_min=46, tm...
[ "time.localtime()[0] calls __gettiem__() on the time.struct_time instance. This is how it gets this list/tuple like behaviour from. Here is a really simple example\n>>> class MyTime(object):\n... def __init__(self, year, month, mday, hour, minute):\n... self.data = year, month, mday, hour, minute\n... ...
[ 3, 1, 0, 0 ]
[]
[]
[ "arrays", "python", "time" ]
stackoverflow_0002218737_arrays_python_time.txt
Q: Is it advisable to go with Python 3.1 for a beginner? Possible Duplicate: What version of Python should I use if I’m a new to Python? Is it advisable to go with Python 3.1 for a beginner? Or are there any severe drawbacks I would have to consider? A: 3.1 is much simpler than 2.5 or 2.6, but currently suffers a...
Is it advisable to go with Python 3.1 for a beginner?
Possible Duplicate: What version of Python should I use if I’m a new to Python? Is it advisable to go with Python 3.1 for a beginner? Or are there any severe drawbacks I would have to consider?
[ "3.1 is much simpler than 2.5 or 2.6, but currently suffers a severe dearth of third-party add-ons, environments supporting it (big apps using it for scripting, etc) and tools such as IDEs. So, much depends on what you want to learn Python for -- if just for personal edification, 3.1 is ideal; if it's to actually ...
[ 17, 4, 3, 3, 1 ]
[]
[]
[ "python", "python_3.x", "version" ]
stackoverflow_0002218841_python_python_3.x_version.txt
Q: What's wrong here? Iterating over a dictionary in Django template I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value. Here's what I have in models.py: class Manors(models.Model): structidx = models.IntegerField...
What's wrong here? Iterating over a dictionary in Django template
I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value. Here's what I have in models.py: class Manors(models.Model): structidx = models.IntegerField(primary_key=True, verbose_name="ID") county = models.CharField...
[ "To iterate a dictionary wouldn't you need:\n<h4>Statistics</h4>\n<ul>\n {% for key, value in manor_stats.get_fields.items %}\n <li> {{ key }}: {{ value }}</li>\n {% endfor %}\n</ul>\n\nBut I'd suggest retrieving the dictionary from the function first:\nViews.py:\n manor_stats = Manors.objects.get(structidx__exa...
[ 29, 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002218388_django_django_templates_python.txt
Q: Many2ManyField is not saving via Modelforms I have a Modelform: class POwner4NewModel(ModelForm): class Meta: model = ProductOwner exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status") This is the model's schema: class P...
Many2ManyField is not saving via Modelforms
I have a Modelform: class POwner4NewModel(ModelForm): class Meta: model = ProductOwner exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status") This is the model's schema: class ProductOwner(models.Model): o_owner = models.F...
[ "form doesn't have save_m2m() because you overwrote form with a model instance when you did form = form.save(commit=False)\ntry using something else like instance = form.save(commit=False) etc. then you should be able to use form.save_m2m() (of course after the instance.save()).\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002218424_django_python.txt
Q: How to evaluate a matched number later in a regex? - Lexing FORTRAN 'H' edit descriptor with Ply I am using Ply to interpret a FORTRAN format string. I am having trouble writing a regex to match the 'H' edit descriptor which is of the form xHccccc ... where x specifies the number of characters to read in after the...
How to evaluate a matched number later in a regex? - Lexing FORTRAN 'H' edit descriptor with Ply
I am using Ply to interpret a FORTRAN format string. I am having trouble writing a regex to match the 'H' edit descriptor which is of the form xHccccc ... where x specifies the number of characters to read in after the 'H' Ply matches tokens with a single regular expression, but I am having trouble using regular expres...
[ "Regex can't do things like that. You can hack it though:\n(1[Hh].|2[Hh]..|3[Hh]...|etc...)\n\nUgly!\n", "This is what comes of thinking that regexps can replace a lexer.\nShort version: regular expressions can only deal with that small subset of all possible language termed \"regular\" (big surprise, I know). Bu...
[ 2, 0, 0 ]
[]
[]
[ "lexical_analysis", "ply", "python", "regex" ]
stackoverflow_0002216843_lexical_analysis_ply_python_regex.txt
Q: Does the Python standard library contain a module for manipulating URIs? I'd like to pass a URI to a constructor and get back an object on which I can call obj.type, obj.host, obj.port, etc. The "Request" object of the urllib2 module is close to what I need, but not quite it. A: Maybe something like the urlparse...
Does the Python standard library contain a module for manipulating URIs?
I'd like to pass a URI to a constructor and get back an object on which I can call obj.type, obj.host, obj.port, etc. The "Request" object of the urllib2 module is close to what I need, but not quite it.
[ "Maybe something like the urlparse module? \n\nThe urlparse module is renamed to urllib.parse in Python 3.0.\n\nFrom the doc:\n>>> from urlparse import urlparse\n>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')\n>>> o # doctest: +NORMALIZE_WHITESPACE\n ParseResult(scheme='http', netloc='www.cwi.n...
[ 6 ]
[]
[]
[ "python", "string", "url" ]
stackoverflow_0002219827_python_string_url.txt
Q: Simple example of gang scheduling of processes in Python? I have a pool of processes that need to be executed. I would like to fully utilize the machine, so that all CPUs are executing processes. I do not want to over-subscribe the system, so what i really want is #executing_processes=#cpus at any given moment. I...
Simple example of gang scheduling of processes in Python?
I have a pool of processes that need to be executed. I would like to fully utilize the machine, so that all CPUs are executing processes. I do not want to over-subscribe the system, so what i really want is #executing_processes=#cpus at any given moment. I also need to store the stdout,stderr and return code of each c...
[ "If you are talking about your own, Python-implemented processes:\nThe multiprocessing module gives you the ability to spawn multiple processes. In particular, it sounds like you would want to create multiprocessing.cpu_count numbers of processes, potentially in a Pool.\nIf you are talking about separate programs ...
[ 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002220083_multiprocessing_python.txt
Q: python tuple division TypeError: unsupported operand type(s) for /: 'tuple' and 'tuple' I'm getting above error , while I fetched a record using query "select max(rowid) from table" and assigned it to variable and while performing / operation is throws above message. How to resolve this. A: Sql query select max...
python tuple division
TypeError: unsupported operand type(s) for /: 'tuple' and 'tuple' I'm getting above error , while I fetched a record using query "select max(rowid) from table" and assigned it to variable and while performing / operation is throws above message. How to resolve this.
[ "Sql query select max(rowid) would return Tuple data like records=(1000,)\nYou may need to do like numerator / records[0]\n" ]
[ 4 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002220099_python_tuples.txt
Q: delete xml node using lxml admin . . . . admin this my xml file. when i user clear()or del method it will clear all the child and a blank node is creating <user/> How can i avoid creating this blank node it will make problem when i use fin...
delete xml node using lxml
admin . . . . admin this my xml file. when i user clear()or del method it will clear all the child and a blank node is creating <user/> How can i avoid creating this blank node it will make problem when i use findall() and try to access any of...
[ "Removing match user node from parent Node would be suitable for this case.\n" ]
[ 4 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0002220185_lxml_python_xml.txt
Q: Catching errors when logging with SocketHandler in Python My web application runs on multpile apache instances and I am having multiprocess logging issues because of this. I am currently using a SocketHandler for logging to a daemon using SocketServer that then writes logs to a single log file (similar to this ex...
Catching errors when logging with SocketHandler in Python
My web application runs on multpile apache instances and I am having multiprocess logging issues because of this. I am currently using a SocketHandler for logging to a daemon using SocketServer that then writes logs to a single log file (similar to this example). Now that I am using a SocketHandler for logging I am ha...
[ "When a socket creation operation fails (e.g. because there is no server listening), the default behaviour is to retry the next time an event is logged, with an exponential back-off algorithm. Here are some approaches you could try:\n\nSubclass SocketHandler, override the createSocket method and handle exceptions h...
[ 5, 1 ]
[]
[]
[ "exception_handling", "mod_python", "python", "sockets" ]
stackoverflow_0002220159_exception_handling_mod_python_python_sockets.txt
Q: writing to data to excel I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated. def month_end(request): """ A simple view that will generate a month end report as ...
writing to data to excel
I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated. def month_end(request): """ A simple view that will generate a month end report as a PDF response. """ c...
[ "Have a look to xlwt http://pypi.python.org/pypi/xlwt\n", "You could directly write CSV from MySQL records,\nimport csv\ncsv_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar=\"'\")\n\ndata = cursor.fetchall()\nfor row in data:\n csv_writer.writerow(row)\n\nFull example at\nhttp://snipplr.com/vie...
[ 4, 4 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0002220351_csv_django_python.txt
Q: Python properties: Two instances of variable? Really confused about what's going on here. I have a class defined as follows: class Profile(models.Model): user = models.OneToOneField(User) primary_phone = models.CharField(max_length=20) address = models.ForeignKey(Address) @property def primary...
Python properties: Two instances of variable?
Really confused about what's going on here. I have a class defined as follows: class Profile(models.Model): user = models.OneToOneField(User) primary_phone = models.CharField(max_length=20) address = models.ForeignKey(Address) @property def primary_email(self): return self.user.email @primary_e...
[ "I'm not a Django user, but I'd guess it's because you didn't update the model after changing u.email. Try calling u.save() (or whatever the method happens to be called) before accessing the user's email through the profile.\nYou can use Django's signaling feature to build a workaround. Basically, update Profile.us...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002218989_django_python.txt
Q: perror equivalent function in python I'm using try except block in python, while the try block fails , how to print meaningful error message. I'm looking for something like perror() in C A: >>> try: ... 0/0 ... except Exception,e: ... print e.message ... integer division or modulo by zero or in Python ...
perror equivalent function in python
I'm using try except block in python, while the try block fails , how to print meaningful error message. I'm looking for something like perror() in C
[ ">>> try:\n... 0/0\n... except Exception,e:\n... print e.message\n...\ninteger division or modulo by zero\n\nor in Python 2.6 and above, e.args, because of BaseException.message has been deprecated\n>>> try:\n... 0/0\n... except Exception,e:\n... print e.args\n...\n('integer division or modulo by ze...
[ 6 ]
[ "try:\n pass\nexcept Exception, err:\n print err\n\n" ]
[ -2 ]
[ "python", "try_catch" ]
stackoverflow_0002220038_python_try_catch.txt
Q: Does Django have `__not_equal`? Does Django have a field lookup like __not_equal? (Field lookups are __exact, __contains, etc.) A: Use one of __exact, __contains etc. with exclude() instead of filter(). A: You can also use the Q object and negate it. E.g. Poll.objects.filter(~Q(question='Who'))
Does Django have `__not_equal`?
Does Django have a field lookup like __not_equal? (Field lookups are __exact, __contains, etc.)
[ "Use one of __exact, __contains etc. with exclude() instead of filter().\n", "You can also use the Q object and negate it.\nE.g.\nPoll.objects.filter(~Q(question='Who'))\n\n" ]
[ 6, 3 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0002220682_django_orm_python.txt
Q: Google App Engine: How do I save uploaded text file to Blob, then read from it line by line? I have a huge file (over 16,000 lines) that I want to save in the datastore for parsing later. Each line contains info on an entity. How do I read line by line from the stored Blob? I can't seem to find a good tutorial...
Google App Engine: How do I save uploaded text file to Blob, then read from it line by line?
I have a huge file (over 16,000 lines) that I want to save in the datastore for parsing later. Each line contains info on an entity. How do I read line by line from the stored Blob? I can't seem to find a good tutorial or documentation on a Blob anywhere. GAE only shows how to deal with images, but I want to read f...
[ "Use the Text type to store it instead of a blob. Text does not have any limits on size, but its not indexable or queryable. \nSo if all you want is sequential line by line access to the data, it would work perfectly.\n", "If you simply need the lines from the blob, just do:\nlines = blob.split(\"\\n\")\n\nIf you...
[ 1, 0 ]
[]
[]
[ "blob", "google_app_engine", "python" ]
stackoverflow_0002216134_blob_google_app_engine_python.txt
Q: Migrating off AppEngine I have an application running on AppEngine that uses about 50 CPU hours a day. Most of it is spent waiting for the datastore. I am contemplating moving it off of AppEngine to something like Rackspace Cloud Servers because I think that my application can be more efficient if I can offload s...
Migrating off AppEngine
I have an application running on AppEngine that uses about 50 CPU hours a day. Most of it is spent waiting for the datastore. I am contemplating moving it off of AppEngine to something like Rackspace Cloud Servers because I think that my application can be more efficient if I can offload some of the work to the databa...
[ "If you can redeploy to appscale, you won't have to rewrite any of your App Engine code.\n", "You can use TyphoonAE, which is based on the SDK, and designed for small to medium scale deployments - eg, individual servers to small clusters - and should be fairly easy to set up.\nSorry to see you go.\n" ]
[ 9, 1 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0002215721_google_app_engine_python_web_applications.txt
Q: App engine - Uploading a large file and parsing data from it onto the datastore I have a file that contains ~16,000 lines of information on entities. The user is supposed to upload the file using an HTML upload form, then the system handles this by reading line by line and creating then put()'ing entities onto the...
App engine - Uploading a large file and parsing data from it onto the datastore
I have a file that contains ~16,000 lines of information on entities. The user is supposed to upload the file using an HTML upload form, then the system handles this by reading line by line and creating then put()'ing entities onto the datastore. I'm limited by the 30 second request time limit. I have tried a lot of di...
[ "To solve a similar problem, I stored the dataset in a model with a single TextProperty, then spawn a taskqueue task that:\n\nFetches a dataset from the datastore if there are any left.\nChecks if the length of the dataset is <= N, where N is some small number of entities you can put() without a timeout. I used 5....
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python", "upload" ]
stackoverflow_0002208546_google_app_engine_python_upload.txt
Q: Python list slice syntax used for no obvious reason I occasionally see the list slice syntax used in Python code like this: newList = oldList[:] Surely this is just the same as: newList = oldList Or am I missing something? A: [:] Shallow copies the list, making a copy of the list structure containing reference...
Python list slice syntax used for no obvious reason
I occasionally see the list slice syntax used in Python code like this: newList = oldList[:] Surely this is just the same as: newList = oldList Or am I missing something?
[ "[:] Shallow copies the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if...
[ 53, 51, 12, 4 ]
[ "Shallow Copy: (copies chunks of memory from one location to another)\na = ['one','two','three']\n\nb = a[:]\n\nb[1] = 2\n\nprint id(a), a #Output: 1077248300 ['one', 'two', 'three']\nprint id(b), b #Output: 1077248908 ['one', 2, 'three']\n\nDeep Copy: (Copies object reference)\na = ['one','two','three']\n\nb = a\n...
[ -2 ]
[ "list", "python", "shallow_copy" ]
stackoverflow_0000323689_list_python_shallow_copy.txt
Q: How to know all the derived classes of a parent? Suppose you have a base class A, and this class is reimplemented by B and C. Suppose also there's a class method A.derived() that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have class D(A): pass or class D(B): pass, now A...
How to know all the derived classes of a parent?
Suppose you have a base class A, and this class is reimplemented by B and C. Suppose also there's a class method A.derived() that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have class D(A): pass or class D(B): pass, now A.derived() returns [B,C,D]. How would you implement t...
[ "If you define your classes as a new-style class (subclass of object) then this is possible since the subclasses are saved in __subclasses__.\nclass A(object):\n def hello(self):\n print \"Hello A\"\n\nclass B(A):\n def hello(self):\n print \"Hello B\"\n\n>>> for cls in A.__subclasses__():\n... print cls.__name...
[ 22, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002219998_python.txt
Q: Equivalent functionality to Google Charts API from python ? (Venn Diagrams also needed!) is there any library (for C or python) that I can use to get roughly the same functionality as I can get from Google Charts ? I specifically need the pie diagrams (standard), multi-dataset-pie-diagrams (not-so-standard), and v...
Equivalent functionality to Google Charts API from python ? (Venn Diagrams also needed!)
is there any library (for C or python) that I can use to get roughly the same functionality as I can get from Google Charts ? I specifically need the pie diagrams (standard), multi-dataset-pie-diagrams (not-so-standard), and venn diagrams (rare)...
[ "http://pygooglechart.slowchop.com/ is a Python wrapper for the Google Charts API. Also see Pretty graphs and charts in Python\n" ]
[ 1 ]
[]
[]
[ "charts", "python" ]
stackoverflow_0002220929_charts_python.txt
Q: Python + Komodo Edit I am trying to get scapy to auto complete in komodo edit with no success, has anyone successfully done this? Thanks, Python New Comer A: Autocomplete in Python is a hit or miss proposition. It varies widely -- some things can be analyzed by Komodo and some can't. If it won't autocomplete...
Python + Komodo Edit
I am trying to get scapy to auto complete in komodo edit with no success, has anyone successfully done this? Thanks, Python New Comer
[ "Autocomplete in Python is a hit or miss proposition. It varies widely -- some things can be analyzed by Komodo and some can't. \nIf it won't autocomplete, it's probably because it relies on too many metaclass techniques that seem to baffle Komodo.\n", "If you're in virtualenv or have some tricky python paths y...
[ 1, 1 ]
[]
[]
[ "komodoedit", "python", "scapy" ]
stackoverflow_0002218637_komodoedit_python_scapy.txt
Q: Rasterizing a GDAL layer Edit Here is the proper way to do it, and the documentation: import random from osgeo import gdal, ogr RASTERIZE_COLOR_FIELD = "__color__" def rasterize(pixel_size=25): # Open the data source orig_data_source = ogr.Open("test.shp") # Make a copy of the layer's data source...
Rasterizing a GDAL layer
Edit Here is the proper way to do it, and the documentation: import random from osgeo import gdal, ogr RASTERIZE_COLOR_FIELD = "__color__" def rasterize(pixel_size=25): # Open the data source orig_data_source = ogr.Open("test.shp") # Make a copy of the layer's data source because we'll need to # ...
[ "EDIT: I guess I'd use qGIS python bindings: http://www.qgis.org/wiki/Python_Bindings\nThat's the easiest way I can think of. I remember hand rolling something before, but it's ugly. qGIS would be easier, even if you had to make a separate Windows installation (to get python to work with it) then set up an XML-RPC ...
[ 10 ]
[]
[]
[ "gdal", "gis", "python", "rasterizing" ]
stackoverflow_0002220749_gdal_gis_python_rasterizing.txt
Q: Python: Setting an element of a Numpy matrix I am a pretty new to python. I have created an empty matrix a = numpy.zeros(shape=(n,n)) Now I can access each element using a.item(i,j) How do I set an index (i,j)? A: Here's how: a[i,j] = x A: Or a.itemset((i,j),x) A: Try this a[i,j]=5
Python: Setting an element of a Numpy matrix
I am a pretty new to python. I have created an empty matrix a = numpy.zeros(shape=(n,n)) Now I can access each element using a.item(i,j) How do I set an index (i,j)?
[ "Here's how:\na[i,j] = x\n\n", "Or\na.itemset((i,j),x)\n\n", "Try this\na[i,j]=5\n\n" ]
[ 65, 10, 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002220968_numpy_python.txt
Q: Custom instance unpickling in Python: should the object dictionary be updated, or is replacing it OK? When defining how objects of a certain class should be unpickled, via __setstate__, I gather that it is safe to do def __setstate__(self, dict_returned_by_pickle): self.__dict__.update(dict_returned_by_pickle)...
Custom instance unpickling in Python: should the object dictionary be updated, or is replacing it OK?
When defining how objects of a certain class should be unpickled, via __setstate__, I gather that it is safe to do def __setstate__(self, dict_returned_by_pickle): self.__dict__.update(dict_returned_by_pickle) when the pickled state is a dictionary. This is what I have seen in an answer here on stackoverflow. How...
[ "Replacing it is fine. That is what the borg pattern does.\nThe original dict will be garbage collected if there are no other references to it.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "pickle", "python" ]
stackoverflow_0002221279_dictionary_pickle_python.txt
Q: Why doesn't this loop display an updated object count every five seconds? I use this python code to output the number of Things every 5 seconds: def my_count(): while True: print "Number of Things: %d" % Thing.objects.count() time.sleep(5) my_count() If another process generates a new T...
Why doesn't this loop display an updated object count every five seconds?
I use this python code to output the number of Things every 5 seconds: def my_count(): while True: print "Number of Things: %d" % Thing.objects.count() time.sleep(5) my_count() If another process generates a new Thing while my_count() is running, my_count() will keep printing the same number...
[ "Because Python DB API is by default in AUTOCOMMIT=OFF mode, and (at least for MySQLdb) on REPEATABLE READ isolation level. This means that behind the scenes you have an ongoing database transaction (InnoDB is transactional engine) in which the first access to given row (or maybe even table, I'm not sure) fixes \"v...
[ 16 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002221247_django_mysql_python.txt
Q: Retrieving many-to-many relation properties using SQLAlchemy I have a many-to-many relationship in which the relation-table contains more columns than only the primary key. As an example, consider a slide show system in which each image could have it's own timeout, and a different timeout depending on the slidesho...
Retrieving many-to-many relation properties using SQLAlchemy
I have a many-to-many relationship in which the relation-table contains more columns than only the primary key. As an example, consider a slide show system in which each image could have it's own timeout, and a different timeout depending on the slideshow. A daft example, but it will have to do for the sake of illustra...
[ "You can define intermediate model based on show_has_image table (use composite primary key) and define relations to it. Then use association_proxy to define Show.images property.\n" ]
[ 1 ]
[]
[]
[ "declarative", "python", "sql", "sqlalchemy", "turbogears" ]
stackoverflow_0002217465_declarative_python_sql_sqlalchemy_turbogears.txt
Q: Independent instances of 'random' The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that? class RandomSeeded: def __init__(sel...
Independent instances of 'random'
The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that? class RandomSeeded: def __init__(self, seed): import random as r1 ...
[ "Class random.Random exists specifically to allow the behavior you want -- modules are intrinsically singletons, but classes are meant to be multiply instantiated, so both kinds of needs are covered.\nShould you ever need an independent copy of a module (which you definitely don't in the case of random!), try using...
[ 21, 7, 4 ]
[]
[]
[ "class", "module", "python", "random", "seed" ]
stackoverflow_0002219436_class_module_python_random_seed.txt
Q: How to refer to a method name from with a method in Python? Say I have the following class defined with the method foo: class MyClass: def foo(self): print "My name is %s" % __name__ Now when I call foo() I expect/want to see this printed out My name is foo However I get My name is __main__ ...
How to refer to a method name from with a method in Python?
Say I have the following class defined with the method foo: class MyClass: def foo(self): print "My name is %s" % __name__ Now when I call foo() I expect/want to see this printed out My name is foo However I get My name is __main__ And if I was to put the class definition into a module called Foo...
[ "This does what you're after:\n\nfrom inspect import currentframe, getframeinfo\n\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % getframeinfo(currentframe())[2]\n\n", "Names always refer to local variables or (if one doesn't exist) then global variables. There is a a global __name__ that ...
[ 11, 4, 3, 2, 1, 1 ]
[ "This will do it:\n(You need to refer to self.__class__._name__.)\nclass MyClass:\n def foo(self):\n print \"My name is %s\" % self.__class__.__name__\n\n" ]
[ -2 ]
[ "introspection", "methods", "python" ]
stackoverflow_0002222044_introspection_methods_python.txt
Q: The ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} syntax doesn't work in a Mako template In a Mako template, I need to do something like: ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} When A do that, I get this error: SyntaxException: (SyntaxError) unexpected EOF while parsing (, line 1) ("'foo %(a)s bar...
The ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} syntax doesn't work in a Mako template
In a Mako template, I need to do something like: ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} When A do that, I get this error: SyntaxException: (SyntaxError) unexpected EOF while parsing (, line 1) ("'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'") in file… How do I fix this issue? I need to use this syntax in ...
[ "A work-around is to pass the dict object in a different way. For example:\nfrom mako.template import Template\n\nprint Template(\"${'foo %(a)s bar %(b)s' % data}\").render(data=dict(a='Alpha',b='Beta'))\n\n" ]
[ 0 ]
[ "Solution:\n${'foo %(a)s bar %(b)s' % dict((('a', '1'), ('b', '2'),))}\n\n" ]
[ -1 ]
[ "mako", "python", "templates" ]
stackoverflow_0002221910_mako_python_templates.txt
Q: PyQt4 QDialog connections not being made I am working on an application using PyQt4 and the designer it provides. I have a main window application that works fine, but I wanted to create custom message dialogs. I designed a dialog and set up some custom signal/slot connections in the __init__ method and wrote an...
PyQt4 QDialog connections not being made
I am working on an application using PyQt4 and the designer it provides. I have a main window application that works fine, but I wanted to create custom message dialogs. I designed a dialog and set up some custom signal/slot connections in the __init__ method and wrote an if __name__=='__main__': and had a test. The...
[ "It feels like the signal is just not getting passed from the parent down to your child QDIalog.\nTry these suggestions:\n\nUse the new method for connecting signals\nInstead of extending the classes pyuic created, extend the actual QT classes and call the ones generated by pyuic\n\nYour new code will look somethin...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qdialog", "signals_slots" ]
stackoverflow_0002169325_pyqt4_python_qdialog_signals_slots.txt
Q: Printing to a file from a list of lists in Python I am trying to print to a file that will look like: 'A' '1' 'B' '2' 'C' '3' Given the code below, however, the result is : ['A'] ['B'] ['C'] This is probably a 'softball' question, but what am I doing wrong here? l1 = ['1'] l2 = ['A'] l3 = ['2'] l4 = ['B'] l5 = ...
Printing to a file from a list of lists in Python
I am trying to print to a file that will look like: 'A' '1' 'B' '2' 'C' '3' Given the code below, however, the result is : ['A'] ['B'] ['C'] This is probably a 'softball' question, but what am I doing wrong here? l1 = ['1'] l2 = ['A'] l3 = ['2'] l4 = ['B'] l5 = ['3'] l6 = ['C'] listoflists = [l1,l2,l3,l4,l5,l6] itr...
[ "First of all, don't use iter and next(), that's what for is for. Secondly, you are actually writing a list to the file, not its contents. So you could either print the first element of the list (i.e. l1[0]) or iterate through all the inner lists elements.\nYour code should look like this:\nl1 = ['1']\nl2 = ['A']\n...
[ 7, 2, 1, 1, 0, 0 ]
[]
[]
[ "file", "iteration", "list", "python" ]
stackoverflow_0002222189_file_iteration_list_python.txt
Q: Making your own statements Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own. If so, how do I do it? Can you point me to good docs on the subject? A: No, you cannot add new syntax within a Pytho...
Making your own statements
Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own. If so, how do I do it? Can you point me to good docs on the subject?
[ "No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.\n", "You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What yo...
[ 10, 3, 2, 2, 1 ]
[]
[]
[ "keyword", "python", "statements", "syntax" ]
stackoverflow_0002222843_keyword_python_statements_syntax.txt
Q: cx_Freeze ImportError: cannot import name I'm trying create an executable for Windows for a GUI application in tkinter using the ttk module. I made an exe with cx_freeze, but when I run the app in the console it gives me the following error: D:\My Dropbox\python\SAR Calculator\src\dist_tk> Traceback (most rece...
cx_Freeze ImportError: cannot import name
I'm trying create an executable for Windows for a GUI application in tkinter using the ttk module. I made an exe with cx_freeze, but when I run the app in the console it gives me the following error: D:\My Dropbox\python\SAR Calculator\src\dist_tk> Traceback (most recent call last): File "C:\Python31\lib\site-pa...
[ "Looks like cx_freeze doesn't realize it should include the tkinter._fix module, which is conditionally imported by tkinter/__init__.py. You can tell it to include that module explicitly with the --include-modules command-line argument, or the includes keyword argument to cx_Freeze.Executable in your setup.py\n" ]
[ 5 ]
[]
[]
[ "cx_freeze", "exe", "python", "python_3.x", "tkinter" ]
stackoverflow_0002223128_cx_freeze_exe_python_python_3.x_tkinter.txt
Q: Deciding on a blog URL scheme with regard to python performance I'm writing a blog in Python and have come to the point where I have to decide on the URL scheme to use. It's tempting to just list the entries start to end, like: http://myblog.com/1 http://myblog.com/2 ... http://myblog.com/1568 And on the server s...
Deciding on a blog URL scheme with regard to python performance
I'm writing a blog in Python and have come to the point where I have to decide on the URL scheme to use. It's tempting to just list the entries start to end, like: http://myblog.com/1 http://myblog.com/2 ... http://myblog.com/1568 And on the server side I would just have the blog entries in a python list. My fear thou...
[ "The performance difference between the two will be negligible. The overhead of the list or dictionary will be much smaller than the size of the text in the entries.\nKeeping everything in memory is not a good solution though. You should persist the entries to disk (database, flat file, etc.), then (if necessary) u...
[ 1, 0 ]
[]
[]
[ "python", "url" ]
stackoverflow_0002218363_python_url.txt
Q: How to turn a SVG image to a SDL surface or an array of RGBA pixels with python? I'm guessing it has to be done with the aid of some sort of framework. Google gives libCairo as the most common result, but that is way too many dependencies. I mean something that would work on Win/Lin/OSX, be non-GPL, python-compati...
How to turn a SVG image to a SDL surface or an array of RGBA pixels with python?
I'm guessing it has to be done with the aid of some sort of framework. Google gives libCairo as the most common result, but that is way too many dependencies. I mean something that would work on Win/Lin/OSX, be non-GPL, python-compatible, freely re-distributable. And preferably a few hundred KB in size. Thing is, it do...
[ "Try python-rsvg from http://www.cairographics.org/pyrsvg/\nToo many dependencies? Really? http://www.cairographics.org/download/ has Windows binaries. It depends on libpng and zlib. Don't know about getting the Python bindings up though. If the bindings are too hard, you could just shell out to rsvg file.svg outpu...
[ 1 ]
[]
[]
[ "python", "rgb", "sdl", "svg" ]
stackoverflow_0002198499_python_rgb_sdl_svg.txt
Q: Python sort parallel arrays in place? Is there an easy (meaning without rolling one's own sorting function) way to sort parallel lists without unnecessary copying in Python? For example: foo = range(5) bar = range(5, 0, -1) parallelSort(bar, foo) print foo # [4,3,2,1,0] print bar # [1,2,3,4,5] I've seen the exam...
Python sort parallel arrays in place?
Is there an easy (meaning without rolling one's own sorting function) way to sort parallel lists without unnecessary copying in Python? For example: foo = range(5) bar = range(5, 0, -1) parallelSort(bar, foo) print foo # [4,3,2,1,0] print bar # [1,2,3,4,5] I've seen the examples using zip but it seems silly to copy a...
[ "Here's an easy way:\nperm = sorted(xrange(len(foo)), key=lambda x:foo[x])\n\nThis generates a list of permutations - the value in perm[i] is the index of the ith smallest value in foo. Then, you can access both lists in order:\nfor p in perm:\n print \"%s: %s\" % (foo[p], bar[p])\n\nYou'd need to benchmark it to ...
[ 6, 3, 0, 0 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0002222769_algorithm_python_sorting.txt
Q: Stopping a thread in python I am creating a thread in my Python app with thread.start_new_thread. How do I stop it if it hasn't finished in three seconds time? A: You can't do that directly. Anyway aborting a thread is not good practice - rather think about using synchronization mechanisms that let you abort the...
Stopping a thread in python
I am creating a thread in my Python app with thread.start_new_thread. How do I stop it if it hasn't finished in three seconds time?
[ "You can't do that directly. Anyway aborting a thread is not good practice - rather think about using synchronization mechanisms that let you abort the thread in a \"soft\" way.\nBut daemonic threads will automatically be aborted if no non-daemonic threads remain (e.g. if the only main thread ends). Maybe that's wh...
[ 2, 1, 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002223654_multithreading_python.txt
Q: UnicodeEncodeError when redirecting stdout I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout elsewhere (or capture it with the subprocess module), I get a UnicodeEncodeError: $ cat example.py print u'Example: \u00F1' $ python example.py ...
UnicodeEncodeError when redirecting stdout
I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout elsewhere (or capture it with the subprocess module), I get a UnicodeEncodeError: $ cat example.py print u'Example: \u00F1' $ python example.py Example: ñ $ python example.py > /dev/null Trace...
[ "Pipes that don't lead to the terminal don't have an encoding, therefore you'll need to check sys.stdout.isatty() and encode if needed.\n" ]
[ 9 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002224130_python_unicode.txt
Q: Multiple database connections with Python + Pylons + SQLAlchemy I'm trying to implement the proper architecture for multiple databases under Python + Pylons. I can't put everything in the config files since one of the database connections requires the connection info from a previous database connection (sharding)...
Multiple database connections with Python + Pylons + SQLAlchemy
I'm trying to implement the proper architecture for multiple databases under Python + Pylons. I can't put everything in the config files since one of the database connections requires the connection info from a previous database connection (sharding). What's the best way to implement such an infrastructure?
[ "Pylons's template configures the database in config/environment.py, probably with the engine_from_config method. It finds all the config settings with a particular prefix and passes them as keyword arguments to create_engine.\nYou can just replace that with a few calls to sqlalchemy.create_engine() with the per-en...
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002205047_pylons_python.txt
Q: IPython demo mode I'm trying to use the IPython demo mode. I created a file called test.py containing: print 1 print 2 print 3 and then launched IPython and did the following: In [1]: from IPython.demo import LineDemo In [2]: d = LineDemo('test.py') In [3]: d() ********************* <test.py> block # 0 (5 remai...
IPython demo mode
I'm trying to use the IPython demo mode. I created a file called test.py containing: print 1 print 2 print 3 and then launched IPython and did the following: In [1]: from IPython.demo import LineDemo In [2]: d = LineDemo('test.py') In [3]: d() ********************* <test.py> block # 0 (5 remaining) *****************...
[ "There seems to be a bug in IPython. In demo.py in LineDemo.reload, the line that says:\nsrc_b = [l for l in self.fobj.readline() if l.strip()]\n\nshould say:\nsrc_b = [l for l in self.fobj.readlines() if l.strip()]\n\nCurrently it's trying to execute all the letters in the first line instead of...
[ 2, 0 ]
[]
[]
[ "demo", "ipython", "python" ]
stackoverflow_0002224082_demo_ipython_python.txt
Q: Lazy evaluation in Python? Between modules? I'm not sure if something like this is even possible in Python, but if it is it'd be really useful (at least to me in this instance). I have a test framework in which I want to keep the test configuration separate from the test commands. This is useful because it allow...
Lazy evaluation in Python? Between modules?
I'm not sure if something like this is even possible in Python, but if it is it'd be really useful (at least to me in this instance). I have a test framework in which I want to keep the test configuration separate from the test commands. This is useful because it allows you to mix and match configurations/tests witho...
[ "Python is dynamically typed, so this is nothing fancy:\nconfigMod.py:\n\n##### this is configMod.py #####\nmodTestArg1 = \"Brian\"\n\ndef runTest(testMod, *args, **kwargs):\n testMod.doTest(*args, **kwargs)\n\ntestMod.py:\n\n##### this is testMod.py #####\ndef doTest(name, address, city=\"San Francisco\"):\n ...
[ 1, 0 ]
[]
[]
[ "lazy_evaluation", "python", "testing" ]
stackoverflow_0002223025_lazy_evaluation_python_testing.txt
Q: How to extract signature from function reference in Python? Let's say I have a function in Python like so: def foo(x): pass According to Python, 'foo' alone is a function reference, right? >>> def foo(x): pass ... >>> foo <function foo at 0xb7f3d1b4> Is there any way I can examine the function reference to deter...
How to extract signature from function reference in Python?
Let's say I have a function in Python like so: def foo(x): pass According to Python, 'foo' alone is a function reference, right? >>> def foo(x): pass ... >>> foo <function foo at 0xb7f3d1b4> Is there any way I can examine the function reference to determine the number of arguments it expects?
[ "You need inspect.getfullargspec in py3k or inspect.getargspec in earlier versions.\n >>> def foo(x): pass\n\n>>> import inspect\n>>> inspect.getfullargspec(foo)\nFullArgSpec(args=['x'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002224428_python.txt
Q: How do I do text wrapping in pyCairo + Pango? What I need pyCairo to do is : generate an image of size 100x100 containing some text and an image from filesystem as background the text should be within a box which has text wrapping of size 20x20 with bottom left corner at (40,40). save this image A: You need t...
How do I do text wrapping in pyCairo + Pango?
What I need pyCairo to do is : generate an image of size 100x100 containing some text and an image from filesystem as background the text should be within a box which has text wrapping of size 20x20 with bottom left corner at (40,40). save this image
[ "You need to find a way to get the Pango context and set pango.Layout.set_wrap() and pango.Layout.set_width().\n" ]
[ 3 ]
[]
[]
[ "cairo", "pango", "python", "word_wrap" ]
stackoverflow_0001973990_cairo_pango_python_word_wrap.txt