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: String manipulation in Python I have a randomly generated string from 6 letters in this form, example: A' B F2 E' B2 A2 C' D2 C D' E2 F Some letters have " ' " added to them some have number "2". What i want is to add letter "x" to every letter that is on its own. So it would look like this: A' Bx F2 E' B2 A2 C'...
String manipulation in Python
I have a randomly generated string from 6 letters in this form, example: A' B F2 E' B2 A2 C' D2 C D' E2 F Some letters have " ' " added to them some have number "2". What i want is to add letter "x" to every letter that is on its own. So it would look like this: A' Bx F2 E' B2 A2 C' D2 Cx D' E2 Fx The trick is that ...
[ "Transform your string into list with split()\ns = \"\"\"A' B F2 E' B2 A2 C' D2 C D' E2 F\"\"\"\n\nL = s.split(' ')\n\nfor i in xrange(len(L)):\n if len(L[i]) == 1:\n L[i] += 'x'\n\nstr_out = ' '.join(L)\n\n", "The split-comprehend-join version:\n' '.join(n+'x' if len(n)==1 else n for n in inputstr.split(' ')...
[ 5, 4, 3, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002264202_python.txt
Q: Python: How to access parent class object through derived class instance? I'm sorry for my silly question, but... let's suppose I have these classes: class A(): msg = 'hehehe' class B(A): msg = 'hohoho' class C(B): pass and an instance of B or C. How do I get the variable 'msg' from the parent's cla...
Python: How to access parent class object through derived class instance?
I'm sorry for my silly question, but... let's suppose I have these classes: class A(): msg = 'hehehe' class B(A): msg = 'hohoho' class C(B): pass and an instance of B or C. How do I get the variable 'msg' from the parent's class object through this instance? I've tried this: foo = B() print super(foo.__c...
[ "You actually want to use\nclass A(object):\n ...\n...\nb = B()\nbar = super(b.__class__, b)\nprint bar.msg\n\nBase classes must be new-style classes (inherit from object)\n", "If the class is single-inherited:\nfoo = B()\nprint foo.__class__.__bases__[0].msg\n# 'hehehe'\n\nIf the class is multiple-inherited, ...
[ 15, 11, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002265060_python.txt
Q: Indicating that GET response is complete w/ Python AppEngine When I get a GET request from a user, I send them the response and then spend maybe a second logging stuff about that request. Is there a way to close the connection when I have the response ready, but continue doing that logging part, so that the user w...
Indicating that GET response is complete w/ Python AppEngine
When I get a GET request from a user, I send them the response and then spend maybe a second logging stuff about that request. Is there a way to close the connection when I have the response ready, but continue doing that logging part, so that the user wouldn't have to wait for it to complete?
[ "From the Google App Engine docs for the Response object:\n\nApp Engine does not support sending\n data to the user's browser before\n exiting the handler. Some web servers\n use this technique to \"stream\" data to\n the user's browser over a period of\n time in response to a single request.\n App Engine doe...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002261479_google_app_engine_python.txt
Q: why i can't alert this string which is return from django render_to_response django code: return render_to_response(template_name, { "form": form, }, context_instance=RequestContext(request)) and html: <script type="text/javascript"> var a='{{form}}' alert(a) </script> it's error i...
why i can't alert this string which is return from django render_to_response
django code: return render_to_response(template_name, { "form": form, }, context_instance=RequestContext(request)) and html: <script type="text/javascript"> var a='{{form}}' alert(a) </script> it's error is 'unterminated string literal', and i see this in firebug : <script type="text/ja...
[ "Maybe try putting in semi-colons at the ends of the lines in your Django template file?\n<script type=\"text/javascript\">\n var a='{{form}}';\n\n alert(a);\n</script>\n\nOdd though, I’m pretty sure semi-colons are optional there. Could you do a View Source in Firefox (instead of looking via Firebug), and se...
[ 1, 1, 0 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0002264503_django_javascript_python.txt
Q: How would you solve this GPS/location problem and scale it? Would you use a Database? R-tree? Suppose I have a people and their GPS coordinates: User1, 52.99, -41.0 User2, 91.44, -21.4 User3, 5.12, 24.5 ... My objective is: Given a set of coordinates, Out of all those users, find the ones within 20 meters. (how ...
How would you solve this GPS/location problem and scale it? Would you use a Database? R-tree?
Suppose I have a people and their GPS coordinates: User1, 52.99, -41.0 User2, 91.44, -21.4 User3, 5.12, 24.5 ... My objective is: Given a set of coordinates, Out of all those users, find the ones within 20 meters. (how to do a SELECT statement like this?) For each of those users, get the distance. As you probably gu...
[ "\nCreate a MyISAM table with a column of datatype Point\nCreate a SPATIAL index on this column\nConvert the GPS coords into UTM (grid) coords and store them in your table\nIssue this query:\nSELECT user_id, GLength(LineString(user_point, @mypoint))\nFROM users\nWHERE MBRWithin(user_point, LineString(Point(X(...
[ 3, 2, 0 ]
[]
[]
[ "computer_science", "database", "mysql", "python" ]
stackoverflow_0002265775_computer_science_database_mysql_python.txt
Q: How to notify user when django's custom action doesn't behave as expected? I am writing a custom action for django admin. This action should only work for records having particular state. For example "Approve Blog" custom action should approve user blog only when blog is not approved. And it must not appove rejec...
How to notify user when django's custom action doesn't behave as expected?
I am writing a custom action for django admin. This action should only work for records having particular state. For example "Approve Blog" custom action should approve user blog only when blog is not approved. And it must not appove rejected blogs. One option is to filter non approved blogs and then approve them. Bu...
[ "The documentation on admin actions is quite helpful, so go take a look!\nI think just writing an action that only updates non-rejected blogs ought to do.\nThe following code assumes you've got variables rejected and approved that map to the integral values representing Blogs that have been rejected, and blogs that...
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002265101_django_django_admin_python.txt
Q: Permission problem of .egg of easy_install under windows7/vista I use the easy_install to install python packages in a virtuaenv under windows7. Due to the UAV, I have to run the CMD as administrator for installing packages. Here comes the problem, I notice that I can't import the package from a normal user acc...
Permission problem of .egg of easy_install under windows7/vista
I use the easy_install to install python packages in a virtuaenv under windows7. Due to the UAV, I have to run the CMD as administrator for installing packages. Here comes the problem, I notice that I can't import the package from a normal user account. >>> import tempita Traceback (most recent call last): File "<...
[ "I've started using distribute in lieu of setuptools, because the distribute team has been much more proactive in tracking down problems. Curiously, it appears as if distribute no longer creates zip eggs on my Windows 7 system, perhaps for the permissions issues you've encountered. Switching to distribute might be ...
[ 0, 0 ]
[]
[]
[ "easy_install", "python", "virtualenv", "windows" ]
stackoverflow_0002264488_easy_install_python_virtualenv_windows.txt
Q: How do I prevent Qt buttons from appearing in a separate frame? I'm working on a PyQt application. Currently, there's a status panel (defined as a QWidget) which contains a QHBoxLayout. This layout is frequently updated with QPushButtons created by another portion of the application. Whenever the buttons which ...
How do I prevent Qt buttons from appearing in a separate frame?
I'm working on a PyQt application. Currently, there's a status panel (defined as a QWidget) which contains a QHBoxLayout. This layout is frequently updated with QPushButtons created by another portion of the application. Whenever the buttons which appear need to change (which is rather frequently) an update effect g...
[ "You should call the button's close() method. If you want it to be deleted when you close it, you can set the Qt.WA_DeleteOnClose attribute:\nbutton.setAttribute(Qt.WA_DeleteOnClose)\n\n", "Try calling QWidget::hide() on the button before removing from the layout if you don't want to delete your button.\n" ]
[ 2, 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002264482_pyqt_pyqt4_python_qt_qt4.txt
Q: Updating profile with python-twitter I am trying to update my Profile info via python-twitter module. >>> api = twitter.Api(username="username", password="password") >>> user = api.GetUser(user="username") >>> user.SetLocation('New Location') The problem is that it is not getting updated and the documentation is ...
Updating profile with python-twitter
I am trying to update my Profile info via python-twitter module. >>> api = twitter.Api(username="username", password="password") >>> user = api.GetUser(user="username") >>> user.SetLocation('New Location') The problem is that it is not getting updated and the documentation is unclear if there's another step I need to ...
[ "I don't believe that the python-twitter module currently supports updating a profile. SetLocation will only update your local user object that GetUser has returned.\nIt would be relatively trivial to add support for this to the module though. Have a look at this method:\naccount/update_profile \nand then add a new...
[ 1 ]
[ "This are the setprofile methods from User:\nSetProfileBackgroundColor(self, profile_background_color)\n\nSetProfileBackgroundImageUrl(self, profile_background_image_url)\n\nSetProfileBackgroundTile(self, profile_background_tile)\n Set the boolean flag for whether to tile the profile background image.\n\n Arg...
[ -1 ]
[ "api", "python", "twitter" ]
stackoverflow_0001278192_api_python_twitter.txt
Q: processing text from a non-flat file (to extract information as if it *were* a flat file) I have a longitudinal data set generated by a computer simulation that can be represented by the following tables ('var' are variables): time subject var1 var2 var3 t1 subjectA ... t2 subjectB ... and subject name su...
processing text from a non-flat file (to extract information as if it *were* a flat file)
I have a longitudinal data set generated by a computer simulation that can be represented by the following tables ('var' are variables): time subject var1 var2 var3 t1 subjectA ... t2 subjectB ... and subject name subjectA nameA subjectB nameB However, the file generated writes a data file in a format simil...
[ "This is what Python generators are all about.\ndef read_as_flat( someFile ):\n line_iter= iter(someFile)\n time_header= None\n for line in line_iter:\n words = line.split()\n if words[0] == 'time':\n time_header = [ words[1:] ] # the \"time\" line\n description= line_it...
[ 4, 2, 2, 1, 1 ]
[]
[]
[ "awk", "flat_file", "perl", "python", "text_processing" ]
stackoverflow_0002264504_awk_flat_file_perl_python_text_processing.txt
Q: Encountering a problem while moving to Django 1.1 I'm trying to move from django 1.0.2 to 1.1 and I am getting the following error in one of my templates: Request Method: GET Request URL: http://localhost:8000/conserv/media_assets/vod/ Exception Type: TemplateSyntaxError Exception Value: Caught an e...
Encountering a problem while moving to Django 1.1
I'm trying to move from django 1.0.2 to 1.1 and I am getting the following error in one of my templates: Request Method: GET Request URL: http://localhost:8000/conserv/media_assets/vod/ Exception Type: TemplateSyntaxError Exception Value: Caught an exception while rendering: 'NoneType' object has no a...
[ "there's an error in your form class. The fields should be an iterable, but a tuple with one element should be written ('thumb',) instead of ('thumb'). Change your form class to :\nclass UploadImageForm(ModelForm):\n class Meta: \n model = ImageUpload \n fields = ('thumb',)\n\nIt should do the trick.\n" ]
[ 0 ]
[]
[]
[ "django_templates", "python" ]
stackoverflow_0002265914_django_templates_python.txt
Q: showing list item in python I want to manipulate feed which contains frequently updated (with time) contents using feed parser. Goal is to show all the contents of the updated feed. import feedparser d = feedparser.parse("some URL") print "Information of user" i = range(10) for i in d: print d.entries[i].su...
showing list item in python
I want to manipulate feed which contains frequently updated (with time) contents using feed parser. Goal is to show all the contents of the updated feed. import feedparser d = feedparser.parse("some URL") print "Information of user" i = range(10) for i in d: print d.entries[i].summary print " " As parsing da...
[ "i is not an integer. I guess i is already an entry of the feed but better rename it:\nTry: \nfor entry in d.entries:\n print entry.summary\n\nIf you want the first 10 entries you have to do:\ntry:\n for i in range(10):\n print d.entries[i].summary\nexcept IndexError:\n pass\n\n", "for i in range(10):\n ...
[ 4, 4, 1, 1, 1, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0002265871_feedparser_python.txt
Q: Python, generating PDF using ReportLab.Platypus SimpleDocTemplate, date/time in header I'm working on a project in Python/Django which uses ReportLab's SimpleDocTemplate to generate PDF documents. All the documents generated have the current date/time printed in the top right corner. I can't see that it's being d...
Python, generating PDF using ReportLab.Platypus SimpleDocTemplate, date/time in header
I'm working on a project in Python/Django which uses ReportLab's SimpleDocTemplate to generate PDF documents. All the documents generated have the current date/time printed in the top right corner. I can't see that it's being done anywhere in my code, is this a default behaviour in the SimpleDocTemplate object? How do...
[ "I've just tried to reproduce the behavior you described, but unfortunately I cant. So I don't think it's a default behavior. Maybe it would be a good idea if you post a small example where the production date/time in the header is visible.\nBut if it's any help to you, here is what I've done: I used the following ...
[ 2 ]
[]
[]
[ "django", "pdf_generation", "platypus", "python", "reportlab" ]
stackoverflow_0002265976_django_pdf_generation_platypus_python_reportlab.txt
Q: How to break the following line of python I have come upon a couple of lines of code similar to this one, but I'm unsure how I should break it: blueprint = Blueprint(self.blueprint_map[str(self.ui.blueprint_combo.currentText())], runs=self.ui.runs_spin.text(), me=self.ui.me_spin.text(), pe=self.ui.pe_skill_combo.c...
How to break the following line of python
I have come upon a couple of lines of code similar to this one, but I'm unsure how I should break it: blueprint = Blueprint(self.blueprint_map[str(self.ui.blueprint_combo.currentText())], runs=self.ui.runs_spin.text(), me=self.ui.me_spin.text(), pe=self.ui.pe_skill_combo.currentIndex()) Thanks in advance
[ "blueprint = Blueprint(\n self.blueprint_map[str(self.ui.blueprint_combo.currentText())],\n runs=self.ui.runs_spin.text(), \n me=self.ui.me_spin.text(),\n pe=self.ui.pe_skill_combo.currentIndex(),\n)\n\n", "How about this\nblueprint_item = self.blueprint_map[str(self.ui.blueprint_combo.currentText())]...
[ 14, 5, 4, 0, 0 ]
[]
[]
[ "pep8", "python" ]
stackoverflow_0002266659_pep8_python.txt
Q: Python: strange numbers being pulled from binary file /confusion with hex and decimals This might be extremely trivial, and if so I apologise, but I'm getting really confused with the outputs I'm getting: hex? decimal? what? Here's an example, and what it returns: >>> print 'Rx State: ADC Clk=', ADC_Clock_MHz,'MHz...
Python: strange numbers being pulled from binary file /confusion with hex and decimals
This might be extremely trivial, and if so I apologise, but I'm getting really confused with the outputs I'm getting: hex? decimal? what? Here's an example, and what it returns: >>> print 'Rx State: ADC Clk=', ADC_Clock_MHz,'MHz DDC Clk=', DDC_Clock_kHz,'kHz Temperature=', Temperature,'C' Rx State: ADC Clk= [1079246848...
[ "The contents are in pairs because you assign a pair to the variables (e.g. ADC_Clock_MHz = v1 and v1 = [content[pos+1], content[pos]]).\nYou are basically assigning a list of two elements to v1 where the first element is the element in the index pos+1 in the array content and the second element is the element in t...
[ 0, 0, 0 ]
[]
[]
[ "binary", "hex", "numpy", "python" ]
stackoverflow_0002148538_binary_hex_numpy_python.txt
Q: pygst - glimagesink callback I'm trying to use 'glimagesink' element with python. The element (which is GObject inside) has client-draw-callback property which should (in C++ at least) contain a function (bool func(uint t, uint w, uint h)) pointer. I've tried element.set_property('client-draw-callback', myfunc), a...
pygst - glimagesink callback
I'm trying to use 'glimagesink' element with python. The element (which is GObject inside) has client-draw-callback property which should (in C++ at least) contain a function (bool func(uint t, uint w, uint h)) pointer. I've tried element.set_property('client-draw-callback', myfunc), and creating function pointer with ...
[ "This isn't the problem you're having (as far as I can tell) but it's important to note that\nthis API has changed recently, now it expects a void pointer of data which allows you to pass in a handle to user_data (or NULL) when you connect your callback.\ngboolean drawCallback (GLuint texture, GLuint width, GLuint ...
[ 0 ]
[]
[]
[ "ctypes", "gstreamer", "opengl", "python" ]
stackoverflow_0001834990_ctypes_gstreamer_opengl_python.txt
Q: How do I get the content-type from return of urlopen(url) in python2.x? Are theere any functions in 3.x using the http.client.HTTPMessage().get_content_type() ? A: urllib2.urlopen() returns an addinfourl with headers: >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> f.headers['content-typ...
How do I get the content-type from return of urlopen(url) in python2.x?
Are theere any functions in 3.x using the http.client.HTTPMessage().get_content_type() ?
[ "urllib2.urlopen() returns an addinfourl with headers:\n>>> import urllib2\n>>> f = urllib2.urlopen('http://www.python.org/')\n>>> f.headers['content-type']\n'text/html'\n>>> \n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002267568_python.txt
Q: overloading augmented arithmetic assignments in python I'm new to Python so apologies in advance if this is a stupid question. For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, **=, %=) for a class myInt. I checked the Python documentation and this is what I came up with: def __...
overloading augmented arithmetic assignments in python
I'm new to Python so apologies in advance if this is a stupid question. For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, **=, %=) for a class myInt. I checked the Python documentation and this is what I came up with: def __iadd__(self, other): if isinstance(other, myInt): ...
[ "You need to add return self to your method. Explanation:\nThe semantics of a += b, when type(a) has a special method __iadd__, are defined to be:\n a = a.__iadd__(b)\n\nso if __iadd__ returns something different than self, that's what will be bound to name a after the operation. By missing a return statement, t...
[ 14, 7, 1 ]
[]
[]
[ "operator_overloading", "operators", "python" ]
stackoverflow_0002267466_operator_overloading_operators_python.txt
Q: Reading a binary file in Python: takes a very long time to read certain bytes This is very odd I'm reading some (admittedly very large: ~2GB each) binary files using numpy libraries in Python. I'm using the: thingy = np.fromfile(fileObject, np.int16, 1) method. This is right in the middle of a nested loop - I'm...
Reading a binary file in Python: takes a very long time to read certain bytes
This is very odd I'm reading some (admittedly very large: ~2GB each) binary files using numpy libraries in Python. I'm using the: thingy = np.fromfile(fileObject, np.int16, 1) method. This is right in the middle of a nested loop - I'm doing this loop 4096 times per 'channel', and this 'channel' loop 9 times for ever...
[ "Although it's hard to say without some kind of reproducible sample, this sounds like a buffering problem. The First part is buffered and until you reach the end of the buffer, it is fast; then it slows down until the next buffer is filled, and so on.\n", "Where are you storing the results? When lists/dicts/whate...
[ 3, 2, 1 ]
[]
[]
[ "binary", "binaryfiles", "numpy", "python" ]
stackoverflow_0002265930_binary_binaryfiles_numpy_python.txt
Q: Django Loading Templates with Inheritance from Specific Directory In our project, we have a bunch of different templates that clients to choose from (for their webstore). The file layout is something like this: templates cart.html closed.html head.html standard bishop default ...
Django Loading Templates with Inheritance from Specific Directory
In our project, we have a bunch of different templates that clients to choose from (for their webstore). The file layout is something like this: templates cart.html closed.html head.html standard bishop default indiana marley mocca nihilists racont...
[ "In your templates/standard/bishop/browse.html template you're doing the following:\n{% extends \"base.html\" %}\n\nThis refers to templates/base.html and not templates/standard/bishop/base.html. By default Django will check your installed applications as well as the template directories that you specified under TE...
[ 5 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002266530_django_python_templates.txt
Q: Authenticated commenting in Django 1.1? (Now that Django 1.1 is in release candidate status, it could be a good time to ask this.) I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a ForeignKey...
Authenticated commenting in Django 1.1?
(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.) I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a ForeignKey to User already exists. From django.contrib....
[ "WordPress and other systems make this a no-brainer. If you're logged in, the comment form should just \"do the right thing\" and remove the name/email/url fields. Isn't this exactly the kind of heavy lifting a framework is supposed to do for you? \nRather than dancing around with subclassing models for something t...
[ 4, 3, 1, 1, 1, 0 ]
[]
[]
[ "comments", "django", "python" ]
stackoverflow_0001163113_comments_django_python.txt
Q: buildbot: run SVNPoller with --trust-server-cert I asked this similar question and got a satisfactory answer. However, doing the same with SVNPoller doesn't work. So how can I pass --trust-server-cert as an extra param to SVNPoller in buildbot A: class MyPoller(SVNPoller): def __init__(...): SVNPoll...
buildbot: run SVNPoller with --trust-server-cert
I asked this similar question and got a satisfactory answer. However, doing the same with SVNPoller doesn't work. So how can I pass --trust-server-cert as an extra param to SVNPoller in buildbot
[ "class MyPoller(SVNPoller):\n def __init__(...):\n SVNPoller.__init__(self, ...)\n\n def getProcessOutput(self, args):\n args += [\"--trust-server-cert\"]\n return SVNPoller.getProcessOutput(self, args)\n\n", "Use extra_args\nif specified, an array of strings that will be passed as extr...
[ 0, 0 ]
[]
[]
[ "build_process", "buildbot", "project_management", "python", "svn" ]
stackoverflow_0001947508_build_process_buildbot_project_management_python_svn.txt
Q: Design pattern to organize non-trivial ORM queries? I am developing a web API with 10 tables or so in the backend, with several one-to-many and many-to-many associations. The API essentially is a database wrapper that performs validated updates and conditional queries. It's written in Python, and I use SQLAlchemy ...
Design pattern to organize non-trivial ORM queries?
I am developing a web API with 10 tables or so in the backend, with several one-to-many and many-to-many associations. The API essentially is a database wrapper that performs validated updates and conditional queries. It's written in Python, and I use SQLAlchemy for ORM and CherryPy for HTTP handling. So far I have sep...
[ "SQLAlchemy strongly suggests that the session maker be part of some global configuration.\n\nIt is intended that the sessionmaker()\n function be called within the global\n scope of an application, and the\n returned class be made available to\n the rest of the application as the\n single class used to instan...
[ 1, 1 ]
[]
[]
[ "design_patterns", "orm", "python", "refactoring", "sqlalchemy" ]
stackoverflow_0002265234_design_patterns_orm_python_refactoring_sqlalchemy.txt
Q: Grab a line's whitespace/indention with Python Basically, if I have a line of text which starts with indention, what's the best way to grab that indention and put it into a variable in Python? For example, if the line is: \t\tthis line has two tabs of indention Then it would return '\t\t'. Or, if the line was: ...
Grab a line's whitespace/indention with Python
Basically, if I have a line of text which starts with indention, what's the best way to grab that indention and put it into a variable in Python? For example, if the line is: \t\tthis line has two tabs of indention Then it would return '\t\t'. Or, if the line was: this line has four spaces of indention Then it wo...
[ "import re\ns = \"\\t\\tthis line has two tabs of indention\"\nre.match(r\"\\s*\", s).group()\n// \"\\t\\t\"\ns = \" this line has four spaces of indention\"\nre.match(r\"\\s*\", s).group()\n// \" \"\n\nAnd to strip leading spaces, use lstrip.\n\nAs there are down votes probably questioning the efficiency of ...
[ 26, 12, 4, 1 ]
[ "How about using the regex \\s* which matches any whitespace characters. You only want the whitespace at the beginning of the line so either search with the regex ^\\s* or simply match with \\s*.\n", "If you're interested in using regular expressions you can use that. /\\s/ usually matches one whitespace characte...
[ -2, -2 ]
[ "indentation", "python", "whitespace" ]
stackoverflow_0002268532_indentation_python_whitespace.txt
Q: Teleporting Traveler, Optimal Profit over time Problem I'm new to the whole traveling-salesman problem as well as stackoverflow so let me know if I say something that isn't quite right. Intro: I'm trying to code a profit/time-optimized multiple-trade algorithm for a game which involves multiple cities (nodes) wit...
Teleporting Traveler, Optimal Profit over time Problem
I'm new to the whole traveling-salesman problem as well as stackoverflow so let me know if I say something that isn't quite right. Intro: I'm trying to code a profit/time-optimized multiple-trade algorithm for a game which involves multiple cities (nodes) within multiple countries (areas), where: The physical time it...
[ "If this is a game where you are playing against humans I would assume the total size of the data space is actually quite limited. If so I would be inclined to throw out all the fancy pruning as I doubt it's worth it.\nInstead, how about a simple breadth-first search?\nBuild a list of all cities, mark them unvisit...
[ 2, 1 ]
[]
[]
[ "algorithm", "heuristics", "python", "routing", "traveling_salesman" ]
stackoverflow_0002256589_algorithm_heuristics_python_routing_traveling_salesman.txt
Q: Making super() work in Python's urllib2.Request This afternoon I spent several hours trying to find a bug in my custom extension to urllib2.Request. The problem was, as I found out, the usage of super(ExtendedRequest, self), since urllib2.Request is (I'm on Python 2.5) still an old style class, where the use of su...
Making super() work in Python's urllib2.Request
This afternoon I spent several hours trying to find a bug in my custom extension to urllib2.Request. The problem was, as I found out, the usage of super(ExtendedRequest, self), since urllib2.Request is (I'm on Python 2.5) still an old style class, where the use of super() is not possible. The most obvious way to create...
[ "This should work fine since the hierarchy is simple\nclass ExtendedRequest(urllib2.Request):\n def __init__(self,...):\n urllib2.Request.__init__(self,...)\n\n", "Using super may not always be the best-practice. There are many difficulties with using super. Read James Knight's http://fuhm.org/super-har...
[ 1, 1, 0 ]
[]
[]
[ "new_style_class", "python", "request", "super", "urllib2" ]
stackoverflow_0002267016_new_style_class_python_request_super_urllib2.txt
Q: python glib main loop: delaying until loop is entered Is there a way to schedule the execution of a callable until the glib main loop is entered? Alternatively, is there a signal I can subscribe to that will indicate that the main loop is entered? A: You can use gobject.idle_add which will schedule a callable to...
python glib main loop: delaying until loop is entered
Is there a way to schedule the execution of a callable until the glib main loop is entered? Alternatively, is there a signal I can subscribe to that will indicate that the main loop is entered?
[ "You can use gobject.idle_add which will schedule a callable to be executed when the main loop is idle. gobject.timeout_add is an alternative which uses a timer.\nMind that the callable will be called again and again, unless is returns False (or anything that resolves to False, like None).\n" ]
[ 2 ]
[]
[]
[ "glib", "python" ]
stackoverflow_0002268946_glib_python.txt
Q: How to init twisted reactor in the right way? i have a class MyJabber which init a basic jabber account that print the incoming messages to stdout + put them into a queue. The code that add the client to the reactor is this: def addReactor(self): print 'inside AddReactor' factory = client.basicClientFacto...
How to init twisted reactor in the right way?
i have a class MyJabber which init a basic jabber account that print the incoming messages to stdout + put them into a queue. The code that add the client to the reactor is this: def addReactor(self): print 'inside AddReactor' factory = client.basicClientFactory(self.jid, self.option['jabber']['password']) ...
[ "This doesn't seem to really be a question about how to \"init twisted reactor\". Rather, it seems to be more about how to use Twisted Words' XMPP support to send and respond to XMPP messages.\nYou can find a couple examples which do this in the Twisted Words examples directory:\nhttp://twistedmatrix.com/documents...
[ 4, 0 ]
[]
[]
[ "python", "twisted", "twisted.words", "xmpp" ]
stackoverflow_0002265555_python_twisted_twisted.words_xmpp.txt
Q: Package module not found in Python 2.5, but found in 2.6 I have package structure that looks like this: ae util util contains a method mkdir(dir) that, given a path, creates a directory. If the directory exists, no error is thrown; the method fails silently. The directory ae and its parent directory are both ...
Package module not found in Python 2.5, but found in 2.6
I have package structure that looks like this: ae util util contains a method mkdir(dir) that, given a path, creates a directory. If the directory exists, no error is thrown; the method fails silently. The directory ae and its parent directory are both on my PYTHONPATH. When I try to use this method in Python 2....
[ "Maybe Python 2.5 is accessing a different version of util that does not have the mkdir method.\n", "\ndo you import ae.util or import util? Either ae or its parent dir should be in PYTHONPATH, but not both\nverify you have the right util module by running print util (will print the module's source file)\n\n", ...
[ 2, 1, 0 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0002269697_module_package_python.txt
Q: Why can't I do this INSERT in MYSQL? (Python MySQLdb) This is a follow up to this question I asked earlier: Why can't I insert into MySQL? That question solved it partly. Now I'm doing it in Python and it's not working :( cursor.execute("INSERT INTO life(user_id, utm) values(%s,PointFromWKB(point(%s,%s)))",the_us...
Why can't I do this INSERT in MYSQL? (Python MySQLdb)
This is a follow up to this question I asked earlier: Why can't I insert into MySQL? That question solved it partly. Now I'm doing it in Python and it's not working :( cursor.execute("INSERT INTO life(user_id, utm) values(%s,PointFromWKB(point(%s,%s)))",the_user_id, utm_easting, utm_northing) I even did float(utm_eas...
[ "From here (pdf):\n\nFollowing the statement string\n argument to execute(), provide a tuple\n containing the values to be bound to\n the placeholders, in the order they\n should appear within the string. If\n you have only a single value x,\n specify it as (x,) to indicate a\n single-element tuple.\n\ntl;dr...
[ 4, 1, 1 ]
[]
[]
[ "database", "insert", "mysql", "python" ]
stackoverflow_0002269776_database_insert_mysql_python.txt
Q: Why does Sphinx generate json? I notice that Sphinx has the ability to generate documentation in JSON. What are these files used for? A: As the docs say, it's for use of a web application (or custom postprocessing tool) that doesn’t use the standard HTML templates. json's a good simple way for language-...
Why does Sphinx generate json?
I notice that Sphinx has the ability to generate documentation in JSON. What are these files used for?
[ "As the docs say, it's\n\nfor use of a web application (or\n custom postprocessing tool) that\n doesn’t use the standard HTML\n templates.\n\njson's a good simple way for language-agnostic data interchange, so, why not?-)\n", "I assume you're talking about the SerializingHTMLBuilder, in which case I think the ...
[ 6, 0 ]
[]
[]
[ "json", "python", "python_sphinx" ]
stackoverflow_0002269895_json_python_python_sphinx.txt
Q: Python .flv media file conversion I'm looking for a library similar to FFDshow to help me convert .flv to .avi format and possibly do more. I understand that I can do this via VLC player, but I'd rather do it manually with Python (and in bulk). Similar to: media conversion library/plugin preferably php python auto...
Python .flv media file conversion
I'm looking for a library similar to FFDshow to help me convert .flv to .avi format and possibly do more. I understand that I can do this via VLC player, but I'd rather do it manually with Python (and in bulk). Similar to: media conversion library/plugin preferably php python automate ffmpeg conversion from upload dire...
[ "pygst with the right plugins can read .flv files (and write other formats).\n", "Use ffmpeg. You can invoke it from python, if you want to.\nffmpeg -i in.flv -f avi -vcodec mpeg4 -acodec libmp3lame out.avi\n\nFull ducumentation for converting files with ffmpeg can be found here.\n" ]
[ 2, 2 ]
[]
[]
[ "bulk", "flv", "multimedia", "python" ]
stackoverflow_0002267952_bulk_flv_multimedia_python.txt
Q: Python - codec encoding ascii to unicode: error :) I am trying to go about the process of reversing transliteration of an input file(currently in english) back to its original form(in hindi) A sample or a part of the input file looks like this: E-k- b-u-d-z*dhi-m-aan- p-ksii# E-k- ghn-e- j-ngg-l- m-e-ng E-k- b-h-...
Python - codec encoding ascii to unicode: error
:) I am trying to go about the process of reversing transliteration of an input file(currently in english) back to its original form(in hindi) A sample or a part of the input file looks like this: E-k- b-u-d-z*dhi-m-aan- p-ksii# E-k- ghn-e- j-ngg-l- m-e-ng E-k- b-h-u-t- UUNNc-aa p-e-dr thaa# U-s- k-ii p-t-z*t-o-ng s-e...
[ "You have a few problems other than the one which you asked about.\n(1) A conceptual problem: \"E-k- b-u-d-z*dhi-m-aan- p-ksii#\" is not \"english\". It is Hindi language written in ASCII using some romanization scheme. It looks like ITRAN but ITRAN doesn't have AA and A, it has only aa and a. Does the scheme have ...
[ 4, 1, 1 ]
[]
[]
[ "python", "transliteration" ]
stackoverflow_0002265270_python_transliteration.txt
Q: Non-Blocking method for parsing (streaming) XML in python I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without thread...
Non-Blocking method for parsing (streaming) XML in python
I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading). Something like iterparse would be ideal if it finished it...
[ "Diving into the iterparse source provided the solution for me. Here's a simple example of building an XML tree on the fly and processing elements after their close tags:\nimport xml.etree.ElementTree as etree\n\nparser = etree.XMLTreeBuilder()\n\ndef end_tag_event(tag):\n node = self.parser._end(tag)\n print...
[ 8, 4, 1 ]
[]
[]
[ "nonblocking", "parsing", "python", "xml" ]
stackoverflow_0001459648_nonblocking_parsing_python_xml.txt
Q: which is a minimalistic python wsgi development server with support for code reload? From what I can tell wsgiref - no code reload CherryPy - more than just the server mod_wsgi - all the apache overhead paste.httpserver - paste is a huge package with other stuff in it flup - same as paste, too much stuff. Spawnin...
which is a minimalistic python wsgi development server with support for code reload?
From what I can tell wsgiref - no code reload CherryPy - more than just the server mod_wsgi - all the apache overhead paste.httpserver - paste is a huge package with other stuff in it flup - same as paste, too much stuff. Spawning - never used it but seems lightweight enough. Tornado - not really wsgi + full "framewor...
[ "One you might want to look at is Werkzeug - it is a WSGI utility toolkit. It includes a runserver function that takes the wsgiref server and adds automatic code reloading (you can also configure it to reload when configuration files change) and an awesome debugger.\nOn a side note, your disdain for frameworks make...
[ 5, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0002161778_python_wsgi.txt
Q: Django: Template context processor request variable I am trying to implement django-facebookconnect, for I need to check if a user logged in via Facebook or a regular user. At the template, I can check if user logged in via facebook by checking request.facebook.uid such as: {% if is_facebook %} {% show_facebook_ph...
Django: Template context processor request variable
I am trying to implement django-facebookconnect, for I need to check if a user logged in via Facebook or a regular user. At the template, I can check if user logged in via facebook by checking request.facebook.uid such as: {% if is_facebook %} {% show_facebook_photo user %} {% endif %} For this, I need to pass is_face...
[ "If you have access via the request object, why do you need to add a special is_facebook boolean at all? Just enable the built-in django.core.context_processors.request and this will ensure that request is present in all templates, then you can do this:\n{% if request.facebook.uid %}\n\n", "It could be a timing i...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002269508_django_python.txt
Q: Actionscript flex sockets and telnet I am trying to make a flex application where it gets data from a telnet connection and I am running into a weird problem. To give a brief introduction, i want to read data from a process that exposes it through a socket. So if in the shell i type telnet localhost 8651i receive ...
Actionscript flex sockets and telnet
I am trying to make a flex application where it gets data from a telnet connection and I am running into a weird problem. To give a brief introduction, i want to read data from a process that exposes it through a socket. So if in the shell i type telnet localhost 8651i receive the xml and then the connection is closed ...
[ "What security sandbox are you running this in? if you are running this as a flash application embedded in a web page then this is most likely a security violation.\n\nThe XMLSocket.connect() method can\n connect only to computers in the same\n domain where the SWF file resides.\n This restriction does not apply...
[ 0, 0 ]
[]
[]
[ "actionscript_3", "apache_flex", "python", "sockets", "telnet" ]
stackoverflow_0002215308_actionscript_3_apache_flex_python_sockets_telnet.txt
Q: Create a Reg Exp to search for __word__? In a program I'm making in python and I want all words formatted like __word__ to stand out. How could I search for words like these using a regex? A: Perhaps something like \b__(\S+)__\b >>> import re >>> re.findall(r"\b__(\S+)__\b","Here __is__ a __test__ sentence") ['...
Create a Reg Exp to search for __word__?
In a program I'm making in python and I want all words formatted like __word__ to stand out. How could I search for words like these using a regex?
[ "Perhaps something like\n\\b__(\\S+)__\\b\n\n>>> import re\n>>> re.findall(r\"\\b__(\\S+)__\\b\",\"Here __is__ a __test__ sentence\")\n['is', 'test'] \n>>> re.findall(r\"\\b__(\\S+)__\\b\",\"__Here__ is a test __sentence__\")\n['Here', 'sentence']\n>>> re.findall(r\"\\b__(\\S+)__\\b\",\"__Here's__ a test __sente...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002270634_python_regex.txt
Q: How to access string value from new class that inherit string type I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents. How do I get access to the string value assigned to the object of my new class ? class str_usr(str): def __new__(c...
How to access string value from new class that inherit string type
I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents. How do I get access to the string value assigned to the object of my new class ? class str_usr(str): def __new__(cls, arg): return str.__new__(cls, arg) def dub(self)...
[ "Strings in Python are immutable, so once you have one string, you can't change its value. It's almost the same as if you had a class derived from int, and then you added a method to change the value of the int.\nYou can of course return a new value:\nclass str_usr(str):\n def dup(self):\n return self + ...
[ 4, 2, 0 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0002271216_class_oop_python.txt
Q: Is there any limitation in python when handling long file paths? I am writing a file copying utility in Python. But I am getting some error messages when processing files with very long file paths. I suspect Python has some limitations when handling very long file paths. A: Many file systems don't support long f...
Is there any limitation in python when handling long file paths?
I am writing a file copying utility in Python. But I am getting some error messages when processing files with very long file paths. I suspect Python has some limitations when handling very long file paths.
[ "Many file systems don't support long filenames, so it's probably a limitation of the OS or your file system.\nThere are also OS-specific issues like API limitations (e.g. in the Windows API).\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002271437_python.txt
Q: Ready implementation of multivariate Spearman rank correlation I'm looking for a way to calculate multivariate version of Spearman rank correlation $\rho$. Are there any ready to use Python implementation I can use? A: There is one in scipy. A: If now or in the future you will want access to some advanced stat...
Ready implementation of multivariate Spearman rank correlation
I'm looking for a way to calculate multivariate version of Spearman rank correlation $\rho$. Are there any ready to use Python implementation I can use?
[ "There is one in scipy.\n", "If now or in the future you will want access to some advanced statistical packages, also consider calling R libraries from Python when needed via the RPy2. \nAnd then you can compute spearman using a package such as this.\n" ]
[ 2, 1 ]
[]
[]
[ "correlation", "python", "statistics" ]
stackoverflow_0002264609_correlation_python_statistics.txt
Q: django calendar free/busy/availabilitty I am trying to implement a calendar system with the ability to schedule other people for appointments. The system has to be able to prevent scheduling a person during another appointment or during their unavailable time. I have looked at all the existing django calendar proj...
django calendar free/busy/availabilitty
I am trying to implement a calendar system with the ability to schedule other people for appointments. The system has to be able to prevent scheduling a person during another appointment or during their unavailable time. I have looked at all the existing django calendar projects I have found on the internet and none of...
[ "What about using Django's range test.\nFor example:\nappoinment = Appointment()\nappointment.start_time = datetime.datetime.now()\n# 1 hour appointment\nappointment.end_time = appointment.start_time + datetime.timedelta(hours=1)\n# more stuff here\nappointment.save()\n\n# Checking for collision\n# where the start ...
[ 15, 0 ]
[]
[]
[ "calendar", "django", "python" ]
stackoverflow_0002271190_calendar_django_python.txt
Q: Hudson unable to navigate relative directories I have a Python project building with Hudson. Most unit tests work correctly, but any tests that require writing to the file system (I have a class that uses tarfiles, for example) can't find the tmp directory I have set up for intermediate processing (my tearDown met...
Hudson unable to navigate relative directories
I have a Python project building with Hudson. Most unit tests work correctly, but any tests that require writing to the file system (I have a class that uses tarfiles, for example) can't find the tmp directory I have set up for intermediate processing (my tearDown methods remove any files under the relative tmp directo...
[ "Each job in Hudson has it's own working directory, at /path/to/hudson/jobs/[job name]/workspace/\nFor individual jobs, you can set the \"Use custom workspace\" option (under \"Advanced Project Options\") to define where the workspace will be.\nI guess it would depend on how your tests are being run, but if you ins...
[ 2, 1, 0 ]
[]
[]
[ "continuous_integration", "hudson", "python", "unit_testing" ]
stackoverflow_0002270696_continuous_integration_hudson_python_unit_testing.txt
Q: How to use numpy with cygwin I have a bash shell script which calls some python scripts. I am running windows with cygwin which has python in /usr/bin/python. I also have python and numpy installed as a windows package. When I execute the script from cygwin , I get an ImportError - no module named numpy. I have t...
How to use numpy with cygwin
I have a bash shell script which calls some python scripts. I am running windows with cygwin which has python in /usr/bin/python. I also have python and numpy installed as a windows package. When I execute the script from cygwin , I get an ImportError - no module named numpy. I have tried running from windows shell bu...
[ "Windows python and Cygwin Python are independent; if you're using Cygwin's Python, you need to have numpy installed in cygwin.\nIf you'd prefer to use the Windows python, you should be able to call it from a bash script by either:\n\nCalling the windows executable directly: c:/Python/python.exe ./emulate.py\nChang...
[ 4, 0 ]
[]
[]
[ "cygwin", "numpy", "python" ]
stackoverflow_0002271565_cygwin_numpy_python.txt
Q: Help generate Facebook API "Sig" in Python I have been struggling with this for over two days and I could use your help. Here's the problem: Whenever a request is made to the Facebook REST server, we have to send an additional parameter called "sig". This sig is generated using the following algorithm: <?php $sec...
Help generate Facebook API "Sig" in Python
I have been struggling with this for over two days and I could use your help. Here's the problem: Whenever a request is made to the Facebook REST server, we have to send an additional parameter called "sig". This sig is generated using the following algorithm: <?php $secret = 'Secret Key'; // where 'Secret Key' is you...
[ "List had to be sorted.\n" ]
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0002264333_facebook_google_app_engine_python.txt
Q: QtDesigner or doing all of the Qt boilerplate by hand? When starting up a new project, as a beginner, which would you use? For example, in my situation. I'm going to have a program running on an infinite loop, constantly updating values. I need these values to be represented as a bar graph as they're updating....
QtDesigner or doing all of the Qt boilerplate by hand?
When starting up a new project, as a beginner, which would you use? For example, in my situation. I'm going to have a program running on an infinite loop, constantly updating values. I need these values to be represented as a bar graph as they're updating. At the same time, the GUI has to be responsive to user fee...
[ "If I understood your question correctly, updating the GUI has a little to do with the way you programmed it.\nFrom my experience, it's easier to design a main window (or whatever your top level object is) in Designer, and add some dynamically updated content in a widget(s) created in your code. In most cases, it s...
[ 1, 0, 0 ]
[]
[]
[ "pyqt", "python", "user_interface" ]
stackoverflow_0002268853_pyqt_python_user_interface.txt
Q: Python: automated change in variable contents I have a Python function which receives numerous variables, and builds an SQL query out of them: def myfunc(name=None, abbr=None, grade=None, ...) These values should build an SQL query. For that purpose, Those who equal None should be changed to NULL, and those who s...
Python: automated change in variable contents
I have a Python function which receives numerous variables, and builds an SQL query out of them: def myfunc(name=None, abbr=None, grade=None, ...) These values should build an SQL query. For that purpose, Those who equal None should be changed to NULL, and those who store useful values should be embraced with 's: name...
[ "The best way to form a SQL query is not by string-formatting -- the execute method of a cursor object takes a query string with placeholders and a sequence (or dict, depending on the exact implementation you have of the DB API) with the values to substitute there; it will then perform the None-to-Null and string-q...
[ 5, 0, 0 ]
[]
[]
[ "psycopg2", "python", "variables" ]
stackoverflow_0002172654_psycopg2_python_variables.txt
Q: How to fix "can't adapt error" when saving binary data using python psycopg2 I ran across this bug three times today in one of our projects. Putting the problem and solution online for future reference. impost psycopg2 con = connect(...) def save(long_blob): cur = con.cursor() long_data = struct.unpa...
How to fix "can't adapt error" when saving binary data using python psycopg2
I ran across this bug three times today in one of our projects. Putting the problem and solution online for future reference. impost psycopg2 con = connect(...) def save(long_blob): cur = con.cursor() long_data = struct.unpack('<L', long_blob) cur.execute('insert into blob_records( blob_data ) values...
[ "The problem is struct.unpack returns a tuple result, even if there is only one value to unpack. You need to make sure you grab the first item from the tuple, even if there is only one item. Otherwise psycopg2 sql argument parsing will fail trying to convert the tuple to a string giving the \"can't adapt\" error ...
[ 4, 1 ]
[]
[]
[ "iterable_unpacking", "postgresql", "psycopg2", "python", "unpack" ]
stackoverflow_0002149515_iterable_unpacking_postgresql_psycopg2_python_unpack.txt
Q: Why are these lists the same? I can't understand how x and y are the same list. I've been trying to debug it using print statements and import code; code.interact(local=locals()) to drop into various points, but I can't figure out what on earth is going on :-( from collections import namedtuple, OrderedDict coord...
Why are these lists the same?
I can't understand how x and y are the same list. I've been trying to debug it using print statements and import code; code.interact(local=locals()) to drop into various points, but I can't figure out what on earth is going on :-( from collections import namedtuple, OrderedDict coordinates_2d=["x","y"] def virtual_co...
[ "The problem is with this line:\nd={key: lambda self: self.__vals__[key] for key in objects_type}\n\nThe lambda uses the value of the variable key, but that value has changed by the time the lambda is called - so all lambdas will actually use the same value for the key.\nThis can be fixed with a little trick: Pass ...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002272119_python.txt
Q: How can I use a large wxCursor? The wx.Cursor class automatically scales the image I give it to 32x32 and I need to use a cursor that is larger than that. On http://support.microsoft.com/kb/307213 I saw what might be the reason for this behavior Although cursors can, in theory, be any size, the system imposes a...
How can I use a large wxCursor?
The wx.Cursor class automatically scales the image I give it to 32x32 and I need to use a cursor that is larger than that. On http://support.microsoft.com/kb/307213 I saw what might be the reason for this behavior Although cursors can, in theory, be any size, the system imposes a standard size that is exposed by ...
[ "It turns out wx doesn't do anything to support non standard sized cursors.\nhttp://groups.google.com/group/wxpython-users/browse_thread/thread/326aea0d740b85dd/277483ad5df77539\n" ]
[ 0 ]
[]
[]
[ "python", "windows", "wxpython" ]
stackoverflow_0002267986_python_windows_wxpython.txt
Q: Class Inheritance through Multiple Classes I have 3 classes and I run the first class and declare a variable in the second class and want the 3rd class to be able to print out this variable. I have code below to explain this more clearly. from class2 import Class2 class Class1(Class2): def __init__(self): ...
Class Inheritance through Multiple Classes
I have 3 classes and I run the first class and declare a variable in the second class and want the 3rd class to be able to print out this variable. I have code below to explain this more clearly. from class2 import Class2 class Class1(Class2): def __init__(self): self.value1 = 10 self.value2 = 20 ...
[ "It is kind of hard to understand what you are trying to do as your code does not even run.\nI think something like this is what you are trying to do:\nclass Class3():\n\n def printValue(self):\n print self.string1\n\nclass Class2(Class3):\n\n def e(self):\n self.value4 = self.value3 - self.valu...
[ 1, 0 ]
[]
[]
[ "class", "inheritance", "parameters", "python" ]
stackoverflow_0002272728_class_inheritance_parameters_python.txt
Q: Face-tracking libraries for Java or Python I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll hav...
Face-tracking libraries for Java or Python
I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I...
[ "Checkout OpenCV Python Interface\n", "\"faint\" (The Face Annotation Interface) might be what you're looking for.\nhttp://faint.sourceforge.net/\nhttp://technoroy.blogspot.com/2008/06/faint-search-for-faces.html\nI never used it myself. However, I played with the application which bundles with faint.\n", "Ther...
[ 7, 2, 2, 0 ]
[]
[]
[ "face_detection", "java", "python" ]
stackoverflow_0000802243_face_detection_java_python.txt
Q: Python: select function With this code: import scipy from scipy import * x = r_[1:15] print x a = select([x > 7, x >= 4],[x,x+10]) print a I get this answer: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14] [ 0 0 0 14 15 16 17 8 9 10 11 12 13 14] But why do I have zeros in the beginning and not in the end? T...
Python: select function
With this code: import scipy from scipy import * x = r_[1:15] print x a = select([x > 7, x >= 4],[x,x+10]) print a I get this answer: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14] [ 0 0 0 14 15 16 17 8 9 10 11 12 13 14] But why do I have zeros in the beginning and not in the end? Thanks in advance.
[ "You seem to be using numpy.\nFrom the documentation for numpy.select():\n\nnumpy.select(condlist, choicelist, default=0)\n...\ndefault: The element inserted in output when all conditions evaluate to False.\n\nSince your conditions are x > 7 and x >=4, the output array will have elements from x+10 when x >= 4 and f...
[ 5 ]
[]
[]
[ "numpy", "python", "select" ]
stackoverflow_0002272854_numpy_python_select.txt
Q: how to define generic variables in Python (syntax question) With Python it is easy to declare something like self.x = "something" print self.x #outputs "something" I want to have something like this: param["key"] = "x" self.param["key"] = "something" #here I actually want to access this "self" parameter as below ...
how to define generic variables in Python (syntax question)
With Python it is easy to declare something like self.x = "something" print self.x #outputs "something" I want to have something like this: param["key"] = "x" self.param["key"] = "something" #here I actually want to access this "self" parameter as below with its value defined above print self.x #supposed to output "so...
[ "Use setattr -- setattr(self, param['key'], 'something').\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002273211_python.txt
Q: Avoid race condition when asserting file permissions in Python An application wants to parse and "execute" a file, and wants to assert the file is executable for security reasons. A moments thought and you realize this initial code has a race condition that makes the security scheme ineffective: import os class E...
Avoid race condition when asserting file permissions in Python
An application wants to parse and "execute" a file, and wants to assert the file is executable for security reasons. A moments thought and you realize this initial code has a race condition that makes the security scheme ineffective: import os class ExecutionError (Exception): pass def execute_file(filepath): ...
[ "The executability is attached to the file you open, there is nothing stopping several files from pointing to the inode containing the data you wish to read. In other words, the same data may be readable from a non-executable file elsewhere in the same filesystem. Furthermore, even after opening the file, you can't...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "posix", "python", "race_condition", "security" ]
stackoverflow_0002258257_posix_python_race_condition_security.txt
Q: Problem with replacing a word in a file, using Python I have a .txt file containing data like this: 1,Rent1,Expense,16/02/2010,1,4000,4000 1,Car Loan1,Expense,16/02/2010,2,4500,9000 1,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000...
Problem with replacing a word in a file, using Python
I have a .txt file containing data like this: 1,Rent1,Expense,16/02/2010,1,4000,4000 1,Car Loan1,Expense,16/02/2010,2,4500,9000 1,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000 0,Flat Loan2,Expense,16/02/2010,2,4000,8000 I want to ...
[ "print adds an extra newline after the input and you already have one newline there. You should either strip the existing newline (line.rstrip(\"\\n\")) or use sys.stdout.write() instead.\n", "import fileinput\nimport re\np = re.compile(r'^0,')\nfor line in fileinput.FileInput(\"sample.txt\",inplace=1):\n prin...
[ 4, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "file", "python", "replace" ]
stackoverflow_0002271199_file_python_replace.txt
Q: Should pre-commit tests use a big data set and fail if queries take too long, or use a small test database? I am developing some Python modules that use a mysql database to insert some data and produce various types of report. I'm doing test driven development and so far I run: some CREATE / UPDATE / DELETE tests...
Should pre-commit tests use a big data set and fail if queries take too long, or use a small test database?
I am developing some Python modules that use a mysql database to insert some data and produce various types of report. I'm doing test driven development and so far I run: some CREATE / UPDATE / DELETE tests against a temporary database that is thrown away at the end of each test case, and some report generation tests...
[ "I'd do both. Run against the small set first to make sure all the code works, then run against the large dataset for things which need to be tested for time, this would be selects, searches and reports especially. If you are doing inserts or deletes or updates on multiple row sets, I'd test those as well against t...
[ 1, 1 ]
[]
[]
[ "automated_tests", "mysql", "python", "sql", "tdd" ]
stackoverflow_0002273414_automated_tests_mysql_python_sql_tdd.txt
Q: Is it possible to define a wx.Panel as a class in Python? I want to define several plugins. They all inherit from the superclass Plugin. Each plugin consists on a wx.Panel that have a more specific method called "draw". How can I define a class as a Panel and afterwards call that class in my frame? I've tried like...
Is it possible to define a wx.Panel as a class in Python?
I want to define several plugins. They all inherit from the superclass Plugin. Each plugin consists on a wx.Panel that have a more specific method called "draw". How can I define a class as a Panel and afterwards call that class in my frame? I've tried like this: class Panel(wx.Panel): def __init__(self, parent): ...
[ "class MyPanel(wx.Panel):\n def __init__(self, *args):\n wx.Panel.__init__(self, *args)\n\n def draw(self):\n # Your code here\n\n", "There is a class wx.PyPanel that is a version of Panel intended to be subclassed from Python and allows you to override C++ virtual methods.\nThere are PyXxxx v...
[ 5, 2, 0 ]
[]
[]
[ "class", "frame", "panel", "python", "wxpython" ]
stackoverflow_0002272889_class_frame_panel_python_wxpython.txt
Q: Python: Visualisation of waves I want to programm an easy visualisation of wave propagation. I tried this with visual python (VPython) but the programm is very slow. I want to use a 2-D visualisation now. Which module could you recommend? Tkinter? Matplotlib? For the computation i use numpy/scipy because it is f...
Python: Visualisation of waves
I want to programm an easy visualisation of wave propagation. I tried this with visual python (VPython) but the programm is very slow. I want to use a 2-D visualisation now. Which module could you recommend? Tkinter? Matplotlib? For the computation i use numpy/scipy because it is fast. Thanks in advance. EDIT: Do you...
[ "Try this library:\nhttp://linux.wareseeker.com/Programming/summon-1.8.8.zip/2911b4d847\nPython Imaging Library is supposed to be good for 2D graphics:\nhttp://www.pythonware.com/products/pil/ \nOther Useful Links:\nBoost.Python http://www.boost.org/libs/python/doc/\nPyOpenGL http://pyopengl.sourceforge.net/ \nThes...
[ 1 ]
[]
[]
[ "physics", "python", "visualization", "wave" ]
stackoverflow_0002273699_physics_python_visualization_wave.txt
Q: Regex divide with upper-case I would like to replace strings like 'HDMWhoSomeThing' to 'HDM Who Some Thing' with regex. So I would like to extract words which starts with an upper-case letter or consist of upper-case letters only. Notice that in the string 'HDMWho' the last upper-case letter is in the fact the fir...
Regex divide with upper-case
I would like to replace strings like 'HDMWhoSomeThing' to 'HDM Who Some Thing' with regex. So I would like to extract words which starts with an upper-case letter or consist of upper-case letters only. Notice that in the string 'HDMWho' the last upper-case letter is in the fact the first letter of the word Who - and sh...
[ "Try to split with this regular expression:\n/(?=[A-Z][a-z])/\n\nAnd if your regular expression engine does not support splitting empty matches, try this regular expression to put spaces between the words:\n/([A-Z])(?![A-Z])/\n\nReplace it with \" $1\" (space plus match of the first group). Then you can split at th...
[ 2, 2, 2, 1, 1 ]
[]
[]
[ "python", "regex", "split", "string", "uppercase" ]
stackoverflow_0002273462_python_regex_split_string_uppercase.txt
Q: SQLAlchemy subquery - average of sums is there any way how to write the following SQL statement in SQLAlchemy ORM: SELECT AVG(a1) FROM (SELECT sum(irterm.n) AS a1 FROM irterm GROUP BY irterm.item_id); Thank you A: sums = session.query(func.sum(Irterm.n).label('a1')).group_by(Irterm.item_id).subquery() average =...
SQLAlchemy subquery - average of sums
is there any way how to write the following SQL statement in SQLAlchemy ORM: SELECT AVG(a1) FROM (SELECT sum(irterm.n) AS a1 FROM irterm GROUP BY irterm.item_id); Thank you
[ "sums = session.query(func.sum(Irterm.n).label('a1')).group_by(Irterm.item_id).subquery()\naverage = session.query(func.avg(sums.c.a1)).scalar()\n\n" ]
[ 31 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002273127_python_sqlalchemy.txt
Q: Encode East Asian languages using Python This may not really be a Python related question, but pertains to language encoding in general. I'm mining tweets from Twitter, and it appears that there is a large Japanese user community (with messages in Japanese). When I tried encoding the tweets for an XML file I used ...
Encode East Asian languages using Python
This may not really be a Python related question, but pertains to language encoding in general. I'm mining tweets from Twitter, and it appears that there is a large Japanese user community (with messages in Japanese). When I tried encoding the tweets for an XML file I used utf-8. e.g tweet=tweet.encode('utf-8') and non...
[ "Normally you would query the format for what encoding the data is in. Having said that, Shift-JIS is quite a popular encoding for Japanese text.\n>>> u'あいうえお'.encode('shift-jis')\n'\\x82\\xa0\\x82\\xa2\\x82\\xa4\\x82\\xa6\\x82\\xa8'\n\n", "There should be a way to query the encoding of the tweets when read from ...
[ 3, 2 ]
[]
[]
[ "csv", "encoding", "python", "xml" ]
stackoverflow_0002270928_csv_encoding_python_xml.txt
Q: ldap raises an UNWILLING TO PERFORM error My Django application is using python-ldap library (ldap_groups django application) and must add users against an Active Directory on a Windows 2003 Virtual Machine domain. My application running on a Ubuntu virtual Machine is not member of the Windows domain. Here is the ...
ldap raises an UNWILLING TO PERFORM error
My Django application is using python-ldap library (ldap_groups django application) and must add users against an Active Directory on a Windows 2003 Virtual Machine domain. My application running on a Ubuntu virtual Machine is not member of the Windows domain. Here is the code: settings.py DNS_NAME='IP_ADRESS' LDAP_PO...
[ "I found the problem. In fact my objectclass was not compliant with Active Directory.\nFurthermore change information encoding by a python string.\nHere is the code to use:\n attrs = {}\n attrs['objectclass'] = ['top','person','organizationalPerson','user']\n attrs['cn'] = str(username)\n attrs...
[ 2 ]
[]
[]
[ "django", "ldap", "python" ]
stackoverflow_0002273117_django_ldap_python.txt
Q: Python: Can't use the command python I want to install summon-module on windows 7. I tried python setup.py install but cmd doesn't know the command "python". I also set the path correctly. What is the problem? Thanks in advance. A: PATH needs to point to the directory your python.exe is in, or it needs to be i...
Python: Can't use the command python
I want to install summon-module on windows 7. I tried python setup.py install but cmd doesn't know the command "python". I also set the path correctly. What is the problem? Thanks in advance.
[ "PATH needs to point to the directory your python.exe is in, or it needs to be in the current directory, or you need to specify the full path.\nPYTHONPATH needs to point to the directory your setup.py is in, or it needs to be in the current directory, or you need to specify the full path.\n", "Add the directory w...
[ 4, 3, 0 ]
[]
[]
[ "installation", "python", "windows" ]
stackoverflow_0002274319_installation_python_windows.txt
Q: Why User model inheritance doesn't work properly? I'm trying to use a User model inheritance in my django application. Model looks like this: from django.contrib.auth.models import User, UserManager class MyUser(User): ICQ = models.CharField(max_length=9) objects = UserManager() and authentication backen...
Why User model inheritance doesn't work properly?
I'm trying to use a User model inheritance in my django application. Model looks like this: from django.contrib.auth.models import User, UserManager class MyUser(User): ICQ = models.CharField(max_length=9) objects = UserManager() and authentication backend looks like this: import sys from django.db import mo...
[ "Contrary to what the blog post you linked to says, storing this kind of data in a profile model is still the recommended way in Django. Subclassing User has all kinds of problems, one of which is the one you are hitting: Django has no idea you have subclassed User and happily creates and reads User models within t...
[ 4 ]
[]
[]
[ "django", "django_models", "inheritance", "python" ]
stackoverflow_0002274442_django_django_models_inheritance_python.txt
Q: eagerly evaluating boolean expressions in Python Is there a way (using eval or whatever) to evaluate eagerly boolean expressions in python? Let's see this: >>> x = 3 >>> 5 < x < y False Yikes! That's very nice, because this will be false regardless of y's value. The thing is, y can be even undefined, and I'd like...
eagerly evaluating boolean expressions in Python
Is there a way (using eval or whatever) to evaluate eagerly boolean expressions in python? Let's see this: >>> x = 3 >>> 5 < x < y False Yikes! That's very nice, because this will be false regardless of y's value. The thing is, y can be even undefined, and I'd like to get that exception. How can I get python to evalua...
[ "(5 < x) & (x < y)\n\nBy using the bit-and operator, &, you get no short-circuiting behavior (as you get with and, or, chaining, all/any). Short-circuiting is normally deemed desirable (fast &c) but it's not hard to do without it if you really want;-).\n", "all([5 < x, x < y])\n\n", "The most natural way would...
[ 6, 5, 5, 3, 2, 1 ]
[]
[]
[ "eager", "exception_handling", "lazy_evaluation", "python" ]
stackoverflow_0002271017_eager_exception_handling_lazy_evaluation_python.txt
Q: Where to put Python files to be redirected to by urls.py in Django? Where do I put python files to be redirected to by urls.py in Django? The tutorial showed something like this: urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), Where do I set up pages to be easily linked as something.s...
Where to put Python files to be redirected to by urls.py in Django?
Where do I put python files to be redirected to by urls.py in Django? The tutorial showed something like this: urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), Where do I set up pages to be easily linked as something.something.page like this? I am currently just trying to drop straight .py ...
[ "You need to use views. You can create views (keep reading the official django documentation), then import them into your urls.py file and use them. Here's an example:\nviews.py\nfrom django.shortcuts import render_to_response\n\ndef index(request):\n \"\"\"\n Main page.\n \"\"\"\n return render_to_response...
[ 6 ]
[]
[]
[ "django", "django_urls", "frameworks", "python" ]
stackoverflow_0002275016_django_django_urls_frameworks_python.txt
Q: python multi-processing queue: is putting independent from getting? Is putting an object in a multi-processing queue independent from getting an object from it? In other words, will putting an object block the process P1 if another process P2 is getting from it? Update: I am assuming an infinite queue. A: My rea...
python multi-processing queue: is putting independent from getting?
Is putting an object in a multi-processing queue independent from getting an object from it? In other words, will putting an object block the process P1 if another process P2 is getting from it? Update: I am assuming an infinite queue.
[ "My reading of the source code is that get obtains a read lock, which is independent of of the lock (called _notempty) acquired by put. If I understand correctly, concurrent gets can block each other, and concurrent puts can block each other (modulo your use of the block parameter), but that gets and puts do not mu...
[ 2 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0002275108_multiprocessing_python_queue.txt
Q: Why does django not do for the User model the same as it does for the userprofile model? Why doesn't django just have the model to use for User configured in the settings file? The requirements on the model specified would be that it contain a certain set of fields. Is there a reason why it couldn't be done this w...
Why does django not do for the User model the same as it does for the userprofile model?
Why doesn't django just have the model to use for User configured in the settings file? The requirements on the model specified would be that it contain a certain set of fields. Is there a reason why it couldn't be done this way?
[ "The User model has a lot of dependencies and must conform to a diverse set of API requirements in order to interoperate with the rest of the django framework. This is because of its relationship with authentication and authorization. Changing User means changing the expected behavior of contrib.auth. If you wan...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002275043_django_python.txt
Q: POP3_SSL Not Found in poplib module What would cause this strange error when trying to use the poplib.POP3_SSL class. Traceback (most recent call last): File "test.py", line 131, in <module> M = poplib.POP3_SSL('XXXXXXXX', 995) AttributeError: 'module' object has no attribute 'POP3_SSL' My environment is Py...
POP3_SSL Not Found in poplib module
What would cause this strange error when trying to use the poplib.POP3_SSL class. Traceback (most recent call last): File "test.py", line 131, in <module> M = poplib.POP3_SSL('XXXXXXXX', 995) AttributeError: 'module' object has no attribute 'POP3_SSL' My environment is Python 2.6, REHL5 I've never run into this ...
[ "Your python might be compiled without ssl support.\n" ]
[ 1 ]
[]
[]
[ "pop3", "python", "ssl" ]
stackoverflow_0002275913_pop3_python_ssl.txt
Q: How to change wx.Panel background color on MouseOver? this code: import wx app = None class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.SetBackgroundColour((11, 11, 11)) self.name = "plugin" self.Bind(wx...
How to change wx.Panel background color on MouseOver?
this code: import wx app = None class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.SetBackgroundColour((11, 11, 11)) self.name = "plugin" self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver) self.Bind(wx.E...
[ "The method is named SetBackgroundColour, with a u.\nAlso, you're binding events twice with two different methods. Just use the self.Bind style, and remove the other two lines.\n" ]
[ 13 ]
[]
[]
[ "panel", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002275917_panel_python_wxpython_wxwidgets.txt
Q: Django generic relations practice i'm developing a authentication backend with object-based permissions for my django-app.I use generic relations between an object and a permission: class GroupPermission(models.Model): content_t= models.ForeignKey(ContentType,related_name='g_content_t') object_id = models....
Django generic relations practice
i'm developing a authentication backend with object-based permissions for my django-app.I use generic relations between an object and a permission: class GroupPermission(models.Model): content_t= models.ForeignKey(ContentType,related_name='g_content_t') object_id = models.PositiveIntegerField() content_obje...
[ "I'm guessing you're looking for something like:\nperm = Permission.objects.get(pk=1) # pk #1 for brevity.\ngroup = Group.objects.get(pk=1) # Again, for brevity.\ngroup_perms = GroupPermission.objects.filter(permission=perm, group=group)\nobjects = [x.content_object for x in group_perms]\n\nThis should get all ...
[ 3 ]
[]
[]
[ "django", "django_orm", "generic_relationship", "python" ]
stackoverflow_0002275602_django_django_orm_generic_relationship_python.txt
Q: Django legacy database encoding I'm sure this question is not specific to django, but since I couldn't find any solution for my problem in other questions about python and encodings, I'm going to ask this. I need to add new features to existing website which is written in PHP using MySQL as backend. I inspected th...
Django legacy database encoding
I'm sure this question is not specific to django, but since I couldn't find any solution for my problem in other questions about python and encodings, I'm going to ask this. I need to add new features to existing website which is written in PHP using MySQL as backend. I inspected the database and created models for tab...
[ "Check your mysql connection parameters. Also, You can specify DATABASE_OPTIONS:\nDATABASE_OPTIONS = {\n \"charset\": \"utf8\",\n \"init_command\": \"SET storage_engine=InnoDB\",\n}\n\nBut check out if it's really utf-8. Also note that connection and server encoding must be in sync. \n", "Actually this prob...
[ 1, 1 ]
[]
[]
[ "django", "encoding", "python" ]
stackoverflow_0002267242_django_encoding_python.txt
Q: What's the advantage of queues over pipes when communicating between processes? What would be the advantage(s) (if any) of using 2 Queues over a Pipe to communicate between processes? I am planning on using the multiprocessing python module. A: The big win is that queues are process- and thread- safe. Pipes are ...
What's the advantage of queues over pipes when communicating between processes?
What would be the advantage(s) (if any) of using 2 Queues over a Pipe to communicate between processes? I am planning on using the multiprocessing python module.
[ "The big win is that queues are process- and thread- safe. Pipes are not: if two different processes try to read from or write to the same end of a pipe, bad things happen. Queues are also at a somewhat higher level of abstraction than pipes, which may or may not be an advantage in your specific case.\n", "Queues...
[ 12, 4 ]
[]
[]
[ "linux", "multiprocessing", "pipe", "python", "queue" ]
stackoverflow_0002275909_linux_multiprocessing_pipe_python_queue.txt
Q: How do I get my simple twisted proxy to work? I am attempting to make use of the Twisted.Web framework. Notice the three line comments (#line1, #line2, #line3). I want to create a proxy (gateway?) that will forward a request to one of two servers depending on the url. If I uncomment either comment 1 or 2 (and comm...
How do I get my simple twisted proxy to work?
I am attempting to make use of the Twisted.Web framework. Notice the three line comments (#line1, #line2, #line3). I want to create a proxy (gateway?) that will forward a request to one of two servers depending on the url. If I uncomment either comment 1 or 2 (and comment the rest), the request is proxied to the correc...
[ "Since your Simple class implements the getChild() method, it is implied that this is not a leaf node, however, you are stating that it is a leaf node by setting isLeaf = True. (How can a leaf node have a child?).\nTry changing isLeaf = True to isLeaf = False and you'll find that it redirects to the proxy as you'd ...
[ 4, 2 ]
[]
[]
[ "proxy", "python", "twisted" ]
stackoverflow_0002269380_proxy_python_twisted.txt
Q: IF in the Django template system How do I do this: {% if thestring %} {% if thestring.find("1") >= 0 %} {% endif %} {% endif %} I am assuming I need to build a template filter? Will that work? A: It would. But use the in operator instead of the find() method. Example: {% if thestring|contains:"1" %} ...
IF in the Django template system
How do I do this: {% if thestring %} {% if thestring.find("1") >= 0 %} {% endif %} {% endif %} I am assuming I need to build a template filter? Will that work?
[ "It would. But use the in operator instead of the find() method.\nExample:\n{% if thestring|contains:\"1\" %}\n\n", "You don't need to build a custom filter, though one would work -- the alternative of coding\n{% if thestring %}\n\n {% if \"1\" in thestring %}\n\n {% endif %}\n\n{% endif %}\n\nwould also go...
[ 3, 3, 1 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002276319_django_python_templates.txt
Q: Python multiprocessing process vs. standalone Python VM Aside from the ease of use of the multiprocessing module when it comes to hooking up processes with communication resources, are there any other differences between spawning multiple processes using multiprocessing compared to using subprocess to launch separ...
Python multiprocessing process vs. standalone Python VM
Aside from the ease of use of the multiprocessing module when it comes to hooking up processes with communication resources, are there any other differences between spawning multiple processes using multiprocessing compared to using subprocess to launch separate Python VMs ?
[ "On Posix platforms, multiprocessing primitives essentially wrap an os.fork(). What this means is that at point you spawn a process in multiprocessing, the code already imported/initialized remains so in the child process.\nThis can be a boon if you have a lot of things to initialize and then each subprocess essent...
[ 22, 5 ]
[]
[]
[ "multiprocessing", "python", "virtual_machine" ]
stackoverflow_0002276117_multiprocessing_python_virtual_machine.txt
Q: Where is the phpMailer php class equivalent for Python? i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment. So, i've found this tutorial and adapted it with the gmail authentication (tutorial found here) The code i have atm, is that: def ...
Where is the phpMailer php class equivalent for Python?
i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment. So, i've found this tutorial and adapted it with the gmail authentication (tutorial found here) The code i have atm, is that: def createhtmlmail (html, text, subject): """Create a mime-messag...
[ "If you can excuse some blatant self promotion, I wrote a mailer module that makes sending email with Python fairly simple. No dependencies other than the Python smtplib and email libraries.\nHere's a simple example for sending an email with an attachment:\nfrom mailer import Mailer\nfrom mailer import Message\n\nm...
[ 6, 3, 2, 1, 0 ]
[]
[]
[ "email", "phpmailer", "python" ]
stackoverflow_0000807302_email_phpmailer_python.txt
Q: Extending a list of lists in Python? I might be missing something about the intended behavior of list extend, but why does the following happen? x = [[],[]] y = [[]] * 2 print x # [[],[]] print y # [[],[]] print x == y # True x[0].extend([1]) y[0].extend([1]) print x # [[1],[]], which is what I'...
Extending a list of lists in Python?
I might be missing something about the intended behavior of list extend, but why does the following happen? x = [[],[]] y = [[]] * 2 print x # [[],[]] print y # [[],[]] print x == y # True x[0].extend([1]) y[0].extend([1]) print x # [[1],[]], which is what I'd expect print y # [[1],[1]], wtf? I w...
[ "In the case of [something] * 2, python is simply making a reference-copy. Therefore, if the enclosed type(s) are mutable, changing them will be reflected anywhere the item is referenced.\nIn your example, y[0] and y[1] point to the same enclosed list object. You can verify this by doing y[0] is y[1] or alternately...
[ 17, 4, 1 ]
[]
[]
[ "extend", "list", "python" ]
stackoverflow_0002276416_extend_list_python.txt
Q: Path of current Python instance? I need to access the Scripts and tcl sub-directories of the currently executing Python instance's installation directory on Windows. What is the best way to locate these directories? A: Have a look at sys.prefix and sys.exec_prefix >>> import sys >>> sys.prefix '/System/Library/F...
Path of current Python instance?
I need to access the Scripts and tcl sub-directories of the currently executing Python instance's installation directory on Windows. What is the best way to locate these directories?
[ "Have a look at sys.prefix and sys.exec_prefix\n>>> import sys\n>>> sys.prefix\n'/System/Library/Frameworks/Python.framework/Versions/2.6'\n>>> sys.exec_prefix\n'/System/Library/Frameworks/Python.framework/Versions/2.6'\n\n", "Hmm, find the Lib dir from sys.path and extrapolate from there?\n" ]
[ 3, 0 ]
[]
[]
[ "installation", "path", "python", "python_3.x", "windows" ]
stackoverflow_0002276512_installation_path_python_python_3.x_windows.txt
Q: Import OPML subscriptions (file) to Google Reader manually I have a huge (5,000+ feeds) OPML file which freezes and crashes my browser when I try uploading it to my Google Reader account using the following instructions: Login to Google Reader Click Your Subscription Click the More Actions dropdown Select Import ...
Import OPML subscriptions (file) to Google Reader manually
I have a huge (5,000+ feeds) OPML file which freezes and crashes my browser when I try uploading it to my Google Reader account using the following instructions: Login to Google Reader Click Your Subscription Click the More Actions dropdown Select Import Browse for your OPML file Click Open Click Upload You will see ...
[ "Found an answer on Superuser on How to import an OPML file with 1500 feeds into Google Reader\n" ]
[ 1 ]
[]
[]
[ "api", "file_upload", "google_reader", "opml", "python" ]
stackoverflow_0002076488_api_file_upload_google_reader_opml_python.txt
Q: Python: Separating an HTML snippets to paragraphs I have a snippet of HTML that contains paragraphs. (I mean p tags.) I want to split the string into the different paragraphs. For instance: ''' <p class="my_class">Hello!</p> <p>What's up?</p> <p style="whatever: whatever;">Goodbye!</p> ''' Should become: ['<p cla...
Python: Separating an HTML snippets to paragraphs
I have a snippet of HTML that contains paragraphs. (I mean p tags.) I want to split the string into the different paragraphs. For instance: ''' <p class="my_class">Hello!</p> <p>What's up?</p> <p style="whatever: whatever;">Goodbye!</p> ''' Should become: ['<p class="my_class">Hello!</p>', '<p>What's up?</p>' '<p st...
[ "If your string only contains paragraphs, you may be able to get away with a nicely crafted regex and re.split(). However, if your string is more complex HTML, or not always valid HTML, you might want to look at the BeautifulSoup package.\nUsage goes like:\nfrom BeautifulSoup import BeautifulSoup \n\nsoup = Beauti...
[ 5, 2, 0, 0 ]
[]
[]
[ "beautifulsoup", "html", "lxml", "python" ]
stackoverflow_0002276824_beautifulsoup_html_lxml_python.txt
Q: python: Regex matching file extension hi i am trying to get the extension of the file called in a url (eg /wp-includes/js/jquery/jquery.js?ver=1.3.2 HTTP/1.1) and get the query parameters passed to the file too. What would be the best way to the extension? A: urlparse.urlparse() and os.path.splitext().
python: Regex matching file extension
hi i am trying to get the extension of the file called in a url (eg /wp-includes/js/jquery/jquery.js?ver=1.3.2 HTTP/1.1) and get the query parameters passed to the file too. What would be the best way to the extension?
[ "urlparse.urlparse() and os.path.splitext().\n" ]
[ 7 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002277030_python_regex.txt
Q: django-registration, fix for a glitch I am using django-registration version 0.8 I use the default django-registration and Django auth system without any tweak. I did notice a small glitch, once I log in as a user, if I go to the /accounts/login/ , I still get the login entry form, how can I change that it redir...
django-registration, fix for a glitch
I am using django-registration version 0.8 I use the default django-registration and Django auth system without any tweak. I did notice a small glitch, once I log in as a user, if I go to the /accounts/login/ , I still get the login entry form, how can I change that it redirect a logged in user to the main root url /...
[ "You can wrap Django's login view and do the check for already authenticated users there:\nfrom django.contrib.auth.views import login\nfrom django.http import HttpResponseRedirect\n\ndef mylogin(request, **kwargs):\n if request.user.is_authenticated():\n return HttpResponseRedirect('/')\n else:\n ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002275155_django_python.txt
Q: How do I url unencode in Python? Given this: It%27s%20me%21 Unencode it and turn it into regular text? A: in python2 >>> import urlparse >>> urlparse.unquote('It%27s%20me%21') "It's me!" In python3 >>> import urllib.parse >>> urllib.parse.unquote('It%27s%20me%21') "It's me!" A: Take a look at urllib.unquote a...
How do I url unencode in Python?
Given this: It%27s%20me%21 Unencode it and turn it into regular text?
[ "in python2\n>>> import urlparse\n>>> urlparse.unquote('It%27s%20me%21')\n\"It's me!\"\n\nIn python3\n>>> import urllib.parse\n>>> urllib.parse.unquote('It%27s%20me%21')\n\"It's me!\"\n\n", "Take a look at urllib.unquote and urllib.unquote_plus. That will address your problem. Technically though url \"encoding\...
[ 21, 11, 4 ]
[]
[]
[ "encoding", "python", "url" ]
stackoverflow_0002277302_encoding_python_url.txt
Q: Deleting a file from Tkinter import * import socket, sys, os import tkMessageBox root = Tk() root.title("File Deleter v1.0") root.config(bg='black') root.resizable(0, 0) text = Text() text3 = Text() frame = Frame(root) frame.config(bg="black") frame.pack(pady=10, padx=5) frame1 = Frame(root) frame1.config(bg="...
Deleting a file
from Tkinter import * import socket, sys, os import tkMessageBox root = Tk() root.title("File Deleter v1.0") root.config(bg='black') root.resizable(0, 0) text = Text() text3 = Text() frame = Frame(root) frame.config(bg="black") frame.pack(pady=10, padx=5) frame1 = Frame(root) frame1.config(bg="black") frame1.pack(p...
[ "When I run this code on Linux and place a breakpoint in button1(), I see that the value of x includes a trailing newline character. That means the os.remove() call won't work, because the filename I typed in didn't actually contain a newline. If I remove the trailing newline, the code works.\n", "Perhaps x is no...
[ 3, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002277236_python_tkinter.txt
Q: how to login to multiple website accounts concurrently with Python I am using urllib2 and HTTPCookieProcessor to login to a website. I want to login to multiple accounts concurrently and store the cookies to be reused later. Can you recommend an approach or library to achieve this? A: How to achieve this really...
how to login to multiple website accounts concurrently with Python
I am using urllib2 and HTTPCookieProcessor to login to a website. I want to login to multiple accounts concurrently and store the cookies to be reused later. Can you recommend an approach or library to achieve this?
[ "How to achieve this really depends on you needs: what kind of login is it? Digest authentication? Is it a web form? Is JavaScript involved (you're pretty much screwed if this is the case)? A library like mechanize can help you a lot with such stuff: handling of forms, redirection, authentication, cookies... How...
[ 1, 1 ]
[]
[]
[ "authentication", "concurrency", "cookies", "python", "urllib2" ]
stackoverflow_0002270881_authentication_concurrency_cookies_python_urllib2.txt
Q: Inter-database communications in PostgreSQL I am using PostgreSQL 8.4. I really like the new unnest() and array_agg() features; it is about time they realize the dynamic processing potential of their Arrays! Anyway, I am working on web server back ends that uses long Arrays a lot. Their will be two successive proc...
Inter-database communications in PostgreSQL
I am using PostgreSQL 8.4. I really like the new unnest() and array_agg() features; it is about time they realize the dynamic processing potential of their Arrays! Anyway, I am working on web server back ends that uses long Arrays a lot. Their will be two successive processes which will each occur on a different physic...
[ "not sure I totally understand, but you've looked at notify/listen? http://www.postgresql.org/docs/8.1/static/sql-listen.html\n", "Sounds like you want dblink from contrib. This allows some inter-db postgres communication. The pg docs are great and should provide the needed examples.\n", "I am thinking either...
[ 1, 1, 0 ]
[]
[]
[ "arrays", "database_connection", "postgresql", "python" ]
stackoverflow_0002263132_arrays_database_connection_postgresql_python.txt
Q: Subscription web/desktop app [PYTHON] Firstly pardon me if i've yet again failed to title my question correctly. I am required to build an app to manage magazine subscriptions. The client wants to enter subscriber data and then receive alerts at pre-set intervals such as when the subscription of a subscriber is ab...
Subscription web/desktop app [PYTHON]
Firstly pardon me if i've yet again failed to title my question correctly. I am required to build an app to manage magazine subscriptions. The client wants to enter subscriber data and then receive alerts at pre-set intervals such as when the subscription of a subscriber is about to expire and also the option to view a...
[ "Payment gateway integration:\n\nHere is a detailed article about how to integrate the Authorize.net payment system into a Django project. Authorize.net is used by a few popular Django projects, including the Satchmo e-commerce store project.\ndjango-paypal is a pluggable Django app which lets you connect to PayPa...
[ 2, 0 ]
[]
[]
[ "django", "payment_gateway", "python", "sms" ]
stackoverflow_0002270556_django_payment_gateway_python_sms.txt
Q: How to get data in a histogram bin I want to get a list of the data contained in a histogram bin. I am using numpy, and Matplotlib. I know how to traverse the data and check the bin edges. However, I want to do this for a 2D histogram and the code to do this is rather ugly. Does numpy have any constructs to ma...
How to get data in a histogram bin
I want to get a list of the data contained in a histogram bin. I am using numpy, and Matplotlib. I know how to traverse the data and check the bin edges. However, I want to do this for a 2D histogram and the code to do this is rather ugly. Does numpy have any constructs to make this easier? For the 1D case, I can u...
[ "digitize, from core NumPy, will give you the index of the bin to which each value in your histogram belongs:\nimport numpy as NP\nA = NP.random.randint(0, 10, 100)\n\nbins = NP.array([0., 20., 40., 60., 80., 100.])\n\n# d is an index array holding the bin id for each point in A\nd = NP.digitize(A, bins) \n\n",...
[ 27, 6 ]
[]
[]
[ "histogram", "matplotlib", "numpy", "python" ]
stackoverflow_0002275924_histogram_matplotlib_numpy_python.txt
Q: Grouping related search keywords I have a log file containing search queries entered into my site's search engine. I'd like to "group" related search queries together for a report. I'm using Python for most of my webapp - so the solution can either be Python based or I can load the strings into Postgres if it is...
Grouping related search keywords
I have a log file containing search queries entered into my site's search engine. I'd like to "group" related search queries together for a report. I'm using Python for most of my webapp - so the solution can either be Python based or I can load the strings into Postgres if it is easier to do this with SQL. Example d...
[ "f = open('data.txt', 'r')\nraw = f.readlines()\n\n#generate set of all possible groupings\ngroups = set()\nfor lines in raw:\n data = lines.strip().split()\n for items in data:\n groups.add(items)\n\n#parse input into groups\nfor group in groups:\n print \"Group \\'%s\\':\" % group\n for line in...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "data_structures", "postgresql", "python" ]
stackoverflow_0002275901_algorithm_data_structures_postgresql_python.txt
Q: Wrapping a pure virtual method with arguments using Boost::Python I'm currently trying to expose a c++ Interface (pure virtual class) to Python using Boost::Python. The c++ interface is: Agent.hpp #include "Tab.hpp" class Agent { virtual void start(const Tab& t) = 0; virtual void stop() = 0; }; And, by re...
Wrapping a pure virtual method with arguments using Boost::Python
I'm currently trying to expose a c++ Interface (pure virtual class) to Python using Boost::Python. The c++ interface is: Agent.hpp #include "Tab.hpp" class Agent { virtual void start(const Tab& t) = 0; virtual void stop() = 0; }; And, by reading the "official" tutorial, I managed to write and build the next Py...
[ "The get_override functions returns an an object of type override which has a number of overloads for differing number of arguments. So you should be able to just do this:\nvoid start(const Tab& t)\n{\n this->get_override(\"start\")(t);\n}\n\nDid you try this?\n" ]
[ 4 ]
[]
[]
[ "boost_python", "c++", "interface", "python", "word_wrap" ]
stackoverflow_0002277018_boost_python_c++_interface_python_word_wrap.txt
Q: What exactly is meant when mr.developer says "The package 'django-quoteme' is dirty." I'm using mr.developer to track some packages on github. When I rerun my buildout, I get: The package 'django-quoteme' is dirty. Do you want to update it anyway? [yes/No/all] y What is meant by "dirty" exactly? A: From http://g...
What exactly is meant when mr.developer says "The package 'django-quoteme' is dirty."
I'm using mr.developer to track some packages on github. When I rerun my buildout, I get: The package 'django-quoteme' is dirty. Do you want to update it anyway? [yes/No/all] y What is meant by "dirty" exactly?
[ "From http://github.com/fschulze/mr.developer:\n\nDirty SVN\nYou get an error like::\nERROR: Can't switch package 'foo'\n from\n 'https://example.com/svn/foo/trunk/',\n because it's dirty.\nIf you have not modified the package\n files under src/foo, then you can\n check what's going on with status\n -v. One c...
[ 5, 4 ]
[]
[]
[ "buildout", "django", "python" ]
stackoverflow_0002277926_buildout_django_python.txt
Q: detecting end of tty output Hi I'm writing a psudo-terminal that can live in a tty and spawn a second tty which is filters input and output from I'm writing it in python for now, spawning the second tty and reading and writing is easy but when I read, the read does not end, it waits for more input. import subproce...
detecting end of tty output
Hi I'm writing a psudo-terminal that can live in a tty and spawn a second tty which is filters input and output from I'm writing it in python for now, spawning the second tty and reading and writing is easy but when I read, the read does not end, it waits for more input. import subprocess pfd = subprocess.Popen(['/bin...
[ "Well, your output actually hasn't completed. Because you spawned /bin/sh, the shell is still running after \"ls\" completes. There is no EOF indicator, because it's still running.\nWhy not simply run /bin/ls?\nYou could do something like\npfd = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stdin=subprocess.PIPE...
[ 1, 0 ]
[]
[]
[ "control_characters", "python", "tty" ]
stackoverflow_0002278150_control_characters_python_tty.txt
Q: merging dictionaries in python Sorry for the very general title but I'll try to be as specific as possible. I am working on a text mining application. I have a large number of key value pairs of the form ((word, corpus) -> occurence_count) (everything is an integer) which I am storing in multiple python dictionar...
merging dictionaries in python
Sorry for the very general title but I'll try to be as specific as possible. I am working on a text mining application. I have a large number of key value pairs of the form ((word, corpus) -> occurence_count) (everything is an integer) which I am storing in multiple python dictionaries (tuple->int). These values are s...
[ "A disk-based dictionary-like exists -- see the shelve module. Keys into a shelf must be strings, but you could simply use str on your tuples to obtain equivalent string keys; plus, I read your Q as meaning that you want only word as the key, so that's even easier (either str -- or, for vocabularies < 4GB, a struc...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "merge", "python" ]
stackoverflow_0002277895_dictionary_merge_python.txt
Q: Getting UTC offset for a datetime I have tried this but its not correct: In [34]: e_now Out[34]: datetime.datetime(2010, 2, 17, 0, 2, 40, 506444, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>) In [35]: e_now.utcoffset() Out[35]: datetime.timedelta(-1, 68400) A: The tzinfo is identified as EST-1 day, 1...
Getting UTC offset for a datetime
I have tried this but its not correct: In [34]: e_now Out[34]: datetime.datetime(2010, 2, 17, 0, 2, 40, 506444, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>) In [35]: e_now.utcoffset() Out[35]: datetime.timedelta(-1, 68400)
[ "The tzinfo is identified as EST-1 day, 19:00:00 -- and the timedelta is given as -1 day, 68400 seconds (i.e., 19 hours, just as in the tzinfo identification). All timezones east of the London-Paris meridian will have -1 day and a positive number of seconds: for example, when it's a second past midnight in London ...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002278477_datetime_python.txt
Q: How can I end a string randomly and concatenate another string at the end in Python? Basicaly I have a user inputted string like: "hi my name is bob" what I would like to do is have my program randomly pick a new ending of the string and end it with my specified ending. For example: "hi my name DUR." "hi mDUR." e...
How can I end a string randomly and concatenate another string at the end in Python?
Basicaly I have a user inputted string like: "hi my name is bob" what I would like to do is have my program randomly pick a new ending of the string and end it with my specified ending. For example: "hi my name DUR." "hi mDUR." etc etc I'm kinda new to python so hopefully there's an easy solution to this hehe
[ "Something like this: \nimport random\n\ns = \"hi my name is bob\"\nr = random.randint(0, len(s))\nprint s[:r] + \"DUR\"\n\nString concatentation is accomplished with +. The [a:b] notation is called a slice. s[:r] returns the first r characters of s. \n", "s[:random.randrange(len(s))] + \"DUR\"\n\n", "Not sure ...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "concatenation", "python", "string" ]
stackoverflow_0002278585_concatenation_python_string.txt
Q: How to graphically edit the graph of a mathematical function (with python)? Is there already a python package allowing to graphically edit the graph of a function? A: Chaco is designed to be very interactive, and is significantly more so than matplotlib. For example, the user can use the mouse to drag the legen...
How to graphically edit the graph of a mathematical function (with python)?
Is there already a python package allowing to graphically edit the graph of a function?
[ "Chaco is designed to be very interactive, and is significantly more so than matplotlib. For example, the user can use the mouse to drag the legend to different places on a plot, or lasso data, or move a point around on one plot and change the results in another, or change the color of a plot by clicking on a swat...
[ 2 ]
[]
[]
[ "math", "numpy", "python", "user_interface" ]
stackoverflow_0002275845_math_numpy_python_user_interface.txt
Q: what is the usefulness of '>' in python print 'xxx' > 'ssaww' it print 'true' who can give me a clear example . thanks A: Just like in math, > compares two operands and returns True if the left operand is greater than the right, otherwise False. A: In python strings are ordered lexicographically. A: you ca...
what is the usefulness of '>' in python
print 'xxx' > 'ssaww' it print 'true' who can give me a clear example . thanks
[ "Just like in math, > compares two operands and returns True if the left operand is greater than the right, otherwise False.\n", "In python strings are ordered lexicographically.\n", "you can test it out on the interpreter\n>>> 'xxx'>'yyy' #first character 'x' is less than first character 'y', so false\nFalse\...
[ 5, 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002278901_python.txt
Q: What would I use Stackless Python for? There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython? Yes it has green th...
What would I use Stackless Python for?
There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython? Yes it has green threads (stackless) that allow quickly create ...
[ "It allows you to work with massive amounts of concurrency. Nobody sane would create one hundred thousand system threads, but you can do this using stackless.\nThis article tests doing just that, creating one hundred thousand tasklets in both Python and Google Go (a new programming language): http://dalkescientific...
[ 32, 12, 9, 6, 6, 5 ]
[]
[]
[ "python", "python_stackless" ]
stackoverflow_0002220645_python_python_stackless.txt