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: undo write to file What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas? Thanks in advance! A: as others have noted, this doesn't ma...
Python: undo write to file
What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas? Thanks in advance!
[ "as others have noted, this doesn't make much sense, it's far better not to write until you have to. in your case, you can keep the 'writing pointer' one line behind your processing.\npseudocode:\npreviousItem = INVALID\nfor each item I:\n is I same as previousItem?\n then update previousItem with I\n else\...
[ 5, 4, 4, 0, 0 ]
[]
[]
[ "file", "python", "undo" ]
stackoverflow_0001479035_file_python_undo.txt
Q: How to build from the source? I cannot use sqlite3 (build python package). The reason of the is missing _sqlite3.so. I found that peoples had the same problem and they resolved it here. The solutions is given in one sentence: By building from source and moving the library to /usr/lib/python2.5/lib-dynload/ I ...
How to build from the source?
I cannot use sqlite3 (build python package). The reason of the is missing _sqlite3.so. I found that peoples had the same problem and they resolved it here. The solutions is given in one sentence: By building from source and moving the library to /usr/lib/python2.5/lib-dynload/ I resolved the issue. However, I d...
[ "Download the SQLite source here: SQLite Download Page\nExtract the tarball somewhere on your machine.\nNavigate to the expanded directory.\nRun:\n./configure\nmake\nmake install (sudo make install if you have permission issues)\n\nCopy the newly compiled files to your Python directory.\nThose directions are the si...
[ 3 ]
[]
[]
[ "build", "python", "sqlite" ]
stackoverflow_0001479265_build_python_sqlite.txt
Q: How to bind a TextField to an IBOutlet()? I'm trying to figure out how to update an NSTextField programatically. I've figured out how to get the current value of the Text Field from Python: myVar = objc.IBOutlet() .... self.myVar.stringValue() How do I set the value of myVar from the Python side and have the GUI ...
How to bind a TextField to an IBOutlet()?
I'm trying to figure out how to update an NSTextField programatically. I've figured out how to get the current value of the Text Field from Python: myVar = objc.IBOutlet() .... self.myVar.stringValue() How do I set the value of myVar from the Python side and have the GUI update? I'd like some sort of two way binding ...
[ "\nHow do I set the value of myVar from the Python side and have the GUI update?\n\nWhy would you want to? The nib loader set it to a control; if you set the variable, you would lose the control.\nTo set the value of the control, send it a setStringValue_ (or similar) message.\n" ]
[ 1 ]
[]
[]
[ "binding", "cocoa", "pyobjc", "python" ]
stackoverflow_0001479709_binding_cocoa_pyobjc_python.txt
Q: How to find which view is resolved from url in presence of decorators For debugging purposes, I'd like a quick way (e.g. in manage.py shell) of looking up which view that will be called as a result of a specific URL being requested. I know this is what django.core.urlresolvers.resolve does, but when having a decor...
How to find which view is resolved from url in presence of decorators
For debugging purposes, I'd like a quick way (e.g. in manage.py shell) of looking up which view that will be called as a result of a specific URL being requested. I know this is what django.core.urlresolvers.resolve does, but when having a decorator on the view function it will return that decorator. Example: >>>django...
[ "This isn't my area of expertise, but it might help. \nYou might be able to introspect Allow to find out which object it's decorating.\n>>>from django.core.urlresolvers import resolve\n>>>func, args, kwargs=resolve('/edit_settings/')\n>>>func\nAllow\n\nYou could try\n>>>func.func_name\n\nbut it might not return the...
[ 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0001476996_django_django_urls_python.txt
Q: Python: Grab the A record of any URI? I basically want to implement something where you can type in any URI ( I probably will only deal with http ) and I want to return the A record of the domain in the URI, I want the server's IP address. I know there's the ping command which most people use to look an ip addres...
Python: Grab the A record of any URI?
I basically want to implement something where you can type in any URI ( I probably will only deal with http ) and I want to return the A record of the domain in the URI, I want the server's IP address. I know there's the ping command which most people use to look an ip address up, but I also know there's 'host' and 'd...
[ "py> import urlparse,socket\npy> p = urlparse.urlparse(\"http://stackoverflow.com/questions/1480183\")\npy> p\n('http', 'stackoverflow.com', '/questions/1480183', '', '', '')\npy> host=p[1]\npy> ai=socket.gethostbyname(host)\npy> socket.gethostbyname(host)\n'69.59.196.211'\n\n" ]
[ 5 ]
[]
[]
[ "dns", "host", "ip", "python", "url" ]
stackoverflow_0001480183_dns_host_ip_python_url.txt
Q: Is there anyway to use TestCase.assertEqual() outside of a TestCase? I have a utility class that stores methods that are useful for some unit test cases. I want these helper methods to be able to do asserts/fails/etc., but it seems I can't use those methods because they expect TestCase as their first argument... I...
Is there anyway to use TestCase.assertEqual() outside of a TestCase?
I have a utility class that stores methods that are useful for some unit test cases. I want these helper methods to be able to do asserts/fails/etc., but it seems I can't use those methods because they expect TestCase as their first argument... I want to be able to store the common methods outside of the testcase code ...
[ "This is often accomplished with multiple inheritance:\ncommon_methods.py: \nclass CommonMethods:\n def common_method1(self, stuff):\n blah=stuff\n self.failUnless(len(blah) > 5)\n ...\n...\n\nunittest_foo.py:\nimport unittest\nfrom common_methods import CommonMethods\nclass TestPayments(unittest.Test...
[ 4, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001480144_python_unit_testing.txt
Q: Django autoreload for development on every request? Can a Django app be reloaded on every request ? This is very useful for development. Ruby on Rails does just this. runserver reloads, but it reloads slow, and still sometime one has to stop and start it again for some changes to show up. (For example changes i...
Django autoreload for development on every request?
Can a Django app be reloaded on every request ? This is very useful for development. Ruby on Rails does just this. runserver reloads, but it reloads slow, and still sometime one has to stop and start it again for some changes to show up. (For example changes in admin.) mod_wsgi can autoreload on Linux by touching *....
[ "Of course it is going to be slow to reload, it has to load all the application code again and not just the one file. Django is not PHP, so don't expect it to work the same.\nIf you really want Django to reload on every request regardless, then use CGI and a CGI/WSGI bridge. It is still going to be slow though as C...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001478061_django_python.txt
Q: What is Python's Fabric equivalent in other languages? Can someone tell me what's the equivalent of Python's Fabric in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage. A: These tools are for performing common remote administration tas...
What is Python's Fabric equivalent in other languages?
Can someone tell me what's the equivalent of Python's Fabric in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage.
[ "These tools are for performing common remote administration tasks usually as part of automated builds - a Ruby equivalent might be Capistrano, JSch in Java.\n", "It helps you to run commands on a lot of remote machines via SSH from your box. So you don't have to login on each one and copypaste the output of some...
[ 6, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001479632_python.txt
Q: How can I, on some global keystroke, paste some text to current active application in linux with Python or C++ I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low leve...
How can I, on some global keystroke, paste some text to current active application in linux with Python or C++
I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. How i can do this with Python or C++ ?
[ "Probably you want to hack xmon...\n\nAFAIK there is no easy way to hook the X protocol. You will need to do \"deep packet inspection\", which would be fairly easy in the application event loop but not so easy, as you want, \"like a daemon\", or on \"global keystroke[s]\".\nSo, I know this is really brute force and...
[ 1, 0 ]
[]
[]
[ "c++", "linux", "python", "xserver" ]
stackoverflow_0001480655_c++_linux_python_xserver.txt
Q: Python code seems to be getting executed out of order At work I have a programming language encoded in a database record. I'm trying to write a print function in python to display what the record contains. This is the code I'm having trouble with: # Un-indent the block if necessary. if func_option[row.FRM...
Python code seems to be getting executed out of order
At work I have a programming language encoded in a database record. I'm trying to write a print function in python to display what the record contains. This is the code I'm having trouble with: # Un-indent the block if necessary. if func_option[row.FRML_FUNC_OPTN] in ['Endif', 'Else']: self.indent = se...
[ "Just because it is a \"script language\" doesn't mean you have to live without a full debugger with breakpoints !\n\nInstall eric3\nLoad your code\nPress \"debug\" ;)\n\nAlso, you seem new to Python, so here are a few hints :\n\nyou can multiply strings, much faster than a loop\nread how array access works, use [-...
[ 2, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0001476722_debugging_python.txt
Q: Would python be an appropriate choice for a video library for home use software I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software. My question i...
Would python be an appropriate choice for a video library for home use software
I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software. My question is, is python appropriate to create this software or do I need something like c++.
[ "Python is perfectly appropriate for such tasks - indeed the most popular video site, YouTube, is essentially programmed in Python (using, of course, lower-level components called from Python for such tasks as web serving, relational db, video transcoding -- there are plenty of such reusable opensource components f...
[ 6, 1, 1, 1, 1 ]
[]
[]
[ "python", "video", "video_library" ]
stackoverflow_0001477626_python_video_video_library.txt
Q: how to configure apache on XP for python 2.6.2 and what do you prefer, python with framework/without? I am starting python today. It will be my pleasure to have your help. A: About a framework - choose the one you'll like. You can find most of them on Python wiki. About Apache - if you choose a framework, it'll ...
how to configure apache on XP for python 2.6.2 and what do you prefer, python with framework/without?
I am starting python today. It will be my pleasure to have your help.
[ "About a framework - choose the one you'll like. You can find most of them on Python wiki.\nAbout Apache - if you choose a framework, it'll probably have some kind of development web server built-in, with better debugging capabilities than Apache installation. If you really want Apache, then you could install and c...
[ 1, 0 ]
[]
[]
[ "apache", "python", "windows_xp" ]
stackoverflow_0001481309_apache_python_windows_xp.txt
Q: Python - Same line of code only works the second time it called? Sorry I couldn't really describe my problem much better in the title. I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me. I am running Ubuntu 8.10 and python 2.5.2 First I import xml.dom...
Python - Same line of code only works the second time it called?
Sorry I couldn't really describe my problem much better in the title. I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me. I am running Ubuntu 8.10 and python 2.5.2 First I import xml.dom Then I create an instance of a minidom (using its fully qaulified nam...
[ "The problem is in apport_python_hook.apport_excepthook() as a side effect it imports xml.dom.minidom.\nWithout apport_except_hook:\n>>> import sys\n>>> sys.excepthook = sys.__excepthook__\n>>> import xml.dom\n>>> xml.dom.minidom\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttribut...
[ 7, 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001481264_python.txt
Q: Generating random sentences from custom text in Python's NLTK? I'm having trouble with the NLTK under Python, specifically the .generate() method. generate(self, length=100) Print random text, generated using a trigram language model. Parameters: * length (int) - The length of text to generate (default=100) H...
Generating random sentences from custom text in Python's NLTK?
I'm having trouble with the NLTK under Python, specifically the .generate() method. generate(self, length=100) Print random text, generated using a trigram language model. Parameters: * length (int) - The length of text to generate (default=100) Here is a simplified version of what I am attempting. import nltk w...
[ "To generate random text, U need to use Markov Chains\ncode to do that: from here\nimport random\n\nclass Markov(object):\n\n def __init__(self, open_file):\n self.cache = {}\n self.open_file = open_file\n self.words = self.file_to_words()\n self.word_size = len(self.words)\n self.database()\n\n\n ...
[ 13, 7, 1, 0 ]
[ "Maybe you can sort the tokens array randomly before generating a sentence.\n" ]
[ -1 ]
[ "nltk", "python", "random" ]
stackoverflow_0001150144_nltk_python_random.txt
Q: set URL when enter site - pylons My problem is that when a user enter my website like: www.mywebsite.com I use pylonshq I want the URL to be change to /#home if its possible via. map.connect. I have no idéa how to fix it via. python, so therefore a guide or maybe some samples would be a help. Right now it looks l...
set URL when enter site - pylons
My problem is that when a user enter my website like: www.mywebsite.com I use pylonshq I want the URL to be change to /#home if its possible via. map.connect. I have no idéa how to fix it via. python, so therefore a guide or maybe some samples would be a help. Right now it looks like this: map.connect('/', controller...
[ "Simplest solution is to add js, something like this:\nlocation.url += '#home'.\nOr issue redirect with anchor included (but this won't work in IE).\n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001481363_pylons_python.txt
Q: Efficient method to determine location on a grid(array) I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle... Currently I am checking like so: # left column, not a corner ...
Efficient method to determine location on a grid(array)
I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle... Currently I am checking like so: # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: ...
[ "def location(x,y,dim_x,dim_y):\n index = 1*(y==0) + 2*(y==dim_y-1) + 3*(x==0) + 6*(x==dim_x-1)\n return [\"interior\",\"top\",\"bottom\",\"left\",\"top-left\",\n \"bottom-left\",\"right\",\"top-right\",\"bottom-right\"][index]\n\n", "# initially:\nmethod_list = [\n bottom_left, bottom, bottom...
[ 7, 3, 1, 0, 0, 0 ]
[]
[]
[ "arrays", "list", "performance", "python" ]
stackoverflow_0001480406_arrays_list_performance_python.txt
Q: Python: This should be impossible, shouldn't it? This is part of my Django application which is saving a user's profile in a special way. class SomeUser: def __init__(self, request): self.logged_in = True self.profile = request.user.get_profile() self.favorites = self.profile.favorites...
Python: This should be impossible, shouldn't it?
This is part of my Django application which is saving a user's profile in a special way. class SomeUser: def __init__(self, request): self.logged_in = True self.profile = request.user.get_profile() self.favorites = self.profile.favorites.all().values_list('pk', flat=True) def save(self...
[ "I'm guessing self.favorites is some kind of iterator, maybe a django QuerySet.\nThe first str() runs the iterator and empties it out\nThe second str() runs the iterator again and it is empty\n", "With just this snippet of code, it can't happen (assuming self.favorites and self.hello aren't properties). My guess...
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001481545_django_python.txt
Q: Making a string the name of an instance/object I've been struggling for a couple of days now with the following... I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunctio...
Making a string the name of an instance/object
I've been struggling for a couple of days now with the following... I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the str() method. So, to give an example. Let...
[ "If you just want to introduce new named variables in a module namespace, then setattr may well be the easiest way to go:\nimport sys\n\nclass Species:\n def __init__(self, name, legs, stomachs):\n self.name = name\n self.legs = legs\n self.stomachs = stomachs\n\ndef create_species():\n n...
[ 6, 1, 0, 0 ]
[]
[]
[ "object", "python", "string", "variables" ]
stackoverflow_0001479490_object_python_string_variables.txt
Q: Socket program Python vs C++ (Winsock) I have python program which works perfectly for internet chatting. But program built on similar sockets in C++ do not work over internet. Python program import thread import socket class p2p: def __init__(self): socket.setdefaulttimeout(50) self.port = 30...
Socket program Python vs C++ (Winsock)
I have python program which works perfectly for internet chatting. But program built on similar sockets in C++ do not work over internet. Python program import thread import socket class p2p: def __init__(self): socket.setdefaulttimeout(50) self.port = 3000 #Destination IP HERE se...
[ "Per the docs, sendto returns a number that's >0 (number of bytes sent) for success, <0 for failure, and in the latter case you use WSAGetLastError for more information. So try saving the sendto result, printing it (as well as the size of the data you're trying to send), and in case of error print the last-error co...
[ 1 ]
[]
[]
[ "c++", "python", "sockets", "winsock" ]
stackoverflow_0001481103_c++_python_sockets_winsock.txt
Q: How to add header while making soap request using soappy I have WSDL file, using that i wanted to make soap request which will look exactly like this -- <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soa...
How to add header while making soap request using soappy
I have WSDL file, using that i wanted to make soap request which will look exactly like this -- <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header>...
[ "Not tested, but I believe you can use the method the docs suggest to add soap headers, i.e., make and prep a SOAPpy.Header instance, then use server = server._hd (hd) to get a proxy equipped with it (though in your case that does seem to be a workaround attempt to broken WSDL, as you say -- might it be better to f...
[ 0 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0001481313_python_soap_soappy.txt
Q: pythonic format for indices I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16] Ideally I would also be able to represent infinite sequences. Is there an existing standard way of doing this? Or a good library? Or can you propose your...
pythonic format for indices
I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16] Ideally I would also be able to represent infinite sequences. Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? thanks! Edit: Wow! ...
[ "You don't need a string for that, This is as simple as it can get:\nfrom types import SliceType\n\nclass sequence(object):\n def __getitem__(self, item):\n for a in item:\n if isinstance(a, SliceType):\n i = a.start\n step = a.step if a.step else 1\n ...
[ 7, 3, 2, 1, 1 ]
[]
[]
[ "indexing", "python", "sequence", "set" ]
stackoverflow_0001481192_indexing_python_sequence_set.txt
Q: Why I cannot build a chain of methods? (method1.method2.method3) If I have the following code: import sqlite sqlite.connect('tmp.db').cursor().close() I get the following error message: Traceback (most recent call last): File "searchengine2.py", line 13, in ? sqlite.connect('tmp.db').cursor().close() File...
Why I cannot build a chain of methods? (method1.method2.method3)
If I have the following code: import sqlite sqlite.connect('tmp.db').cursor().close() I get the following error message: Traceback (most recent call last): File "searchengine2.py", line 13, in ? sqlite.connect('tmp.db').cursor().close() File "/usr/lib64/python2.4/site-packages/sqlite/main.py", line 280, in clo...
[ "Apparently the cursor keeps a weak reference to the connection (self.con). Because you chain the functions, the connection you've instantiated is out of scope as soon as you instantiate the cursor -- nothing holds a strong reference to the connection anymore, and the connection is eligible for garbage collection....
[ 3, 1 ]
[]
[]
[ "methods", "python", "sqlite" ]
stackoverflow_0001482270_methods_python_sqlite.txt
Q: Understanding this class in python. The operator % and formatting a float class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df'%precision) self.precision = precision self.scale = scale def toval(self, x): if ...
Understanding this class in python. The operator % and formatting a float
class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df'%precision) self.precision = precision self.scale = scale def toval(self, x): if x is not None: x = x * self.scale return x def fromstr...
[ ">>> precision=4\n>>> '%%1.%df'%precision\n'%1.4f'\n\n%% gets translated to %\n1 is printed as is\n%d prints precision as a decimal number\nf is printed literally\n", "In ('%%1.%df' % precision), the first %% yields a literal %, %d is substituted with precision, and f is inserted literally. Here's an example of h...
[ 2, 0, 0 ]
[]
[]
[ "class", "operators", "python" ]
stackoverflow_0001482383_class_operators_python.txt
Q: Google App Engine - ReferenceProperty() gives error - Generic reference - Polymodel Given a Polymodel in Google App Engine, likeso: from google.appengine.ext import db from google.appengine.ext.db import polymodel class Base(polymodel.PolyModel): def add_to_referer(self): Referer(target=self).put() class ...
Google App Engine - ReferenceProperty() gives error - Generic reference - Polymodel
Given a Polymodel in Google App Engine, likeso: from google.appengine.ext import db from google.appengine.ext.db import polymodel class Base(polymodel.PolyModel): def add_to_referer(self): Referer(target=self).put() class Referer(db.Model): target = db.ReferenceProperty() @classmethod def who_referr...
[ "Ah. I answered this immediately after I posted:\nThe file with Referer needs to import Base.\nPerhaps someone else will happen upon this quirk, so I'll leave this question open.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python", "referenceproperty" ]
stackoverflow_0001482435_google_app_engine_python_referenceproperty.txt
Q: What does it mean "weakly-referenced object no longer exists"? I am running a Python code and I get the following error message: Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in <bound method crawler.__del__ of <searchengine.crawler instance at 0x2b8c1f99ef80>> ignored Does anyb...
What does it mean "weakly-referenced object no longer exists"?
I am running a Python code and I get the following error message: Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in <bound method crawler.__del__ of <searchengine.crawler instance at 0x2b8c1f99ef80>> ignored Does anybody know what can it means? P.S. This is the code which produce the ...
[ "A normal AKA strong reference is one that keeps the referred-to object alive: in CPython, each object keeps the number of (normal) references to it that exists (known as its \"reference count\" or RC) and goes away as soon as the RC reaches zero (occasional generational mark and sweep passes also garbage-collect \...
[ 55, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001482141_python.txt
Q: In Python interpreter, return without " ' " In Python, how do you return a variable like: function(x): return x Without the 'x' (') being around the x? A: In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string. If you just ...
In Python interpreter, return without " ' "
In Python, how do you return a variable like: function(x): return x Without the 'x' (') being around the x?
[ "In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string.\nIf you just print the string, it will not be shown with quotes (unless the string has quotes in it).\n>>> 1 # just a number, so no quotes\n1\n>>> \"hi\" # just a string, dis...
[ 45, 2 ]
[]
[]
[ "interpreter", "python", "read_eval_print_loop" ]
stackoverflow_0001482649_interpreter_python_read_eval_print_loop.txt
Q: `xrange(2**100)` -> OverflowError: long int too large to convert to int xrange function doesn't work for large integers: >>> N = 10**100 >>> xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int >>> xrange(N, N+10) Traceback (most recent call last): ... OverflowError:...
`xrange(2**100)` -> OverflowError: long int too large to convert to int
xrange function doesn't work for large integers: >>> N = 10**100 >>> xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int >>> xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too large to convert to int Python 3.x: >>> N = 10**100 >>> r = ra...
[ "I believe there is no backport (Py 3's completely removed the int/long distinction, after all, but in 2.* it's here to stay;-) but it's not hard to hack your own, e.g....:\nimport operator\n\ndef wowrange(start, stop, step=1):\n if step == 0:\n raise ValueError('step must be != 0')\n elif step < 0:\n proce...
[ 19, 11, 9, 3, 1 ]
[]
[]
[ "biginteger", "python", "python_3.x", "range", "xrange" ]
stackoverflow_0001482480_biginteger_python_python_3.x_range_xrange.txt
Q: Auto create next Key in python dictionary Is there an easy way to create dictionary like associative array in php? in php i can do: > $x='a'; > while($x<d){ > $arr[]['Letter']=$x; > $x++ > } The interpreter adds automatically a new number into empty brackets "[]" so i can access letter b from $arr[1]...
Auto create next Key in python dictionary
Is there an easy way to create dictionary like associative array in php? in php i can do: > $x='a'; > while($x<d){ > $arr[]['Letter']=$x; > $x++ > } The interpreter adds automatically a new number into empty brackets "[]" so i can access letter b from $arr[1]['Letter'], etc. Is there a way to do same with...
[ "Edit: I'm stupid. Of course there is a way of doing this in Python. Like so:\nresult = [{'Letter': chr(i+97)} for i in range(26)]\n\nThat will give you a List. Which can be indexed with a number.\nSo result[1]['Letter'] will give you 'b'.\n", "Empty-brackets indexing is syntactically invalid in Python, but you c...
[ 3, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001483058_python.txt
Q: decypher with me that obfuscated MultiplierFactory This week on comp.lang.python, an "interesting" piece of code was posted by Steven D'Aprano as a joke answer to an homework question. Here it is: class MultiplierFactory(object): def __init__(self, factor=1): self.__factor = factor @property de...
decypher with me that obfuscated MultiplierFactory
This week on comp.lang.python, an "interesting" piece of code was posted by Steven D'Aprano as a joke answer to an homework question. Here it is: class MultiplierFactory(object): def __init__(self, factor=1): self.__factor = factor @property def factor(self): return getattr(self, '_%s__facto...
[ "Q1. Can we always access attributes in this fashion?\nA: No. It's only those attributes who start with double underscores. They get obfuscated in that way, to prevent accidental access/overriding from outside the class.\nQ2: Are we just changing the default value for factor argument in __init__ here?\nA: Yes.\nQ2:...
[ 1 ]
[]
[]
[ "obfuscation", "python", "python_datamodel" ]
stackoverflow_0001483085_obfuscation_python_python_datamodel.txt
Q: regex for character appearing at most once I want to check a string that contains the period, ".", at most once in python. A: [^.]*\.?[^.]*$ And be sure to match, don't search >>> dot = re.compile("[^.]*\.[^.]*$") >>> dot.match("fooooooooooooo.bar") <_sre.SRE_Match object at 0xb7651838> >>> dot.match("fooooo...
regex for character appearing at most once
I want to check a string that contains the period, ".", at most once in python.
[ "[^.]*\\.?[^.]*$\n\nAnd be sure to match, don't search\n>>> dot = re.compile(\"[^.]*\\.[^.]*$\")\n>>> dot.match(\"fooooooooooooo.bar\")\n<_sre.SRE_Match object at 0xb7651838>\n>>> dot.match(\"fooooooooooooo.bar.sad\") is None\nTrue\n>>>\n\nEdit:\nIf you consider only integers and decimals, it's even easier:\ndef va...
[ 10, 5, 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001483108_python_regex.txt
Q: How to split data into equal size packets having variable header size.. I am building peer to peer application in python. Its going to work over UDP. I have function called getHeader(packetNo,totalPackets) which returns me the header for that packet.Depending on size of header I am chopping data, attaching data t...
How to split data into equal size packets having variable header size..
I am building peer to peer application in python. Its going to work over UDP. I have function called getHeader(packetNo,totalPackets) which returns me the header for that packet.Depending on size of header I am chopping data, attaching data to header and getting same packet size. Header size is not fixed because length...
[ "Don't use plain-text. Make packet's header a two packed 4-byte (or 8-byte, depending on how many packets you expect) integers, e.g.\nimport struct\nheader = struct.pack('!II', packetNo, totalPackets)\n\nHere's documentation for struct module.\n", "Why not zero-pad your number of packets, so that the header becom...
[ 2, 0 ]
[]
[]
[ "packets", "python", "sockets", "udp" ]
stackoverflow_0001483243_packets_python_sockets_udp.txt
Q: How to except SyntaxError? I would like to except the error the following code produces, but I don't know how. from datetime import datetime try: date = datetime(2009, 12a, 31) except: print "error" The code above is not printing "error". That's what I would like to be able to do. edit: The reason I woul...
How to except SyntaxError?
I would like to except the error the following code produces, but I don't know how. from datetime import datetime try: date = datetime(2009, 12a, 31) except: print "error" The code above is not printing "error". That's what I would like to be able to do. edit: The reason I would like to check for syntax error...
[ "command-line \"parameters\" are strings. if your code is:\ndatetime(2009, '12a', 31)\n\nit won't produce SyntaxError. It raises TypeError.\nAll command-line parameters are needed to be cleaned up first, before use in your code. for example like this:\nmonth = '12'\ntry:\n month = int(month)\nexcept ValueError:\...
[ 10, 4, 3 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0001483343_exception_handling_python.txt
Q: Export QT Menu to text I was wondering if there is a way to convert my QT (version 4.50) menu and all its submenus into a text document in something similar to the following format: Menu 1 Sub Menu 2 Menu 2 sub menu 3 sub menu 4 sub menu 1 A: You might want to look at QObject::findChildren, and use it like ...
Export QT Menu to text
I was wondering if there is a way to convert my QT (version 4.50) menu and all its submenus into a text document in something similar to the following format: Menu 1 Sub Menu 2 Menu 2 sub menu 3 sub menu 4 sub menu 1
[ "You might want to look at QObject::findChildren, and use it like this:\nsubmenus = mainwindow.menuBar().findChildren(QAction)\n\nDepending on how you construct your menus you might have to use QMenu as a parameter aswell.\nAlso depending on your usage some sub menus could have no parent (depending on how you const...
[ 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0001481999_pyqt_python_qt.txt
Q: Why can't I crop this image in Python PIL? (simple syntax problem?) from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) It seems like there's nothing wrong with this, right? That last line will result in an error and won't continue, but I don't know what the erro...
Why can't I crop this image in Python PIL? (simple syntax problem?)
from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) It seems like there's nothing wrong with this, right? That last line will result in an error and won't continue, but I don't know what the error is because it's AJAX and I can't debug ATM.
[ "If your controller is dealing with strings because the crop data is coming in via an ajax GET, it might be worth trying to make them into integers before applying the crop. Example from my terminal...\nTrinity:~ kelvin$ python\nPython 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) \n[GCC 4.0.1 (Apple Computer, Inc. bui...
[ 4, 1, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0001483393_image_python_python_imaging_library.txt
Q: Grab an image via the web and save it with Python I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is: What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). ...
Grab an image via the web and save it with Python
I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is: What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). I want it to be stored into memory until it's done with...
[ "urllib (simple but a bit rough) and urllib2 (powerful but a bit more complicated) are the recommended standard library modules for grabbing data from a URL (either to memory or to disk). For simple-enough needs, x=urllib.urlopen(theurl) will give you an object that lets you access the response headers (e.g. to fi...
[ 3, 1, 0, 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0001482600_image_python.txt
Q: python _+ django, is it compiled code? Just looking into python from a .net background. Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated? does pretty much every web host (unix) support django and python? A: There are many implemen...
python _+ django, is it compiled code?
Just looking into python from a .net background. Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated? does pretty much every web host (unix) support django and python?
[ "There are many implementations of the Python language; the three that are certainly solid, mature and complete enough for production use are CPython, IronPython, and Jython. All of them are typically compiled to some form of bytecode, also known as intermediate code. The compilation from source to bytecode may tak...
[ 11, 2, 2, 1, 0 ]
[ "The Python is interpreted language. But you can compile the python program into a Unix executable using Freeze.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001483685_python.txt
Q: List of Lists in python? I need a good function to do this in python. def foo(n): # do somthing return list_of_lists >> foo(6) [[1], [2,3], [4,5,6]] >> foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] A: def foo(n): lol = [ [] ] i = 1 for x in range(n): if len(lol[-1]) >= i...
List of Lists in python?
I need a good function to do this in python. def foo(n): # do somthing return list_of_lists >> foo(6) [[1], [2,3], [4,5,6]] >> foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]]
[ "def foo(n):\n lol = [ [] ]\n i = 1\n for x in range(n):\n if len(lol[-1]) >= i:\n i += 1\n lol.append([])\n lol[-1].append(x)\n return lol\n\n", "def foo(n):\n i = 1\n while i <= n:\n last = int(i * 1.5 + 1)\n yield range(i, last)\n i = last\n\nlist(foo(3))\n\nWhat ...
[ 9, 8, 5, 3, 1, 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0001482967_list_list_comprehension_python.txt
Q: Python Script to find instances of a set of strings in a set of files I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt; TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... This helps me with I18n, the issue i...
Python Script to find instances of a set of strings in a set of files
I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt; TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... This helps me with I18n, the issue is that my application is now a lot larger and has evolved. As such a lot of...
[ "Assuming the files are of reasonable size (as source files will be) so you can easily read them in memory, and that you're looking for the parts in quotes right of the = signs:\nimport collections\nfiles_by_str = collections.defaultdict(list)\n\nthestrings = []\nwith open('Strings.txt') as f:\n for line in f:\n ...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "find", "internationalization", "python" ]
stackoverflow_0001483830_find_internationalization_python.txt
Q: Get offset of current buffer in vim (in particular, via python scripting) i want to get the offset of the current cursor position the current selection range in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful. I have used v...
Get offset of current buffer in vim (in particular, via python scripting)
i want to get the offset of the current cursor position the current selection range in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful. I have used vim.current.. before for doing scripting, but it uses lines and columns rather t...
[ "If your vim is compiled with the +byte_offset option, then in a Python script after the usual import vim, you can use, e.g.:\nvim.eval('line2byte(line(\".\"))+col(\".\")')\n\nto get the byte offset from start of file of the cursor position, and similarly for other marks. More generally, if you have a line/column p...
[ 16, 13 ]
[]
[]
[ "offset", "python", "vim" ]
stackoverflow_0001483796_offset_python_vim.txt
Q: python PIL - background displayed opaque instead of transparent I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so...
python PIL - background displayed opaque instead of transparent
I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so. However, the avatar is displayed on a black and opaque background; ...
[ "You're generating a JPG image. JPEGs don't support background transparency. You need to generate a PNG image to support transparencies.\n", "That is because JPEG cannot save transparency informations which are contained in a RGBA image. You may want to save the avatar to a format like PNG which is able to keep...
[ 5, 5 ]
[]
[]
[ "django", "image", "python" ]
stackoverflow_0001484101_django_image_python.txt
Q: Replace/delete field using sqlalchemy Using postgres in python, How do I replace all fields from the same column that match a specified value? For example, let's say I want to replace any fields that match "green" with "red" in the "Color" column. How to delete all fields from the same column that match a specif...
Replace/delete field using sqlalchemy
Using postgres in python, How do I replace all fields from the same column that match a specified value? For example, let's say I want to replace any fields that match "green" with "red" in the "Color" column. How to delete all fields from the same column that match a specified value? For example, I'm trying to delet...
[ "Ad1. You need something like this:\nsession.query(Foo).filter_by(color = 'green').update({ 'color': 'red' })\nsession.commit()\n\nAd2. Similarly:\nsession.query(Foo).filter_by(color = 'green').delete()\nsession.commit()\n\nYou can find the querying documentation here and here.\n" ]
[ 9 ]
[]
[]
[ "postgresql", "python", "replace", "sqlalchemy" ]
stackoverflow_0001484235_postgresql_python_replace_sqlalchemy.txt
Q: how % applies to this method in Python? From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder. The other use is a string formatter. So I can do something like '...
how % applies to this method in Python?
From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder. The other use is a string formatter. So I can do something like 'Hi there %s' % name, where name is a list of ...
[ "The string % operator is simpler than you are imagining. It takes a string on the left side, and a variety of things on the right side. The left side doesn't have to be a literal string, it can be a variable, or the result of another computation. Any expression that results in a string is valid for the left sid...
[ 4, 3, 0, 0, 0 ]
[]
[]
[ "class", "python", "string_formatting" ]
stackoverflow_0001484375_class_python_string_formatting.txt
Q: How do I use PyMock and Nose with Django models? I'm trying to do TDD with PyMock, but I keep getting error when I use Nose and execute core.py from command line: "ERROR: Failure: ImportError (Settings cannot be imported, because environment variable DJA NGO_SETTINGS_MODULE is undefined.)" If I remove "from cms.mo...
How do I use PyMock and Nose with Django models?
I'm trying to do TDD with PyMock, but I keep getting error when I use Nose and execute core.py from command line: "ERROR: Failure: ImportError (Settings cannot be imported, because environment variable DJA NGO_SETTINGS_MODULE is undefined.)" If I remove "from cms.models import Entry" from the unit test module I created...
[ "You do need DJANGO_SETTINGS_MODULE defined in order to run core.py -- why don't you just export DJANGO_SETTINGS_MODULE=whatever in your bash session before starting nose?\n" ]
[ 4 ]
[]
[]
[ "django", "nose", "python", "unit_testing" ]
stackoverflow_0001484293_django_nose_python_unit_testing.txt
Q: Ñ not displayed in Google App Engine website I'm using Google App Engine to build a website and I'm having problems with special characters. I think I've reduced the problem to this two code samples: request = urlfetch.fetch( url=self.WWW_INFO, payload=urllib.urlencode(inputs), method=urlfetch.P...
Ñ not displayed in Google App Engine website
I'm using Google App Engine to build a website and I'm having problems with special characters. I think I've reduced the problem to this two code samples: request = urlfetch.fetch( url=self.WWW_INFO, payload=urllib.urlencode(inputs), method=urlfetch.POST, headers={'Content-Type': 'application/x-...
[ "You need to get the charset from the content-type header in the fetch's result, use it to decode the bytes into Unicode, then, on the response, set the header with your favorite encoding (I do suggest utf-8 -- no good reason to do otherwise) and emit the encoding of the Unicode text via that codec. The pass throu...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "unicode", "utf_8" ]
stackoverflow_0001484427_google_app_engine_python_unicode_utf_8.txt
Q: Python process pool and scope I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process ...
Python process pool and scope
I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process if it runs too long (which i cant d...
[ "Did you read the programming guidelines? There is lots of stuff in there about global variables. There are even more limitations under Windows. You don't say which platform you are running on, but this could be the problem if you are running under Windows. From the above link\n\nGlobal variables\nBear in mind ...
[ 3, 2, 0 ]
[]
[]
[ "pool", "python" ]
stackoverflow_0001484310_pool_python.txt
Q: how are these two variables unpacked? Through tutorials I had learned that you can define two variables in the same statement, e.g.: In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' well how does that apply to here? fh, opened = cbook.to_filehandle(fname, 'w', return_opened =...
how are these two variables unpacked?
Through tutorials I had learned that you can define two variables in the same statement, e.g.: In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' well how does that apply to here? fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) I prodded further: In [18]: fh Out[...
[ "My guess is that the function internally looks something like this:\ndef to_filehandle(filename, mode, return_opened=False):\n # do something to open the file and set opened\n # to True if it worked, False otherwise\n if return_opened:\n return the_filehandle, opened\n else:\n return the_...
[ 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0001484748_python_variables.txt
Q: GTK Twitter Client I am learning Python and PyGTK. I'm trying to write a Twitter client. Which widget is best suited for displaying the Tweets (Timeline). I can do it easily with textview but it doesn't support sub widgets to display users image. Tried using TreeView but it seems to be an overkill and is too comp...
GTK Twitter Client
I am learning Python and PyGTK. I'm trying to write a Twitter client. Which widget is best suited for displaying the Tweets (Timeline). I can do it easily with textview but it doesn't support sub widgets to display users image. Tried using TreeView but it seems to be an overkill and is too complex. I'm using Glade
[ "You could try Webkit (the browser rendering engine) using pywebkitgtk. It let's you develop in web technologies (HTML, CSS, JS) on the desktop. I think Gwibber, the microblogging client, uses it.\nThe widget you'd have to use is webkit.WebView. I'm not able to post more links here, just google for \"HOWTO Create P...
[ 5, 3, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0001392872_gtk_pygtk_python.txt
Q: Djapian - filtering results I use Djapian to search for object by keywords, but I want to be able to filter results. It would be nice to use Django's QuerySet API for this, for example: if query.strip(): results = Model.indexer.search(query).prefetch() else: results = Model.objects.all() results = results....
Djapian - filtering results
I use Djapian to search for object by keywords, but I want to be able to filter results. It would be nice to use Django's QuerySet API for this, for example: if query.strip(): results = Model.indexer.search(query).prefetch() else: results = Model.objects.all() results = results.filter(somefield__lt=somevalue) r...
[ "I went through its source and found that Djapian has a filter method that can be applied to its results. I have just tried the below code and it seems to be working. \nMy indexer is as follows:\nclass MarketIndexer( djapian.Indexer ):\n\n fields = [ 'name', 'description', 'tags_string', 'state']\n tags = [('...
[ 4, 0 ]
[]
[]
[ "django", "full_text_search", "python", "search", "xapian" ]
stackoverflow_0001483874_django_full_text_search_python_search_xapian.txt
Q: Piping output of subprocess.call to progress bar I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. ...
Piping output of subprocess.call to progress bar
I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. Now when the user has selected the device to burn wit...
[ "You can use glib.io_add_watch() to watch for output on the pipes connected to stdout and stderr in the subprocess object.\nproc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout_id = glib.io_add_watch(proc.stdout, glib.IO_IN|glib.IO_HUP, stdout_cb)\nstderr_id = glib.io_add_watch(p...
[ 3, 1, 0, 0 ]
[]
[]
[ "multithreading", "progress_bar", "pygtk", "python", "subprocess" ]
stackoverflow_0001284196_multithreading_progress_bar_pygtk_python_subprocess.txt
Q: HTML tag replacement using regex and python I have a Python script that will look at an HTML file that has the following format: <DOC> <HTML> ... </HTML> </DOC> <DOC> <HTML> ... </HTML> </DOC> How do I remove all HTML tags (replace the tags with '') with the exception of the opening and closing DOC tags using reg...
HTML tag replacement using regex and python
I have a Python script that will look at an HTML file that has the following format: <DOC> <HTML> ... </HTML> </DOC> <DOC> <HTML> ... </HTML> </DOC> How do I remove all HTML tags (replace the tags with '') with the exception of the opening and closing DOC tags using regex in Python? Also, if I want to retain the alt-t...
[ "For what you are trying to accomplish I would use BeautifulSoup rather than regex.\nhttp://www.crummy.com/software/BeautifulSoup/\n", "Check out lxml, a really nice python library for dealing with xml. You can use drop_tag to accomplish what you are looking for.\n\nfrom lxml import html \nh = html.fragment_froms...
[ 3, 2, 1 ]
[]
[]
[ "html", "python", "regex", "tags" ]
stackoverflow_0001484575_html_python_regex_tags.txt
Q: Better resources to learn buildout I am trying to grasp a bit more of buildout with this tutorial, but unlike a tutorial, it seems like a cut and paste of presentation slides. I don't have a really clear idea of what the purpose of buildout is, and how it positions itself with scons and setuptools. Would you be s...
Better resources to learn buildout
I am trying to grasp a bit more of buildout with this tutorial, but unlike a tutorial, it seems like a cut and paste of presentation slides. I don't have a really clear idea of what the purpose of buildout is, and how it positions itself with scons and setuptools. Would you be so kind to provide details on these issue...
[ "I quite like the Plone Buildout Tutorial.\nIt gives a reasonable overview of how it all works and the ways in which you can extend a simple buildout file.\nHere is the new link to Plone Buildout Tutorial.\n", "The most useful resource that I found so far are the videos from pycon 2009 on Setuptools, Distutils an...
[ 6, 3 ]
[]
[]
[ "buildout", "python", "resources" ]
stackoverflow_0001369664_buildout_python_resources.txt
Q: Wildcard for PyGTK States How do I combine: button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_SELECTED, gtk.gdk.color_parse("Green")) etc. Into a one-liner wildcard covering all of the possible states (See D...
Wildcard for PyGTK States
How do I combine: button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_SELECTED, gtk.gdk.color_parse("Green")) etc. Into a one-liner wildcard covering all of the possible states (See Doc)
[ "I do not think you can do that. You can still do it with fewer lines though:\nstates = [gtk.STATE_NORMAL, gtk.STATE_ACTIVE, gtk.STATE_PRELIGHT,\n gtk.STATE_SELECTED, gtk.STATE_INSENSITIVE]\n\nfor state in states:\n button.modify_bg(state, gtk.gdk.color_parse(\"Green\"))\n\n", "EDIT:\nMaybe this comes...
[ 1, 0 ]
[]
[]
[ "pygtk", "python", "state" ]
stackoverflow_0001484339_pygtk_python_state.txt
Q: Best approach to a command line proxy? I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router...
Best approach to a command line proxy?
I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router/switch lab in which the user is given remot...
[ "Python is not my primary language, so I'll leave that part of the answer for others. I do alot of security work, though, and I would urge a \"white list\" approach, not a \"black list\" approach. In other words, pick a set of safe commands and forbid all others. This is much much easier than trying to think of all...
[ 6, 0, 0, 0 ]
[]
[]
[ "command_line", "python", "regex" ]
stackoverflow_0001482367_command_line_python_regex.txt
Q: Using mechanize to visit a site that requires SSL I need to visit a site (https://*) that requires me to install two certificates in Firefox before I can visit it successfully. One I can export as a .p12 file (Client Certificate), and one is a .crt file (CA Certificate). If I try accessing this site without these ...
Using mechanize to visit a site that requires SSL
I need to visit a site (https://*) that requires me to install two certificates in Firefox before I can visit it successfully. One I can export as a .p12 file (Client Certificate), and one is a .crt file (CA Certificate). If I try accessing this site without these certificates, I get a "failed handshake error". How do ...
[ "I'd suggest you use webdriver to automate Firefox. It has a Python interface too.\n" ]
[ 1 ]
[]
[]
[ "mechanize", "python", "ssl", "ssl_certificate" ]
stackoverflow_0001485571_mechanize_python_ssl_ssl_certificate.txt
Q: With python.multiprocessing, how do I create a proxy in the current process to pass to other processes? I'm using the multiprocessing library in Python. I can see how to define that objects returned from functions should have proxies created, but I'd like to have objects in the current process turned into proxies...
With python.multiprocessing, how do I create a proxy in the current process to pass to other processes?
I'm using the multiprocessing library in Python. I can see how to define that objects returned from functions should have proxies created, but I'd like to have objects in the current process turned into proxies so I can pass them as parameters. For example, running the following script: from multiprocessing import cur...
[ "Why do you say serve_forever is not supported?\nmanager = Mymanager()\ns = manager.get_server()\ns.serve_forever()\n\nshould work.\nSee managers.BaseManager.get_server doc for official examples.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "proxy", "python", "python_multiprocessing" ]
stackoverflow_0001458205_multiprocessing_proxy_python_python_multiprocessing.txt
Q: Global statements v. variables available throughout a classes I try to avoid "global" statements in python and Do you use the "global" statement in Python? suggests this is a common view. Values go into a function through its arguments and come out through its return statement (or reading/writing files or excepti...
Global statements v. variables available throughout a classes
I try to avoid "global" statements in python and Do you use the "global" statement in Python? suggests this is a common view. Values go into a function through its arguments and come out through its return statement (or reading/writing files or exceptions or probably something else I'm forgetting). Within a class, sel...
[ "self.variable is not global to the class, it's global to the instance. There's a big difference:\nclass MyClass:\n def __init__(self, a):\n self.a = a\n\nmc1 = MyClass(1)\nmc2 = MyClass(2)\nassert mc1.a == 1\nassert mc2.a == 2\n\nYou should definitely use self to encapsulate data in your classes. \nTha...
[ 1, 1 ]
[ "Ideally, no instance-wide variables would be used and everything would be passed as a parameter and well-documented in comments. That being said, it can get very tedious to comment every little thing and method parameter lists can start to look ridiculous (unless you have a hierarchy of partially-applied methods)....
[ -1 ]
[ "python" ]
stackoverflow_0001486708_python.txt
Q: Type of object from udp buffer in python using metaclasses/reflection Is it possible to extract type of object or class name from message received on a udp socket in python using metaclasses/reflection ? The scenario is like this: Receive udp buffer on a socket. The UDP buffer is a serialized binary string(a mess...
Type of object from udp buffer in python using metaclasses/reflection
Is it possible to extract type of object or class name from message received on a udp socket in python using metaclasses/reflection ? The scenario is like this: Receive udp buffer on a socket. The UDP buffer is a serialized binary string(a message). But the type of message is not known at this time. So can't de-serial...
[ "What you receive from the udp socket is a byte string -- that's all the \"type of object or class name\" that's actually there. If the byte string was built as a serialized object (e.g. via pickle, or maybe marshal etc) then you can deserialize it back to an object (using e.g. pickle.loads) and then introspect to...
[ 2, 0, 0 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0001487582_python_sockets_udp.txt
Q: How to build a mini-network of small programs feeding each other data? I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure h...
How to build a mini-network of small programs feeding each other data?
I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.
[ "Stick with traditional simulation structures, at least at first\nIs it your goal to write an asynchronous system as an exercise? If so, then I guess you have to implement at least a multi-threaded if not multi-process or network system.\nBut if it's really a simulation, and what you want are the analysis results, ...
[ 5, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "simulation" ]
stackoverflow_0001484658_python_simulation.txt
Q: Case-insensitive comparison of sets in Python I have two sets (although I can do lists, or whatever): a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) I want to get: frozenset(['Today']) or at least: frozenset(['today']) The second option is doable if I lowercase every...
Case-insensitive comparison of sets in Python
I have two sets (although I can do lists, or whatever): a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) I want to get: frozenset(['Today']) or at least: frozenset(['today']) The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant...
[ "Here's version that works for any pair of iterables:\ndef intersection(iterableA, iterableB, key=lambda x: x):\n \"\"\"Return the intersection of two iterables with respect to `key` function.\n\n \"\"\"\n def unify(iterable):\n d = {}\n for item in iterable:\n d.setdefault(key(ite...
[ 10, 8, 4, 2 ]
[]
[]
[ "compare", "django", "python" ]
stackoverflow_0001479979_compare_django_python.txt
Q: Time difference between system date and string, e.g. from directory name? I would like to write a small script that does the following (and that I can then run using my crontab): Look into a directory that contains directories whose names are in some date format, e.g. 30-10-09. Convert the directory name to the d...
Time difference between system date and string, e.g. from directory name?
I would like to write a small script that does the following (and that I can then run using my crontab): Look into a directory that contains directories whose names are in some date format, e.g. 30-10-09. Convert the directory name to the date it represents (of course, I could put this information as a string into a f...
[ "I would suggest using Python. You'll need the following functions:\n\nos.listdir gives you the directory contents, as a list of strings\ntime.strptime(name, \"%d-%m-%y\") will try to parse such a string, and return a time tuple. You get a ValueError exception if parsing fails.\ntime.mktime will convert a time tupl...
[ 1 ]
[]
[]
[ "date", "python", "scripting" ]
stackoverflow_0001487450_date_python_scripting.txt
Q: python multiprocessing proxy I have a 2 processes: the first process is manager.py starts in backgroung: from multiprocessing.managers import SyncManager, BaseProxy from CompositeDict import * class CompositeDictProxy(BaseProxy): _exposed_ = ('addChild', 'setName') def addChild(self, child): ret...
python multiprocessing proxy
I have a 2 processes: the first process is manager.py starts in backgroung: from multiprocessing.managers import SyncManager, BaseProxy from CompositeDict import * class CompositeDictProxy(BaseProxy): _exposed_ = ('addChild', 'setName') def addChild(self, child): return self._callmethod('addChild', [...
[ "Besides fixing many other bugs in the above which I assume are accidental (init must be __init__, you're missing several instances of self, misindentation, etc, etc), the key bit is to make the registration in manager.py into:\nManager.register('get_plant', CompositeDict, proxytype=CompositeDictProxy)\n\nno idea...
[ 1 ]
[]
[]
[ "composite", "multiprocessing", "proxy", "python" ]
stackoverflow_0001486835_composite_multiprocessing_proxy_python.txt
Q: Error in nested for loops (Python) I am getting an error in the following code. The Error message is "Error: Inconsistent indentation detected!" s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is t...
Error in nested for loops (Python)
I am getting an error in the following code. The Error message is "Error: Inconsistent indentation detected!" s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: ...
[ "Once you cleaned your tabs and spaces (you should have only tabs or only spaces), you'd need to fix your loops:\ns = [30,40,50]\na = [5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6]\np = [0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2]\n\nfor j in s: # within loop j is being 30 then 40 then 50, same true for...
[ 6, 5, 2, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001487561_python_syntax.txt
Q: Python: pass c++ object to a script, then invoke extending c++ function from script First of all, the problem is that program fails with double memory freeing ... The deal is: I have FooCPlusPlus *obj; and I pass it to my script. It works fine. Like this: PyObject *pArgs, *pValue; pArgs = Py_BuildValue("((O))", ...
Python: pass c++ object to a script, then invoke extending c++ function from script
First of all, the problem is that program fails with double memory freeing ... The deal is: I have FooCPlusPlus *obj; and I pass it to my script. It works fine. Like this: PyObject *pArgs, *pValue; pArgs = Py_BuildValue("((O))", obj); pValue = PyObject_CallObject(pFunc, pArgs); where pFunc is a python function... So...
[ "Well, finally I know where the problem was:\nwe should return from \"bar\" function input args:\nreturn args;\n\ninstead of\nreturn PyCObject_FromVoidPtr((void *) ruleHandler, NULL);\n\n" ]
[ 0 ]
[]
[]
[ "python", "reference_counting" ]
stackoverflow_0001487001_python_reference_counting.txt
Q: Server side clusters of coordinates based on zoom level Thanks to this answer I managed to come up with a temporary solution to my problem. However, with a list of 6000 points that grows everyday it's becoming slower and slower. I can't use a third party service* therefore I need to come up with my own solution. ...
Server side clusters of coordinates based on zoom level
Thanks to this answer I managed to come up with a temporary solution to my problem. However, with a list of 6000 points that grows everyday it's becoming slower and slower. I can't use a third party service* therefore I need to come up with my own solution. Here are my requirements: Clustering of the coordinates nee...
[ "I don't see why you have to \"cluster\" on the fly. Summarize at each zoom level at a resolution you're happy with.\nSimply have a structure of X, Y, # of links. When someone adds a link, you insert the real locations (Zoom level max, or whatever), then start bubbling up from there.\nEventually you'll have 10 sets...
[ 2, 2 ]
[]
[]
[ "cluster_analysis", "google_maps", "google_maps_markers", "postgresql", "python" ]
stackoverflow_0001487704_cluster_analysis_google_maps_google_maps_markers_postgresql_python.txt
Q: Return a list of dictionaries that match the corresponding list of values in python For example, this is my list of dictionaries: [{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] Based on the list ['blue', 'red', 'green'] I want to return the followi...
Return a list of dictionaries that match the corresponding list of values in python
For example, this is my list of dictionaries: [{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] Based on the list ['blue', 'red', 'green'] I want to return the following: [{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': '...
[ "This might be a little naieve, but it works:\ndata = [\n {'name':'John', 'color':'red'},\n {'name':'Bob', 'color':'green'},\n {'name':'Tom', 'color':'blue'}\n]\ncolors = ['blue', 'red', 'green']\nresult = []\n\nfor c in colors:\n result.extend([d for d in data if d['color'] == c])\n\nprint result\n\n",...
[ 4, 2, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001485660_dictionary_python.txt
Q: What are good python libraries for the following needs? What are good python libraries for the following needs: MVC Domain Abstraction Database Abstraction Video library (just to create thumbnails) I already know that SQLAlchemy is really good for Database Abstraction so don't bother with it unless you want to...
What are good python libraries for the following needs?
What are good python libraries for the following needs: MVC Domain Abstraction Database Abstraction Video library (just to create thumbnails) I already know that SQLAlchemy is really good for Database Abstraction so don't bother with it unless you want to suggest a better one. Edit: This might seem stupid to ment...
[ "Have you tried wxWidgets (well, wxPython in fact)? \nIt has nice documentation (which is always a good thing), and allows creating code in MVC manner. It's just the GUI library, but allows some simple image manipulation (if it's not good enough for you try using Python version of ImageMagick). It uses native contr...
[ 4, 1, 1 ]
[]
[]
[ "database_abstraction", "domain_model", "libraries", "model_view_controller", "python" ]
stackoverflow_0001488691_database_abstraction_domain_model_libraries_model_view_controller_python.txt
Q: scipy 'Minimize the sum of squares of a set of equations' I face a problem in scipy 'leastsq' optimisation routine, if i execute the following program it says raise errors[info][1], errors[info][0] TypeError: Improper input parameters. and sometimes index out of range for an array... from scipy import * impor...
scipy 'Minimize the sum of squares of a set of equations'
I face a problem in scipy 'leastsq' optimisation routine, if i execute the following program it says raise errors[info][1], errors[info][0] TypeError: Improper input parameters. and sometimes index out of range for an array... from scipy import * import numpy from scipy import optimize from numpy import asarray fr...
[ "leastsq works with vectors so the residual function, func, needs to return a vector of length at least two. So if you replace return eqn with return [eqn, 0.], your example will work. Running it gives:\noptimized parameters: (array([10., 10.]), 2)\n\nwhich is one of the many correct answers for the minimum of t...
[ 2, 1, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0001488227_python_scipy.txt
Q: Mimic Python's strip() function in C I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that i...
Mimic Python's strip() function in C
I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered. fgets doesn't help either a...
[ "Python strings' strip method removes both trailing and leading whitespace. The two halves of the problem are very different when working on a C \"string\" (array of char, \\0 terminated).\nFor trailing whitespace: set a pointer (or equivalently index) to the existing trailing \\0. Keep decrementing the pointer unt...
[ 14, 12, 1, 0 ]
[]
[]
[ "c", "fgets", "python", "string" ]
stackoverflow_0001488372_c_fgets_python_string.txt
Q: Python matplotlib 3d bar function How to add strings to the axes in Axes3D instead of numbers? I just started using the matplotlib. I have used Axes3dD to plot similar to the example given on their website (http://matplotlib.sourceforge.net/examples/mplot3d/bars3d_demo.html). Note that one must use the last verson...
Python matplotlib 3d bar function
How to add strings to the axes in Axes3D instead of numbers? I just started using the matplotlib. I have used Axes3dD to plot similar to the example given on their website (http://matplotlib.sourceforge.net/examples/mplot3d/bars3d_demo.html). Note that one must use the last verson (matplotlib 0.99.1), otherwise the axi...
[ "Your actually on the right path there. but instead of a string you will want to pass a list or tuple to set_xticklabels(). You may also wish to adjust the center location for the label with set_xticks().\nYou may also find this function of use get_xmajorticklabels(). It will return the rendered tick labels. So you...
[ 2, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001487463_matplotlib_python.txt
Q: How to draw a class's metaclass in UML? If class A is created by its __metaclass M, how does the arrow look in UML? The stereotype syntax seems to be related. I didn't look in Python UML tools yet. A: A metaclass is drawn using the class notation plus the <<metaclass>> stereotype. The relationship between a clas...
How to draw a class's metaclass in UML?
If class A is created by its __metaclass M, how does the arrow look in UML? The stereotype syntax seems to be related. I didn't look in Python UML tools yet.
[ "A metaclass is drawn using the class notation plus the <<metaclass>> stereotype. The relationship between a class and its metaclass can be defined using a dependency relationship between the two (dashed line with the arrow pointing to the metaclass) annotated with the stereotype <<instantiate>>.\n", "This answer...
[ 4, 1, 0 ]
[]
[]
[ "metadata", "python", "uml" ]
stackoverflow_0001483273_metadata_python_uml.txt
Q: Evaluating into two or more lists Howdy, codeboys and codegirls! I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere. Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in ...
Evaluating into two or more lists
Howdy, codeboys and codegirls! I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere. Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady ...
[ "Try\nfor arg in arguments:\n lst = equal if '=' in arg else plain\n lst.append(arg)\n\nor (holy ugly)\nfor arg in arguments:\n (equal if '=' in arg else plain).append(arg)\n\nA third option: Create a class which offers append() and which sorts into several lists.\n", "You can use itertools.groupby() for...
[ 4, 4, 3, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001486558_list_python.txt
Q: When is it advisable to use a ret_val variable? I have seen conflicting advice on whether the following code is better def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val or whether this is better: def function(): if some_condition(): ...
When is it advisable to use a ret_val variable?
I have seen conflicting advice on whether the following code is better def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val or whether this is better: def function(): if some_condition(): return 2 else: return 3 This is a...
[ "Did we forget why \"multiple exit points\" was considered harmful in the first place? Back in the day (before widespread access to good exception handling and finally constructs, or managing objects like auto_ptr that do cleanup when they leave scope), this was the problem that haunted many multi-exit functions:\...
[ 8, 5, 5, 2, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "coding_style", "python", "return_value" ]
stackoverflow_0001489372_coding_style_python_return_value.txt
Q: Python Modules most worthwhile reading I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular? Related Threa...
Python Modules most worthwhile reading
I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular? Related Threads: Beginner looking for beautiful and inst...
[ "Queue.py shows you how to make a class thread-safe, and the proper use of the Template Method design pattern.\nsched.py is a great example of the Dependency Injection pattern.\nheapq.py is a really well-crafted implementation of the Heap data structure.\nIf I had to pick my three favorite modules in the Python sta...
[ 18, 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001490190_python.txt
Q: Python object inspector? besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this: when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector...
Python object inspector?
besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this: when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) after closing ...
[ "Winpdb is a platform independent graphical GPL Python debugger with an object inspector.\nIt supports remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.\nSome other features:\n\nGPL license. Winpdb is Free So...
[ 5, 2, 1, 1 ]
[ "You can use ipython, with the %debug statement. Once your code crashes, you can add breakpoints, see objects etc. A very crude way to kickoff the debugger is to raise Exception at some line of your code, run it in ipython, the type %debug when it crashes.\n" ]
[ -1 ]
[ "debugging", "introspection", "python" ]
stackoverflow_0001487952_debugging_introspection_python.txt
Q: save method in a view I have a very simple model: class Artist(models.Model): name = models.CharField(max_length=64, unique=False) band = models.CharField(max_length=64, unique=False) instrument = models.CharField(max_length=64, unique=False) def __unicode__ (self): return self.name that I'm using as a mod...
save method in a view
I have a very simple model: class Artist(models.Model): name = models.CharField(max_length=64, unique=False) band = models.CharField(max_length=64, unique=False) instrument = models.CharField(max_length=64, unique=False) def __unicode__ (self): return self.name that I'm using as a model form: from django.forms ...
[ "Apparently the problem resided in my template. I was using \n <form action=\"display/\" method=\"POST\">\n\nas opposed to\n <form action=\".\" method=\"POST\">\n\nalso changed my HttpRequest object from render_to_response to HttpResponseRedirect\ntrue newbie errors but at least it works now\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001489041_django_django_forms_python.txt
Q: In python, how do you launch an Amazon EC2 instance from within a Google App Engine app? In python, what is the best way to launch an Amazon EC2 instance from within a Google App Engine app? I would like to keep my AWS keys as secure as possible and be able to retrieve the public DNS for the newly launched EC2 ins...
In python, how do you launch an Amazon EC2 instance from within a Google App Engine app?
In python, what is the best way to launch an Amazon EC2 instance from within a Google App Engine app? I would like to keep my AWS keys as secure as possible and be able to retrieve the public DNS for the newly launched EC2 instance.
[ "I believe you can use boto with the current App Engine release (and maybe AEP to help, though maybe that's not needed for your specific task of starting an instance and retrieving its public domain name). This post has a good overview of \"lessons learned\" while getting all this to work. (Sorry, no personal expe...
[ 5 ]
[]
[]
[ "amazon_ec2", "google_app_engine", "python" ]
stackoverflow_0001490429_amazon_ec2_google_app_engine_python.txt
Q: calling Objective C functions from Python? Is there a way to dynamically call an Objective C function from Python? For example, On the mac I would like to call this Objective C function [NSSpeechSynthesizer availableVoices] without having to precompile any special Python wrapper module. A: As others have mentio...
calling Objective C functions from Python?
Is there a way to dynamically call an Objective C function from Python? For example, On the mac I would like to call this Objective C function [NSSpeechSynthesizer availableVoices] without having to precompile any special Python wrapper module.
[ "As others have mentioned, PyObjC is the way to go. But, for completeness' sake, here's how you can do it with ctypes, in case you need it to work on versions of OS X prior to 10.5 that do not have PyObjC installed:\nimport ctypes\nimport ctypes.util\n\n# Need to do this to load the NSSpeechSynthesizer class, whic...
[ 23, 10, 4, 3 ]
[]
[]
[ "macos", "objective_c", "python" ]
stackoverflow_0001490039_macos_objective_c_python.txt
Q: Difference between attributes and style tags in lxml I am trying to learn lxml after having used BeautifulSoup. However, I am not a strong programmer in general. I have the following code in some source html: <p style="font-family:times;text-align:justify"><font size="2"><b><i> The reasons to eat pickles include:...
Difference between attributes and style tags in lxml
I am trying to learn lxml after having used BeautifulSoup. However, I am not a strong programmer in general. I have the following code in some source html: <p style="font-family:times;text-align:justify"><font size="2"><b><i> The reasons to eat pickles include: </i></b></font></p> Because the text is bolded, I want ...
[ "Using the CSS API really isn't the right approach. If you want to find all b elements, do\nstrHTM=open(r'c:\\myfile.htm','r').read() # no need to split it into lines first\nnewHTM=html.fromString(strHTM)\nbELements = newHTM.findall('b')\nfor b in bElements:\n print b.text_content()\n\n" ]
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0001490474_lxml_python.txt
Q: Managing Perl habits in a Python environment Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. Subtle variable misspelling can ...
Managing Perl habits in a Python environment
Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. Subtle variable misspelling can waste an extraordinary amount of time. I understan...
[ "Splitting Python classes into separate files (like in Java, one class per file) helps find scoping problems, although this is not idiomatic python (that is, not pythonic).\nI have been writing python after much perl and found this from tchrist to be useful, even though it is old:\nhttp://linuxmafia.com/faq/Devtool...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "perl", "python", "transitions" ]
stackoverflow_0001489355_perl_python_transitions.txt
Q: get the exit code for python program I'm running a python program on WindowsXP. How can I obtain the exit code after my program ends? A: From a Windows command line you can use: echo %ERRORLEVEL% For example: C:\work>python helloworld.py Hello World! C:\work>echo %ERRORLEVEL% 0 A: How do you run the program...
get the exit code for python program
I'm running a python program on WindowsXP. How can I obtain the exit code after my program ends?
[ "From a Windows command line you can use:\necho %ERRORLEVEL%\n\nFor example:\nC:\\work>python helloworld.py\nHello World!\n\nC:\\work>echo %ERRORLEVEL%\n0\n\n", "How do you run the program?\nExit in python with sys.exit(1)\nIf you're in CMD or a BAT file you can access the variable %ERRORLEVEL% to obtain the exit...
[ 8, 5, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001491796_python.txt
Q: Precise response to tablet/mouse events in Windows How can I tell Windows not to do unhelpful pre-processing on tablet pen events? I am programming in Python 2.6, targetting tablet PCs running Windows 7 (though I would like my program to work with little modification on XP with a SMART interactive whiteboard, and ...
Precise response to tablet/mouse events in Windows
How can I tell Windows not to do unhelpful pre-processing on tablet pen events? I am programming in Python 2.6, targetting tablet PCs running Windows 7 (though I would like my program to work with little modification on XP with a SMART interactive whiteboard, and for mouse users on Linux/Mac). I've written a program wh...
[ "For raw mouse messages, you can use WM_INPUT on XP and later. Seven added some touch specific stuff: WM_GESTURE and WM_TOUCH\n" ]
[ 1 ]
[]
[]
[ "python", "tablet_pc", "winapi" ]
stackoverflow_0001490011_python_tablet_pc_winapi.txt
Q: Testing for an empty iterator in a Python for... loop The code below is based on this recipe. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways: If get_ye...
Testing for an empty iterator in a Python for... loop
The code below is based on this recipe. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways: If get_yes_no_answer() == False and there are two or more items left...
[ "why are you doing it this way at all? why not just:\ndef get_choice(pattern, inpt):\n choices = pattern.finditer(inpt, re.M)\n if not choices:\n sys.exit('No choices')\n for choice in choices:\n print(choice.group(0))\n if get_yes_no_answer():\n return choice\n sys.exit(...
[ 4, 2, 0, 0 ]
[]
[]
[ "conditional", "exception", "iterator", "python" ]
stackoverflow_0001491957_conditional_exception_iterator_python.txt
Q: How do I disable psycopg2 connection pooling? I have configured pgpool-II for postgres connection pooling and I want to disable psycopg2 connection pooling. How do I do this? Thanks! A: psycopg2 doesn't pool connections unless you explicitely use the psycopg.pool module.
How do I disable psycopg2 connection pooling?
I have configured pgpool-II for postgres connection pooling and I want to disable psycopg2 connection pooling. How do I do this? Thanks!
[ "psycopg2 doesn't pool connections unless you explicitely use the psycopg.pool module.\n" ]
[ 6 ]
[ "I don't think you can. Dan McKinley bemoaned this fact (among some other interesting issues) in his blog post Python PostgreSQL Driver Authors Hate You.\n" ]
[ -1 ]
[ "psycopg2", "python" ]
stackoverflow_0001440245_psycopg2_python.txt
Q: How to obtain the name of the calling shell in Python? I have a Python script that is always called from a shell, which can be either zsh or bash. How can I tell which one called the script? A: In Linux you can use procfs: >>> os.readlink('/proc/%d/exe' % os.getppid()) '/bin/bash' os.getppid() returns the PID ...
How to obtain the name of the calling shell in Python?
I have a Python script that is always called from a shell, which can be either zsh or bash. How can I tell which one called the script?
[ "In Linux you can use procfs:\n>>> os.readlink('/proc/%d/exe' % os.getppid())\n'/bin/bash'\n\nos.getppid() returns the PID of parent process. This is portable. But obtaining process name can't be done in portable way. You can parse ps output which is available on all unices, e.g. with psutil. \n", "You can't do t...
[ 10, 0 ]
[ "os.system(\"echo $0\")\nThis works flawlessly on my system:\ncat shell.py: \n\n #!/ms/dist/python/PROJ/core/2.5/bin/python\n\n import os\n print os.system(\"echo $0\")\n\n\nbash-2.05b$ uname -a\nLinux pi929c1n10 2.4.21-32.0.1.EL.msdwhugemem #1 SMP Mon Dec 5 21:32:44 EST 2005 i686 athlon i386 GNU/Linux\n\n...
[ -3 ]
[ "python", "shell" ]
stackoverflow_0001492508_python_shell.txt
Q: How to shutdown cherrypy from within? I am developing on cherrypy, I start it from a python script. For better development I wonder what is the correct way to stop cherrypy from within the main process (and not from the outside with ctrl-c or SIGTERM). I assume I have to register a callback function from the main ...
How to shutdown cherrypy from within?
I am developing on cherrypy, I start it from a python script. For better development I wonder what is the correct way to stop cherrypy from within the main process (and not from the outside with ctrl-c or SIGTERM). I assume I have to register a callback function from the main application to be able to stop the cherrypy...
[ "import sys\nclass MyCherryPyApplication(object):\n\n def default(self):\n sys.exit()\n default.exposed = True\n\ncherrypy.quickstart(MyCherryPyApplication())\n\nPutting a sys.exit() in any request handler exits the whole server\nI would have expected this only terminates the current thread, but it terminates ...
[ 5 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001492699_cherrypy_python.txt
Q: Download multiple pages concurrently? I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other. According to this thread, Python doesn't allow this because of something called Globa...
Download multiple pages concurrently?
I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other. According to this thread, Python doesn't allow this because of something called Global Interpreter Lock that prevents lauching t...
[ "Don't worry about GIL. In your case it doesn't matter.\nEasiest way to do what you want is to create thread pool, using threading module and one of thread pool implementations from ASPN. Each thread from that pool can use httplib to download your web pages.\nAnother option is to use PyCURL module -- it supports pa...
[ 9, 7, 2, 2, 0 ]
[]
[]
[ "concurrent_processing", "python" ]
stackoverflow_0001491993_concurrent_processing_python.txt
Q: Identical string return FALSE with '==' in Python, why? The data string is receive through a socket connexion. When receiving the first example where action variable would = 'IDENTIFY', it works. But when receiving the second example where action variable would = 'MSG' it does not compare. And the most bizarre th...
Identical string return FALSE with '==' in Python, why?
The data string is receive through a socket connexion. When receiving the first example where action variable would = 'IDENTIFY', it works. But when receiving the second example where action variable would = 'MSG' it does not compare. And the most bizarre thing, when I use Telnet instead of my socket client both are b...
[ "Can't reproduce your problem. To debug it, print or log the repr() of data and action: this will likely show you the cause (probably some non-visible binary byte has snuck into data, based on how you obtained it [[which you don't show us]] and hence into action).\n" ]
[ 5 ]
[]
[]
[ "python", "string_comparison" ]
stackoverflow_0001493007_python_string_comparison.txt
Q: Python WebkitGtk: How to respond to the default context menu items? The default context menu contains items like "Open link in new window" and "Download linked file", which don't seem to do anything. I obviously like to react on these items, but can't figure out how, since the port's documentation is a bit sparse....
Python WebkitGtk: How to respond to the default context menu items?
The default context menu contains items like "Open link in new window" and "Download linked file", which don't seem to do anything. I obviously like to react on these items, but can't figure out how, since the port's documentation is a bit sparse. Does anybody know?
[ "In the C port, you have to connect to the 'create-web-view', 'new-window-policy-decision-requested', and 'download-requested' signals. I think the Python port works the same way. See this page for the documentation on the C versions of those signals:\nhttp://webkitgtk.org/reference/webkitgtk-WebKitWebView.html\n" ...
[ 2 ]
[]
[]
[ "gtk", "python", "webkit" ]
stackoverflow_0001491179_gtk_python_webkit.txt
Q: Program new functionality for zoom button on Microsoft Natural Ergonomic Desktop 7000 I just bought a new keyboard and mouse (Microsoft Natural Ergonomic Desktop 7000) and it has a neat little zoom lever in the middle of the keyboard. What I'd like to do is write a little program (in C# or Python, for use on Windo...
Program new functionality for zoom button on Microsoft Natural Ergonomic Desktop 7000
I just bought a new keyboard and mouse (Microsoft Natural Ergonomic Desktop 7000) and it has a neat little zoom lever in the middle of the keyboard. What I'd like to do is write a little program (in C# or Python, for use on Windows Vista) which makes the zoom button act like a scroll button instead. I have no idea wher...
[ "This web page en comments should help you out a bit: Icool blog\n" ]
[ 1 ]
[]
[]
[ "c#", "driver", "keyboard", "python" ]
stackoverflow_0001493202_c#_driver_keyboard_python.txt
Q: Rhythmbox: how do I access the 'rating' field of a track through Python script? I would like the capability to get/set the rating associated with a specific track through a Python. How do I achieve this? A: You can use Rhythmbox' D-Bus interface. I have written a small script that can get/set the rating and disp...
Rhythmbox: how do I access the 'rating' field of a track through Python script?
I would like the capability to get/set the rating associated with a specific track through a Python. How do I achieve this?
[ "You can use Rhythmbox' D-Bus interface. I have written a small script that can get/set the rating and displays a notification, all acting on the currently playing song.\nThe script is here: http://kaizer.se/wiki/code/rhrating.py\nAddendum one: I promise I write more beautiful Python when it's not a throwaway scrip...
[ 3 ]
[]
[]
[ "linux", "python", "rhythmbox" ]
stackoverflow_0001492849_linux_python_rhythmbox.txt
Q: Cannot access django app through ip address while accessing it through localhost I have a django app on my local computer. I can access the application from a browser by using the url: http://localhost:8000/myapp/ But I cannot access the application by using the ip of the host computer: http://193.140.209.49:8000/...
Cannot access django app through ip address while accessing it through localhost
I have a django app on my local computer. I can access the application from a browser by using the url: http://localhost:8000/myapp/ But I cannot access the application by using the ip of the host computer: http://193.140.209.49:8000/myapp/ I get a 404 error. What should I do? Any suggestions?
[ "I assume you're using the development server. If so, then you need to specifically bind to your external IP for the server to be available there. Try this command:\n./manage.py runserver 193.140.209.49:8000\n\n" ]
[ 70 ]
[]
[]
[ "django", "networking", "python" ]
stackoverflow_0001493479_django_networking_python.txt
Q: Subclass of webapp.RequestHandler doesn't have a response attribute Using the below code, my template loads fine until I submit the from, then I get the following error: e = AttributeError("'ToDo' object has no attribute 'response'",) Why doesn't my ToDo object not have a response attribute? It works the first ti...
Subclass of webapp.RequestHandler doesn't have a response attribute
Using the below code, my template loads fine until I submit the from, then I get the following error: e = AttributeError("'ToDo' object has no attribute 'response'",) Why doesn't my ToDo object not have a response attribute? It works the first time it's called. import cgi import os from google.appengine.api import u...
[ "why do you do what you do in post? it should be:\ndef post(self):\n task = Task() # not ToDo()\n task.description = self.request.get('description')\n task.put()\n self.redirect('/')\n\nput called on a subclass of webapp.RequestHandler will try to handle PUT request, according to docs.\n"...
[ 3 ]
[]
[]
[ "google_app_engine", "post_redirect_get", "python" ]
stackoverflow_0001493467_google_app_engine_post_redirect_get_python.txt
Q: Creating a news archive in Django I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g. Sept 09 Oct 09 I then need in the view to some every time a ...
Creating a news archive in Django
I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g. Sept 09 Oct 09 I then need in the view to some every time a new news article is created for a new m...
[ "An excellent place to start is the book Practical Django Projects by James Bennett. Among other things, it guides you through the development of a web blog with multiple time-based views (by month, etc) that should serve you well as the basis for your application.\n", "One option you can try is to create a cust...
[ 3, 3, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "mysql", "python" ]
stackoverflow_0001492866_django_django_models_django_templates_mysql_python.txt
Q: Regex find non digit and/or end of string How do I include an end-of-string and one non-digit characters in a python 2.6 regular expression set for searching? I want to find 10-digit numbers with a non-digit at the beginning and a non-digit or end-of-string at the end. It is a 10-digit ISBN number and 'X' is valid...
Regex find non digit and/or end of string
How do I include an end-of-string and one non-digit characters in a python 2.6 regular expression set for searching? I want to find 10-digit numbers with a non-digit at the beginning and a non-digit or end-of-string at the end. It is a 10-digit ISBN number and 'X' is valid for the final digit. The following do not work...
[ "You have to group the alternatives with parenthesis, not brackets:\nr'\\D(\\d{9}[\\dXx])($|\\D)'\n\n| is a different construct than []. It marks an alternative between two patterns, while [] matches one of the contained characters. So | should only be used inside of [] if you want to match the actual character |. ...
[ 7, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001493871_python_regex.txt
Q: POSTing a complex JSON object using Prototype I'm using Prototype 1.6.1 to create an application under IIS, using ASP and Python. The python is generating a complex JSON object. I want to pass this object to another page via an AJAX request, but the Prototype documentation is a little too cunning for me. Can some...
POSTing a complex JSON object using Prototype
I'm using Prototype 1.6.1 to create an application under IIS, using ASP and Python. The python is generating a complex JSON object. I want to pass this object to another page via an AJAX request, but the Prototype documentation is a little too cunning for me. Can someone show me an example of how to create an Prototyp...
[ "new Ajax.Request('/some_url',\n{\n method:\"post\",\n postBody:\"{'some':'json'}\",\n onSuccess: function(transport){\n var response = transport.responseText || \"no response text\";\n alert(\"Success! \\n\\n\" + response);\n },\n onFailure: function(){ alert('Something went wrong...') }\n});\n\n" ]
[ 7 ]
[]
[]
[ "iis", "javascript", "prototypejs", "python" ]
stackoverflow_0001494039_iis_javascript_prototypejs_python.txt
Q: How to define [] for class in Python? I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to def []=() construct in ruby, so that calling Python obj['foo'] would ...
How to define [] for class in Python?
I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to def []=() construct in ruby, so that calling Python obj['foo'] would actually call some [](self, what) method. H...
[ "It's all in the docs: __getitem__.\n", "This is done with __getitem___ in Python.\nHere is a list of all the operators:\nhttp://docs.python.org/library/operator.html\n", "define a method in your class with __getitem__(key) and __setitem__(key, value)\n", "http://docs.python.org/reference/datamodel.html\nSect...
[ 11, 7, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0001494146_python.txt
Q: General Command pattern and Command Dispatch pattern in Python I was looking for a Command pattern implementation in Python... (According to Wikipedia, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later ti...
General Command pattern and Command Dispatch pattern in Python
I was looking for a Command pattern implementation in Python... (According to Wikipedia, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. ) The only thing I found was Command Dispatch pattern: class Di...
[ "The simplest command pattern is already built into Python, simply use a callable:\ndef greet(who):\n print \"Hello %s\" % who\n\ngreet_command = lambda: greet(\"World\")\n# pass the callable around, and invoke it later\ngreet_command()\n\nThe command pattern as an object oriented design pattern makes more sense...
[ 63, 5, 4, 4 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0001494442_design_patterns_oop_python.txt
Q: Python Auto Importing Possible Duplicate: Perl's AUTOLOAD in Python (getattr on a module) I'm coming from a PHP background and attempting to learn Python, and I want to be sure to do things the "Python way" instead of how i've developed before. My question comes from the fact in PHP5 you can set up your code so ...
Python Auto Importing
Possible Duplicate: Perl's AUTOLOAD in Python (getattr on a module) I'm coming from a PHP background and attempting to learn Python, and I want to be sure to do things the "Python way" instead of how i've developed before. My question comes from the fact in PHP5 you can set up your code so if you attempt to call a c...
[ "Imports serve at least two other important purposes besides making the modules or contents of the modules available:\n\nThey serve as a sort of declaration of intent -- \"this module uses services from this other module\" or \"this module uses services belonging to a certain class\" -- e.g. if you are doing a secu...
[ 15, 11, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001493888_python.txt
Q: Separate Admin/User authentication system in Django I've recently started learning/using django; I'm trying to figure out a way to have two separate authentications systems for administrators and users. Rather than create a whole new auth system, I'd like to leverage django's built-in functionality (i.e. session m...
Separate Admin/User authentication system in Django
I've recently started learning/using django; I'm trying to figure out a way to have two separate authentications systems for administrators and users. Rather than create a whole new auth system, I'd like to leverage django's built-in functionality (i.e. session management, @login_required decorator, etc.). Specificall...
[ "You could potentially write one or more custom authentication backends. This is documented here. I have written a custom backend to authenticate against an LDAP server, for example.\n", "If I understand your question correctly (and perhaps I don't), I think you're asking how to create a separate login form for...
[ 1, 1, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0001494524_authentication_django_python.txt
Q: Percentage with variable precision I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters. How can I write this in Python? The "%.8f" string formatting works decently, but I need to ke...
Percentage with variable precision
I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters. How can I write this in Python? The "%.8f" string formatting works decently, but I need to keep the last three characters after the l...
[ "Try this:\nimport math\ndef format_percentage(x, precision=3):\n return (\"%%.%df%%%%\" % (precision - min(0,math.log10(100-x)))) % x\n\n", "Mark Ransom's answer is a beautiful thing. With a little bit of work, it can solve the problem for any inputs. I went ahead and did the little bit of work.\nYou just n...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "precision", "python" ]
stackoverflow_0001494708_algorithm_precision_python.txt