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: Pyunit setUpClass not running Based on the documentation for PyUnit, I would expect the following code to run the test test_simple after calling setUpClass. However it doesn't seem to do that, I put a print statement inside setUpClass to verify this. import unittest class TestData(unittest.TestCase): def tes...
Pyunit setUpClass not running
Based on the documentation for PyUnit, I would expect the following code to run the test test_simple after calling setUpClass. However it doesn't seem to do that, I put a print statement inside setUpClass to verify this. import unittest class TestData(unittest.TestCase): def test_simple(self): pass @...
[ "It works for me. The documentation also mentions this was only added in Python 2.7 (3.2 for the 3.x releases). Do you have Python 2.7/3.2?\n" ]
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005385229_python_unit_testing.txt
Q: Populating model properties dynamically from a javascript call Problem Description: 1] I have a model with country and city properties class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty(default='Afghanistan',c...
Populating model properties dynamically from a javascript call
Problem Description: 1] I have a model with country and city properties class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty(default='Afghanistan',choices=['Afghanistan','Aring land Islands','Albania']) #city...
[ "Assuming your IDs for those two inputs are country and city:\ndocument.getElementById(\"country\").value = geoip_country_name()\ndocument.getElementById(\"city\").value = geoip_city()\n\n", "I wrote the following python class to find the country and city for the user. \nThis is working, if someone finds any issu...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0005371644_google_app_engine_javascript_python.txt
Q: PHP equivalent to Python's struct I am trying to port the following Python code to PHP, but I can't find the PHP equivalent to Python's struct. (and I specifically need an equivalent to struct.calcsize()) Is there any PHP equivalent that I could use? import struct attr_fmt = ">iii4x" attr_size = struct.calcsize(se...
PHP equivalent to Python's struct
I am trying to port the following Python code to PHP, but I can't find the PHP equivalent to Python's struct. (and I specifically need an equivalent to struct.calcsize()) Is there any PHP equivalent that I could use? import struct attr_fmt = ">iii4x" attr_size = struct.calcsize(self.attr_fmt) EDIT: For those that are ...
[ "I'm not familiar with Python's struct, but it looks a bit like PHP's pack and unpack. I'm not aware of any direct way to determine the size before hand.\nHere's an example that I believe is the same as yours:\n$fmt = 'N3x4'; // three 32-bit big endian integers followed by 4 bytes of padding\n$s = pack($fmt, 0, 0, ...
[ 4 ]
[]
[]
[ "php", "python", "struct" ]
stackoverflow_0005385518_php_python_struct.txt
Q: Django Twitter OAuth authentication I'm trying to implement a Twitter authentication via OAuth on my Django application, but I'm stuck at this error after receiving the Twitter callback: Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 100. res...
Django Twitter OAuth authentication
I'm trying to implement a Twitter authentication via OAuth on my Django application, but I'm stuck at this error after receiving the Twitter callback: Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args,...
[ "I had this same issue. Seems that the libs used by oauthtwitter have changed. To patch your local version do the following:\nin:\n/usr/local/lib/python2.6/dist-packages/oauth_python_twitter-1.0-py2.6.egg/oauthtwitter.py\n\nfind line 37 and change it from:\nApi.__init__(self, access_token.key, access_token.secret)\...
[ 1, 0 ]
[]
[]
[ "django", "oauth", "python", "twitter" ]
stackoverflow_0004714624_django_oauth_python_twitter.txt
Q: Python Function with "Pointers" Ok, I recently started programming in Python, and I really like it. However, I have run into a little issue. I want to be able to define a function to take in some data and assign it to a variable that I designate, rather than have to perform the operation every time I want to submi...
Python Function with "Pointers"
Ok, I recently started programming in Python, and I really like it. However, I have run into a little issue. I want to be able to define a function to take in some data and assign it to a variable that I designate, rather than have to perform the operation every time I want to submit the value. Here is a code fragment:...
[ "Have you tried/looked into the getattr and setattr functions?\nFor example, assuming these \"variables\" are object attributes:\ndef checkval(self, attr, presence, tagstr):\n tag = getattr(presence, tagstr, None) # tag = presence.\"tagstr\" or None\n setattr(self, attr, tag or 'tag not found') ...
[ 1 ]
[]
[]
[ "function", "lxml", "pointers", "python", "xml" ]
stackoverflow_0005385509_function_lxml_pointers_python_xml.txt
Q: Consuming RSS in Django ( / Python) For a site I'm working on I would like to import a lot of RSS feeds using Django. Since I need the content of them fast I will need to cache them locally (either in the database or in some other way) Is there a standard app to do RSS consumption in Django, or is there a standard...
Consuming RSS in Django ( / Python)
For a site I'm working on I would like to import a lot of RSS feeds using Django. Since I need the content of them fast I will need to cache them locally (either in the database or in some other way) Is there a standard app to do RSS consumption in Django, or is there a standard way to do this in Python? Of course I co...
[ "Check outhttp://feedparser.org/docs/ http://code.google.com/p/feedparser/\nOne of the best Python libraries for parsing RSS and Atom Feeds; although it seems like you want to do a bit more (caching, auto-refresh etc.)\n" ]
[ 8 ]
[]
[]
[ "django", "python", "rss" ]
stackoverflow_0005385565_django_python_rss.txt
Q: Python urllib2.Request.get_header documentation? I'm working on a library that involves pre-processing of urllib2.Request instances (using the urllib2.BaseHandler.xxx_request callbacks). Some of the pre-processors need to examine the headers contained in the supplied urllib2.Request instance. I noticed the officia...
Python urllib2.Request.get_header documentation?
I'm working on a library that involves pre-processing of urllib2.Request instances (using the urllib2.BaseHandler.xxx_request callbacks). Some of the pre-processors need to examine the headers contained in the supplied urllib2.Request instance. I noticed the official Python documentation only lists methods for adding a...
[ "I'm sure get_header is officially supported, but I can't find it mentioned in the documentation.\nAs to your \"get_header returning None\" problem, looking at the source to urllib2.py, the add_header method is calling key.capitalize() before saving the header key-value pair, which is why get_header('Content-type')...
[ 4 ]
[]
[]
[ "http_headers", "python", "urllib2" ]
stackoverflow_0005385056_http_headers_python_urllib2.txt
Q: What's the difference between these two ways of implementing `on duplication increment`? Assume that I have a table user_count defined as follows: id primary key, auto increment user_id unique count default 0 What I want to do is increment count by one when an existing record of a user...
What's the difference between these two ways of implementing `on duplication increment`?
Assume that I have a table user_count defined as follows: id primary key, auto increment user_id unique count default 0 What I want to do is increment count by one when an existing record of a user exists or else insert a new record. Currently, I do it this way (in Python): try: cu...
[ "The first one uses an exception to direct the flow of the program, which isn't what you should do unless you have no other solutions to it (e.g. getting exclusive access to a file). Also, it takes the work from the database which should know better to handle the case.\nThe second code handles all the work in the d...
[ 1, 1 ]
[]
[]
[ "database", "mysql", "python", "sql" ]
stackoverflow_0005385718_database_mysql_python_sql.txt
Q: Python mechanize SelectControl is empty when it should have values I'm trying to automate the download of some data from a webform. I'm using python's mechanize module. The url is here: http://www.hiv.lanl.gov/components/sequence/HIV/search/search.html I need to fill out the Sequence Length, Subtype and Genomic Re...
Python mechanize SelectControl is empty when it should have values
I'm trying to automate the download of some data from a webform. I'm using python's mechanize module. The url is here: http://www.hiv.lanl.gov/components/sequence/HIV/search/search.html I need to fill out the Sequence Length, Subtype and Genomic Region. I've got the Sequence-Length and Genomic-Region figured out but I'...
[ "The problem is that the Subtype <select> options are populated by Javascript, which mechanize does not execute. The Javascript code runs when the page loads, populating the slave options with the HIV-1 list:\naddLoadEvent(fillList(document.forms['search'].slave, lists['HIV-1']));\n\nHowever, the mapping of Virus -...
[ 1 ]
[]
[]
[ "html_parsing", "mechanize", "python" ]
stackoverflow_0005383933_html_parsing_mechanize_python.txt
Q: Python httplib2.Http not sending post parameters I have been trying to make an API request to Twilio using the httplib2 Http class and no matter how I try to setup the request, it doesn't send my post DATA. I know this, because I posted to a local URL and the post arguments are empty. Here is my code: _TWILIO_URL ...
Python httplib2.Http not sending post parameters
I have been trying to make an API request to Twilio using the httplib2 Http class and no matter how I try to setup the request, it doesn't send my post DATA. I know this, because I posted to a local URL and the post arguments are empty. Here is my code: _TWILIO_URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/%s' c...
[ "Twilio mentions this requirement in their API docs concerning POST requests:\n\nBut be sure to set the HTTP\n Content-Type header to\n \"application/x-www-form-urlencoded\"\n for your requests if you are\n writing your own client.\n\n", "It turns out that the 'content-type' has to be set to 'application/...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005385699_python.txt
Q: Proper Accessor for Django Uploaded Files Assuming a Django form like the following... class MyForm(forms.Form): attachment = forms.FileField() I've seen many tutorials which access uploaded Django files with request.FILES['attachment'], however I was under the impression that whenever possible you should acc...
Proper Accessor for Django Uploaded Files
Assuming a Django form like the following... class MyForm(forms.Form): attachment = forms.FileField() I've seen many tutorials which access uploaded Django files with request.FILES['attachment'], however I was under the impression that whenever possible you should access POSTed data via form.cleaned_data['attachme...
[ "When you create a form in HTML, it has a particular encoding (or method of sending the data to the server). By default, the encoding is application/x-www-form-urlencoded, which essentially sends the form details in a single string. However, if you want to upload files to the server, you need to set the encoding to...
[ 7 ]
[]
[]
[ "django", "django_forms", "http_post", "python" ]
stackoverflow_0005384883_django_django_forms_http_post_python.txt
Q: Plot functions in Python I am required to use Python for engineering project. Need to create many graphs, including surface plots. In the past I used Matlab for plotting and really liked it. I was wandering if there is a module/package/extension which bring similar capability into Python. To be more specific, I n...
Plot functions in Python
I am required to use Python for engineering project. Need to create many graphs, including surface plots. In the past I used Matlab for plotting and really liked it. I was wandering if there is a module/package/extension which bring similar capability into Python. To be more specific, I need piloting for 2 different r...
[ "Try matplotlib, it's pretty extensive and has a shell similar to MATLAB / Mathematica.\n", "I suspect matplotlib.pyplot would be right up your alley.\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005385801_python.txt
Q: nodebox grid() vs. grid library In Nodebox you can have: grid() as a command grid as a library If I follow this tutorial: http://nodebox.net/code/index.php/Grid It says to import grid with this: grid = ximport("grid") But in nodebox this is a command, which is why I believe things dont work as they should. Is th...
nodebox grid() vs. grid library
In Nodebox you can have: grid() as a command grid as a library If I follow this tutorial: http://nodebox.net/code/index.php/Grid It says to import grid with this: grid = ximport("grid") But in nodebox this is a command, which is why I believe things dont work as they should. Is that correct? If not how do I import th...
[ "That is correct. When you import the grid library, grid = ximport(\"grid\"), you can no longer use the built-in grid function. However, the functionality of the grid library is a superset of the grid built-in. That is, you can do everything and more with the library that you could with the function. The function i...
[ 0 ]
[]
[]
[ "nodebox", "python" ]
stackoverflow_0004985257_nodebox_python.txt
Q: Define variables with the same list data but different objects using python this is my code : attackUp = [10, 15,10, 15,10, 15] defenceUp = [10, 15,10, 15,10, 15] magicUp = [10, 15,10, 15,10, 15] attType = [1,1,1,1,1,1] weightDown = [10, 15,10, 15,10, 15] #装饰器数据 accAttackSword = [100, 100,100, 100,100, 100] accAt...
Define variables with the same list data but different objects using python
this is my code : attackUp = [10, 15,10, 15,10, 15] defenceUp = [10, 15,10, 15,10, 15] magicUp = [10, 15,10, 15,10, 15] attType = [1,1,1,1,1,1] weightDown = [10, 15,10, 15,10, 15] #装饰器数据 accAttackSword = [100, 100,100, 100,100, 100] accAttackSaber = [100, 100,100, 100,100, 100] accAttackAx = [100, 100,100, 100,100, 10...
[ "Well, a step in the right direction would be to create a base list and then copy it using slice notation:\nbase = [100, 100, 100, 100]\nvalue_a = base[:]\nvalue_b = base[:]\n\nand so on. This doesn't gain you much for the shorter lists, but it should be useful for the longer ones at least. \nBut I think more gener...
[ 5, 1, 1, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005385815_python_variables.txt
Q: How to show math equations in QTextEdit? Does anyone know how to show mathematical equations in QTextEdit written in any format (TXT, MathML, MML, LaTeX, HTML, XML or anything) using only Python, that is without using 3rd party packages like Latex itself.? I tried to find the MathML Widget from Qt but it disappear...
How to show math equations in QTextEdit?
Does anyone know how to show mathematical equations in QTextEdit written in any format (TXT, MathML, MML, LaTeX, HTML, XML or anything) using only Python, that is without using 3rd party packages like Latex itself.? I tried to find the MathML Widget from Qt but it disappeared from their web site and I couldn't find it ...
[ "You can use this: http://qwt.sourceforge.net/\nIt definitely seems funny that I cannot find the MathML widget in Qt.\nEDIT: I think they are trying to replace it with webkit support, but it isn't implemented yet: http://developer.qt.nokia.com/wiki/Qt_Webkit_HTML5_Score\n" ]
[ 0 ]
[]
[]
[ "equations", "math", "python" ]
stackoverflow_0005385740_equations_math_python.txt
Q: How should this Python function be called I am having a trouble correctly referencing a recently added fpath() function. The code takes an argument from the commandline in the form of a file, wildcard or folder for use in the last code block. #! /usr/bin/env python import os, sys, glob from optparse import Option...
How should this Python function be called
I am having a trouble correctly referencing a recently added fpath() function. The code takes an argument from the commandline in the form of a file, wildcard or folder for use in the last code block. #! /usr/bin/env python import os, sys, glob from optparse import OptionParser #logic to determine if argument is a fi...
[ "The following code pattern has some issues:\nall_files = ''\ndef fpath(arguments):\n all_files = []\n # modify all_files\n return all_files \n\nIt looks like you want to pass back the content of all_files to the caller. There are two general ways to do this, with a global variable and with a return value:...
[ 2 ]
[]
[]
[ "function", "modularity", "python", "scripting" ]
stackoverflow_0005385959_function_modularity_python_scripting.txt
Q: django content types - how to get model class of content type to create a instance? I dont know if im clear with the title quiestion, what I want to do is the next case: >>> from django.contrib.contenttypes.models import ContentType >>> ct = ContentType.objects.get(model='user') >>> ct.model_class() <class 'django...
django content types - how to get model class of content type to create a instance?
I dont know if im clear with the title quiestion, what I want to do is the next case: >>> from django.contrib.contenttypes.models import ContentType >>> ct = ContentType.objects.get(model='user') >>> ct.model_class() <class 'django.contrib.auth.models.User'> >>> ct_class = ct.model_class() >>> ct_class.username = 'hell...
[ "You need to create an instance of the class. ct.model_class() returns the class, not an instance of it. Try the following:\n>>> from django.contrib.contenttypes.models import ContentType\n>>> ct = ContentType.objects.get(model='user')\n>>> ct_class = ct.model_class()\n>>> ct_instance = ct_class()\n>>> ct_instance....
[ 54, 8 ]
[]
[]
[ "django", "django_contenttypes", "python" ]
stackoverflow_0005386104_django_django_contenttypes_python.txt
Q: best way to create this dict in python this is my code : vars_ = { 'attackUp':attackUp,'defenceUp':defenceUp,'magicUp':magicUp,'attType':attType,'weightDown':weightDown, 'accAttackSword':accAttackSword,'accAttackSaber':accAttackSaber,'accAttackAx':accAttackAx, 'accAt...
best way to create this dict in python
this is my code : vars_ = { 'attackUp':attackUp,'defenceUp':defenceUp,'magicUp':magicUp,'attType':attType,'weightDown':weightDown, 'accAttackSword':accAttackSword,'accAttackSaber':accAttackSaber,'accAttackAx':accAttackAx, 'accAttackHammer':accAttackHammer,'accAttackSpear'...
[ "I would stop and consider why you are doing this. I can't help but think its not necessary. \nEven if you decide this is necessary (which i doubt) - You are pretty much recreating globals(). Type that into your interpretter and see if you still want to do this. \nOrganize it further like senderle suggested in your...
[ 3, 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005386003_dictionary_python.txt
Q: OK so i dont get how to make this professor class call on this lecturer class So i have this code i'm trying to work through first is this class Lecturer (Person): def lecture (self, stuff): self.say(stuff + "- you should be taking notes") then i'm trying to make a class called professor which calls ...
OK so i dont get how to make this professor class call on this lecturer class
So i have this code i'm trying to work through first is this class Lecturer (Person): def lecture (self, stuff): self.say(stuff + "- you should be taking notes") then i'm trying to make a class called professor which calls on this lecture def i made code like this class Professor (Person): def profes...
[ "Then Professor should either 'be a' Lecturer or 'have a' Lecturer.\nclass Person(object):\n def say(self, stuff):\n return stuff\n\nclass Lecturer(Person):\n def lecture(self, stuff):\n return self.say(str(stuff) + \" - you should be taking notes\")\n\nclass Professor1(Lecturer): # 'is a' Lect...
[ 5, 3 ]
[]
[]
[ "class", "python", "subclass" ]
stackoverflow_0005386092_class_python_subclass.txt
Q: Simulating lack of a dependency when testing a python script What's the best way to temporarily hide an installed module from a python script to test how it handles environments that don't have the module installed? I'd like to avoid having to uninstall the module just to test. A: import sys sys.modules['numpy']...
Simulating lack of a dependency when testing a python script
What's the best way to temporarily hide an installed module from a python script to test how it handles environments that don't have the module installed? I'd like to avoid having to uninstall the module just to test.
[ "import sys\nsys.modules['numpy']=None\n\nSetting sys.modules['numpy']=None makes Python think that it has already tried and failed to import numpy. Subsequent attempts at importing numpy now raise ImportError:\ntry:\n import numpy\nexcept ImportError as err:\n print(err)\n # No module named numpy\n\nDelet...
[ 6, 3 ]
[]
[]
[ "dependencies", "import", "module", "python", "testing" ]
stackoverflow_0005386194_dependencies_import_module_python_testing.txt
Q: How do I save web images to App Engine's blobstore? I've used this question as a template to solve the same problem, but I'm running into issues when posting. I have these components: HTML form with a textbox for the image URL. This posts to... A handler that takes the posted URL, encodes it, and uses urlfetch t...
How do I save web images to App Engine's blobstore?
I've used this question as a template to solve the same problem, but I'm running into issues when posting. I have these components: HTML form with a textbox for the image URL. This posts to... A handler that takes the posted URL, encodes it, and uses urlfetch to post it again to... A separate file upload handler tha...
[ "You can achieve the same without using blobstore api. I think you have to just get the url and get the content using urlfetch().content method and store it as a blob property.\nurl = \"imageurl\"\nresult = urlfetch.fetch(url)\nif result.status_code == 200:\n prof.avatar = db.Blob(result.content)\n\nFor further r...
[ 3, 3 ]
[]
[]
[ "blobstore", "google_app_engine", "image", "python", "tipfy" ]
stackoverflow_0005370113_blobstore_google_app_engine_image_python_tipfy.txt
Q: Dynamically populating values in djangoform Problem details: 1] I have a model that looks like follows class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty( choices=['Afghanistan','Aring land']) #city se...
Dynamically populating values in djangoform
Problem details: 1] I have a model that looks like follows class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty( choices=['Afghanistan','Aring land']) #city selected by the user city = db.StringProperty()...
[ "You would normally do this by overriding __init__\nfrom django.forms import ModelForm, ChoiceField\nclass MyModelForm(ModelForm):\n class Meta:\n model = MyModel\n\n def __init__(self, *args, **kwargs):\n super(MyModelForm, self).__init__(*args, **kwargs)\n geoiplocator_instance = GeoIpL...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0005385601_django_django_forms_google_app_engine_python.txt
Q: Getting display after form post submission in Google App Engine in Python Content of page not displayed after a form post, but displayed when directly viewing the page. I have a Python App Engine piece of code that is attempting to direct to a new page and display a programatically defined (i.e. in the code, not h...
Getting display after form post submission in Google App Engine in Python
Content of page not displayed after a form post, but displayed when directly viewing the page. I have a Python App Engine piece of code that is attempting to direct to a new page and display a programatically defined (i.e. in the code, not html) piece of text. However up pressing the submit button of the form I get a b...
[ "Your code runs pretty smoothly; probably you have not implemented correctly the post method for some weird indentation error (this would explain the 405 error).\nCopy and paste my application.py and try again:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\ncl...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005377758_google_app_engine_python.txt
Q: Refactoring a python function so that it can take any sized list How can I make this function take as input an arbitrary list size? def ugly_function(lst): for a in lst[0]: for b in lst[1]: for c in lst[2]: for d in lst[3]: for e in lst[4]: ...
Refactoring a python function so that it can take any sized list
How can I make this function take as input an arbitrary list size? def ugly_function(lst): for a in lst[0]: for b in lst[1]: for c in lst[2]: for d in lst[3]: for e in lst[4]: for f in lst[5]: for g in lst[6]...
[ "Check out itertools.\ndef ugly_function(lst):\n for comb in itertools.product(*lst):\n if some_test(comb):\n return comb\n\n(Or, as a 1-liner:\ndef ugly_function(lst):\n return next(comb for comb in itertools.product(*lst) if some_test(comb))\n\n", "from itertools import ifilter, product\n\nde...
[ 4, 2 ]
[]
[]
[ "python", "refactoring" ]
stackoverflow_0005386789_python_refactoring.txt
Q: Porting optimized Sieve of Eratosthenes from Python to C++ Some time ago I used the (blazing fast) primesieve in python that I found here: Fastest way to list all primes below N To be precise, this implementation: def primes2(n): """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n-n%...
Porting optimized Sieve of Eratosthenes from Python to C++
Some time ago I used the (blazing fast) primesieve in python that I found here: Fastest way to list all primes below N To be precise, this implementation: def primes2(n): """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n-n%6+6, 2-(n%6>1) sieve = [True] * (n/3) for i in xrange(1,...
[ "I'll try to explain as much as I can. The sieve array has an unusual indexing scheme; it stores a bit for each number that is congruent to 1 or 5 mod 6. Thus, a number 6*k + 1 will be stored in position 2*k and k*6 + 5 will be stored in position 2*k + 1. The 3*i+1|1 operation is the inverse of that: it takes nu...
[ 3, 1, 0 ]
[]
[]
[ "c++", "python", "sieve_of_eratosthenes" ]
stackoverflow_0005293238_c++_python_sieve_of_eratosthenes.txt
Q: is there an "if in" operator in PHP? i was looking to something that checks whether a string exists inside another, as in python: print "a" in "aloha" wold return 1 A: strpos() $pos = strpos("aloha", "a"); EDIT You can verify the existence of string by putting IF like this:- if (strpos("aloha", "a") !== false...
is there an "if in" operator in PHP?
i was looking to something that checks whether a string exists inside another, as in python: print "a" in "aloha" wold return 1
[ "strpos()\n$pos = strpos(\"aloha\", \"a\");\n\nEDIT\nYou can verify the existence of string by putting IF like this:-\nif (strpos(\"aloha\", \"a\") !== false) {\n echo \"The string was found\";\n\n} else {\n echo \"The string was not found\";\n}\n\n", "strpos(\"aloha\", \"a\") !== false\n\nReturns true is...
[ 3, 2, 1, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005387293_php_python.txt
Q: Remove tabs from within lists of a list I have 10 lists with four elements each seperated by tabs within a large list. How do I remove the tabs, have the elements seperated within their respective lists, all within in a large list? A: Courtesy of this question. This may work. >>> tabbedlist = 'element0\telement...
Remove tabs from within lists of a list
I have 10 lists with four elements each seperated by tabs within a large list. How do I remove the tabs, have the elements seperated within their respective lists, all within in a large list?
[ "Courtesy of this question. This may work.\n>>> tabbedlist = 'element0\\telement1\\telement2\\telement3'\n>>> list = tabbedlist.split('\\t')\n>>> list\n['element0', 'element1', 'element2', 'element3']\n\nThis appears to also work for: tabbedlist = 'element0 element1 element2 element3' Where those...
[ 2, 1, 1, 0 ]
[]
[]
[ "for_loop", "list", "loops", "python" ]
stackoverflow_0005387436_for_loop_list_loops_python.txt
Q: Apple Python launcher is acting on command key bindings I've written a Python utility that uses tkinter. I'm running it on a Macintosh. When it is executed, it runs within an apple-supplied Python launcher program (/Library/Frameworks/Python.framework/Versions/3.2/Resources/Python.app). My code installs its own m...
Apple Python launcher is acting on command key bindings
I've written a Python utility that uses tkinter. I'm running it on a Macintosh. When it is executed, it runs within an apple-supplied Python launcher program (/Library/Frameworks/Python.framework/Versions/3.2/Resources/Python.app). My code installs its own menus and I bind to the usual Macintosh command-key equivalent...
[ "Instead of overriding Tkinter's default key bindings, consider re-mapping Tcl's \"exit\" command to a custom function. (This is called every time you hit command-q or use the \"quit\" menu item.)\ndef save_and_exit():\n save_changed_files()\n sys.exit()\n\nself.createcommand('exit', save_and_exit)\n\nBesides...
[ 2, 0, 0 ]
[]
[]
[ "macos", "python", "tkinter" ]
stackoverflow_0005372869_macos_python_tkinter.txt
Q: Django pagination error I have created a Django application. There is a filtering functionality in my application. The filtered data is shown in a separate page. Now I want to give Django Pagination to the filtered list page. While doing it, I came into this error. The pagination is shown at the bottom of the page...
Django pagination error
I have created a Django application. There is a filtering functionality in my application. The filtered data is shown in a separate page. Now I want to give Django Pagination to the filtered list page. While doing it, I came into this error. The pagination is shown at the bottom of the page with showing the correct num...
[ "It sounds like you've already correctly identified the reason that the next link is redirecting to the home page:\n\nThe next link will be something like ?page=2\nThere is no choices GET variable and there are no POST variables, so val2 will be '' when it enters your long if elif statement.\nelse: return HttpRespo...
[ 2, 2 ]
[]
[]
[ "django", "django_models", "django_pagination", "django_templates", "python" ]
stackoverflow_0005387012_django_django_models_django_pagination_django_templates_python.txt
Q: Making a subclass in Python which overrides superclass method So I'm trying to make a class called Dean and this class has to be able to call upon the super class of say (just printing out a text). I was told to use Professor.say(self, stuff) to call upon the superclass of say but I don't really get that. My code...
Making a subclass in Python which overrides superclass method
So I'm trying to make a class called Dean and this class has to be able to call upon the super class of say (just printing out a text). I was told to use Professor.say(self, stuff) to call upon the superclass of say but I don't really get that. My code is as follows: Class Dean(Professor): Professor.say(self, st...
[ "Let me try to rephrase what you have said using the correct terms. You want this subclass of Professor, called Dean, to have a method that overrides a method in its superclass; the method's name is say. The Dean's method should call the superclass's version of the method.\nThe answer is: you define the overridden ...
[ 4 ]
[]
[]
[ "class", "python", "subclass" ]
stackoverflow_0005387348_class_python_subclass.txt
Q: Initialization of data attributes I have a class like this class SomeClass: def doSomething(self): self.counter = 50 I create an instance x for SomeClass x = SomeClass() When I try to get the value of counter like this: x.counter I get the following error - Traceback (most recent call last): File "...
Initialization of data attributes
I have a class like this class SomeClass: def doSomething(self): self.counter = 50 I create an instance x for SomeClass x = SomeClass() When I try to get the value of counter like this: x.counter I get the following error - Traceback (most recent call last): File "<stdin>", line 1, in <module> Attribute...
[ "No, self.counter is created only then doSomething() is called. In Python, instance attributes are dynamic and can be created at runtime. To have self.counter available from the creation of the object, put its initialization in a constructor:\nclass SomeClass:\n def __init__(self):\n self.counter = None\n...
[ 7 ]
[]
[]
[ "attributes", "class", "function", "member", "python" ]
stackoverflow_0005388410_attributes_class_function_member_python.txt
Q: SQL fiscal dates, flat files, misery Using sqlite3, python I have a crappy legacy file legacy_sales: item | year | week | mon | tue | wed | thu | fri | sat |sun 4444 2011 29 10 0 4 15 18 25 30 And I have an awesome new file sales (this is an example of the 'mon' entry from above): it...
SQL fiscal dates, flat files, misery
Using sqlite3, python I have a crappy legacy file legacy_sales: item | year | week | mon | tue | wed | thu | fri | sat |sun 4444 2011 29 10 0 4 15 18 25 30 And I have an awesome new file sales (this is an example of the 'mon' entry from above): item | units | date 4444 10 2011...
[ "insert into sales from (\n -- here be magic\n select item, units, DATEADD(day, DayInYear, start_date)\n from (\n select item,\n year,\n (week - 1) * 7 + 0 as DayInYear,\n mon as Units\n from legacy_sales\n union all\n select ...
[ 1, 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0005386631_python_sql_sqlite.txt
Q: Please help me understand a bit shift operation def different(s): x = len(s) for i in range(1, 1 << x): u.append([s[j] for j in range(x) if (i & (1 << j))]) It takes a list and makes different combinations (a,b,c) = ((a,b,c),(a,b),(a,c) ...) But what does the range do? From 1 to what. I don't unders...
Please help me understand a bit shift operation
def different(s): x = len(s) for i in range(1, 1 << x): u.append([s[j] for j in range(x) if (i & (1 << j))]) It takes a list and makes different combinations (a,b,c) = ((a,b,c),(a,b),(a,c) ...) But what does the range do? From 1 to what. I don't understand the "<<" and also, if (i & (1 << j)) what does ...
[ "<< is the binary left shift operator. 1 << x is a way of saying two to the power of x.\n", "The range function returns a list of numbers from zero to the given number minus one. It also has two- and three-argument forms (see the doc for more info):\nrange(n) == [0, 1, 2, ..., n - 1]\n\n<< is the left-shift opera...
[ 5, 5 ]
[]
[]
[ "bit_shift", "python" ]
stackoverflow_0005388639_bit_shift_python.txt
Q: Remove duplicate words using regex in Python I need to remove repetitive words in string so that 'the (the)' will become 'the'. Why can't I do it as follows? re.sub('(.+) \(\1\)', '\1', 'the (the)') Thanks. A: You need to doubly escape the back-reference: re.sub('(.+) \(\\1\)', '\\1', 'the (the)') --> the Or u...
Remove duplicate words using regex in Python
I need to remove repetitive words in string so that 'the (the)' will become 'the'. Why can't I do it as follows? re.sub('(.+) \(\1\)', '\1', 'the (the)') Thanks.
[ "You need to doubly escape the back-reference:\nre.sub('(.+) \\(\\\\1\\)', '\\\\1', 'the (the)')\n--> the\n\nOr use the r prefix:\n\nWhen an \"r\" or \"R\" prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.\n\nre.sub(r'(.+) \\(\...
[ 6, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005388726_python_regex.txt
Q: How to automatically remove certain preprocessors directives and comments from a C header-file? What's a good way to remove all text from a file which lies between /* */ and #if 0 and corresponding #endif? I want to strip these parts from C headers. This is the code I have so far: For line in file: if def0Enc...
How to automatically remove certain preprocessors directives and comments from a C header-file?
What's a good way to remove all text from a file which lies between /* */ and #if 0 and corresponding #endif? I want to strip these parts from C headers. This is the code I have so far: For line in file: if def0Encountered == 0: if Line.strip().startswith('#if 0') == True: Def0StartsAt = Li...
[ "Not sure what this strange code should be doing but it is straight forward to iterate over the file line-by-line. Use two flags to check if you are inside a comment or and if block. Toggle the the flags based on string comparisions. Based on the value of both flags you either output the current line or ignore it.....
[ 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005388620_python_string.txt
Q: generating non-html output from google's app engine I'm trying to dynamically generate iCal output using Max M's icalendar python module and google's app engine. However, when I omit the boiler plate <html> header and footer tags on the output from webapp.RequestHandler, it looks like the HTTP 200 response is add...
generating non-html output from google's app engine
I'm trying to dynamically generate iCal output using Max M's icalendar python module and google's app engine. However, when I omit the boiler plate <html> header and footer tags on the output from webapp.RequestHandler, it looks like the HTTP 200 response is added to the top of the file. When I register this code: cla...
[ "Webapp and App Engine don't care what content type you return, so the issue is unrelated to the tag (or lack thereof). You likely have a print statement somewhere in your code, which is causing the headers to be sent as part of the body of the response. You should never use print in a WSGI app - always use self.r...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005095558_django_google_app_engine_python.txt
Q: Python: How to construct a tuple, value dictionary from a list of key,value dictionary? I have a list of dicts as follows: lst = [{'unitname':'unit1', 'test1': 2, 'test2': 9}, {'unitname':'unit2', 'test1': 24, 'test2': 35}] How do I contruct a single dict as follows: dictA = { ('unit1','test1'): 2, ('unit1','test...
Python: How to construct a tuple, value dictionary from a list of key,value dictionary?
I have a list of dicts as follows: lst = [{'unitname':'unit1', 'test1': 2, 'test2': 9}, {'unitname':'unit2', 'test1': 24, 'test2': 35}] How do I contruct a single dict as follows: dictA = { ('unit1','test1'): 2, ('unit1','test2'): 9, ('unit2','test1'):24, ('unit2','test2' : 35 } ` I have all the unit names & test nam...
[ "You could try:\ndictA = {}\nfor l in lst:\n name = l.pop('unitname')\n for test in l:\n dictA[name, test] = l[test]\n\n\nPosted at the same time and with the same assumptions as Gareth's solution - however this will not give you the extra item of (name, 'unitname') = name\n\nMarcelo Cantos's solution is qui...
[ 2, 2, 1 ]
[]
[]
[ "dictionary", "list", "python", "tuples" ]
stackoverflow_0005388962_dictionary_list_python_tuples.txt
Q: fix soaplib to support chunked requests I have soap webservice built with soaplib, but if client sent chunked request it fails on length = req_env.get("CONTENT_LENGTH") body = input.read(int(length)) because length is '' (empty string), any ideas how to fix soaplib? A: a bit ugly, but looks like it works: ...
fix soaplib to support chunked requests
I have soap webservice built with soaplib, but if client sent chunked request it fails on length = req_env.get("CONTENT_LENGTH") body = input.read(int(length)) because length is '' (empty string), any ideas how to fix soaplib?
[ "a bit ugly, but looks like it works:\n\n if '' != length:\n body = input.read(int(length))\n elif req_env.get(\"HTTP_TRANSFER_ENCODING\").lower() == 'chunked':\n\n chunk_size = int(input.readline(), 16)\n while chunk_size > 0:\n ...
[ 0 ]
[]
[]
[ "python", "soap", "soaplib", "web_services" ]
stackoverflow_0005351250_python_soap_soaplib_web_services.txt
Q: python ctypes Win32 way window title gets truncted? I been trying to create Win32 Application by using python (2.7) and ctypes module. Window is created and shown but title of window gets truncated. I got 'M' instead of 'My test window'. What I am doing wrong? Thanks in advance P.S. Here follows the code and scree...
python ctypes Win32 way window title gets truncted?
I been trying to create Win32 Application by using python (2.7) and ctypes module. Window is created and shown but title of window gets truncated. I got 'M' instead of 'My test window'. What I am doing wrong? Thanks in advance P.S. Here follows the code and screenshot: # -*- coding: utf-8 -*- from sys import platform,...
[ "It is because you are creating a Unicode window with CreateWindowExW but then calling the ANSI DefWindowProcA. You are passing Unicode strings which typically have zero for every other byte since your text is in the ASCII range which explains what you observe.\nThe solution? Call DefWindowProcW instead.\nActually...
[ 5, 0 ]
[]
[]
[ "ctypes", "python", "winapi" ]
stackoverflow_0005388576_ctypes_python_winapi.txt
Q: Read file Again Python I would like to read a file again and again when it arrives at the end. The file is only numbers separate by comma. I use python and I read on the doc that file.seek(0) can be use for this but doesn't work for me. This is my script: self.users = [] self.index = -1 infile = open(filename, "r"...
Read file Again Python
I would like to read a file again and again when it arrives at the end. The file is only numbers separate by comma. I use python and I read on the doc that file.seek(0) can be use for this but doesn't work for me. This is my script: self.users = [] self.index = -1 infile = open(filename, "r") for line in infile.readlin...
[ "\ninfile.read() will read in the whole of the file and then throw away the result. Why are you doing it?\nWhen you call infile.readlines you have already read in the whole file. Then your loop iterates over the result, which is just a Python list. Moving to the start of the file will have no effect on that.\nIf yo...
[ 2, 2, 1, 0 ]
[]
[]
[ "file", "python", "reload" ]
stackoverflow_0005389021_file_python_reload.txt
Q: Simple multi-threading with SQLObject doesn't work It stucks once I execute .getOne(): from sqlobject import * import threading sqlhub.processConnection = connectionForURI('mysql://user:password@localhost:3306/database') class Player(SQLObject): name = StringCol(length=64) last_login = DateTimeCol() ...
Simple multi-threading with SQLObject doesn't work
It stucks once I execute .getOne(): from sqlobject import * import threading sqlhub.processConnection = connectionForURI('mysql://user:password@localhost:3306/database') class Player(SQLObject): name = StringCol(length=64) last_login = DateTimeCol() create_date = DateTimeCol(default=DateTimeCol.now) def ...
[ "could getOne be falling over, and you're just not seeing the exception? In this case you can specify a default result as an argument, or you could put it in a try/except clause.\nWhat happens if you run it in a debugger?\nthere's not much info to go on here as we don't know what's in your database.\n", "Unfortun...
[ 1, 0 ]
[]
[]
[ "python", "sqlobject" ]
stackoverflow_0005361943_python_sqlobject.txt
Q: Fast way for multiple processes to read from central source in Python? I'm looking for a fast way for multiple processes (in multiprocessing.Pool()) to read from a central datasource. Currently I have a file which is read into a queue (using multiprocessing.Manager().Queue()), then a worker pool is started and it...
Fast way for multiple processes to read from central source in Python?
I'm looking for a fast way for multiple processes (in multiprocessing.Pool()) to read from a central datasource. Currently I have a file which is read into a queue (using multiprocessing.Manager().Queue()), then a worker pool is started and its processes read from this queue. It works fine, but when I'm working with ...
[ "If you're just doing reads on the file it's safe to have multiple processes read at same time. Instead of passing data in the queue, just pass the offset and count. Than in the workers do:\nf.seek(offset)\nget_records(f, count)\n\n" ]
[ 3 ]
[]
[]
[ "multiprocessing", "performance", "python", "queue" ]
stackoverflow_0005389787_multiprocessing_performance_python_queue.txt
Q: Python - iterating over result of list.append why can't I do something like this: files = [file for file in ['default.txt'].append(sys.argv[1:]) if os.path.exists(file)] A: list.append doesn't return anything in Python: >>> l = [1, 2, 3] >>> k = l.append(5) >>> k >>> k is None True You may want this instead: >>...
Python - iterating over result of list.append
why can't I do something like this: files = [file for file in ['default.txt'].append(sys.argv[1:]) if os.path.exists(file)]
[ "list.append doesn't return anything in Python:\n>>> l = [1, 2, 3]\n>>> k = l.append(5)\n>>> k\n>>> k is None\nTrue\n\nYou may want this instead:\n>>> k = [1, 2, 3] + [5]\n>>> k\n[1, 2, 3, 5]\n>>> \n\nOr, in your code:\nfiles = [file for file in ['default.txt'] + sys.argv[1:] if os.path.exists(file)]\n\n", "You c...
[ 10, 4 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005390352_list_python.txt
Q: How to dump/append all the values of a dict into a list if key is a tuple? I have a dict as follows with unit names and testnames in a list: dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45} units = ['unit1', 'unit2'] testnames = ['test1','test2'] How d...
How to dump/append all the values of a dict into a list if key is a tuple?
I have a dict as follows with unit names and testnames in a list: dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45} units = ['unit1', 'unit2'] testnames = ['test1','test2'] How do we append all values of say test1 into a list? i.e. temp = [10,78] # test1 va...
[ "It looks like you're asking about list comprehensions.\n[v for k,v in dictA.iteritems() if k[1] == 'test1']\n\nWill give you:\n[10, 78]\n\nSimilarly:\n>>> [v for k,v in dictA.iteritems() if k[1] == 'test2']\n[2, 45]\n\nNow, where the key is a tuple, we referenced the element in the if-clause.\n", "temp = [ j for...
[ 2, 1, 1 ]
[]
[]
[ "append", "dictionary", "list", "python", "tuples" ]
stackoverflow_0005390362_append_dictionary_list_python_tuples.txt
Q: Pythonic way of creating 2D numpy array I have a function gen() which returns a numpy array of nElements number of floats. I'm looking for a more Pythonic (one liner?) way to do the following: a = zeros((nSamples, nElements)) for i in xrange(nSamples): a[i,:] = gen() This is one way to do it: a = array([gen(...
Pythonic way of creating 2D numpy array
I have a function gen() which returns a numpy array of nElements number of floats. I'm looking for a more Pythonic (one liner?) way to do the following: a = zeros((nSamples, nElements)) for i in xrange(nSamples): a[i,:] = gen() This is one way to do it: a = array([gen() for i in xrange(nSamples)]).reshape((nSampl...
[ "This may not answer your question directly, but since you mentioned Pythonic in the title... Please understand that Pythonic isn't necessarily a \"one-liner\" or the most clever and short (keystroke-wise) way of doing something. Quite the contrary - Pythonic code strives for clarity. \nIn the case of your code, I ...
[ 9, 0 ]
[]
[]
[ "2d", "arrays", "numpy", "python" ]
stackoverflow_0005390301_2d_arrays_numpy_python.txt
Q: How to reliably process web-data in Python I'm using the following code to get data from a website: time_out = 4 def tryconnect(turl, timer=time_out, retries=10): urlopener = None sitefound = 1 tried = 0 while (sitefound != 0) and tried < retries: try: urlopener = urllib2.urlop...
How to reliably process web-data in Python
I'm using the following code to get data from a website: time_out = 4 def tryconnect(turl, timer=time_out, retries=10): urlopener = None sitefound = 1 tried = 0 while (sitefound != 0) and tried < retries: try: urlopener = urllib2.urlopen(turl, None, timer) sitefound = 0 ...
[ "You can avoid some boilerplate code in the first function too:\ntime_out = 4\n\ndef tryconnect(turl, timer=time_out, retries=10):\n for tried in xrange(retries):\n try:\n return urllib2.urlopen(turl, None, timer)\n except urllib2.URLError:\n pass\n return None\n\nand in th...
[ 6 ]
[]
[]
[ "python", "urllib2", "urlopen", "web" ]
stackoverflow_0005390752_python_urllib2_urlopen_web.txt
Q: Patches I add to my graph are not opaque with alpha=1. Why? I would like to add a rectangle over a graph. Through all the documentation I've found, the rectangle should be opaque by default, with transparency controlled by an alpha argument. However, I can't get the rectangle to show up as opaque, even with alpha ...
Patches I add to my graph are not opaque with alpha=1. Why?
I would like to add a rectangle over a graph. Through all the documentation I've found, the rectangle should be opaque by default, with transparency controlled by an alpha argument. However, I can't get the rectangle to show up as opaque, even with alpha = 1. Am I doing something wrong, or is there something else I nee...
[ "From the documentation:\n\nWithin an axes, the order that the\n various lines, markers, text,\n collections, etc appear is determined\n by the\n matplotlib.artist.Artist.set_zorder()\n property. The default order is\n patches, lines, text, with collections\n of lines and collections of patches\n appearing ...
[ 11, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005390699_matplotlib_python.txt
Q: Matrix class definition I need some help especially for b). Thank you Define a class for matrices as follows: (a) Provide an implementation of __init__ that takes a list of lists as input and returns a new object of type matrix. For the matrix A = 1 2 3 4 a user could enter A = matrix( [[1,2],[3,4]]). (b) Provid...
Matrix class definition
I need some help especially for b). Thank you Define a class for matrices as follows: (a) Provide an implementation of __init__ that takes a list of lists as input and returns a new object of type matrix. For the matrix A = 1 2 3 4 a user could enter A = matrix( [[1,2],[3,4]]). (b) Provide an implementation of __repr...
[ "For a), it really depends on how you want to store the matrix. Storing the matrix as a list of lists, as is, is probably fine for most uses, but I don't know what your use is exactly. Matrixes have constraints that lists of lists lack (all rows have the same numbers of items of the same type); it will be up to thi...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005391401_python.txt
Q: How should I host multiple Pylons websites on the one server? I currently have one Pylons website running on my server that is setup using nginx as a proxy to Paster. In the near future, I plan to host another Pylons site on the same server. If I were to go the same route and use nginx+Paster, it would mean runnin...
How should I host multiple Pylons websites on the one server?
I currently have one Pylons website running on my server that is setup using nginx as a proxy to Paster. In the near future, I plan to host another Pylons site on the same server. If I were to go the same route and use nginx+Paster, it would mean running two paster instances on different ports and then using the one ng...
[ "I think there is nothing wrong with running few paster instances, but you should consider using FastCGI (or wsgi) and Virtual Hosts, because it's more suitable for \"production environment\". \nExample with FastCGI:\npid /var/run/nginx.pid;\nuser www;\nworker_processes 1;\n\nevents {\n wor...
[ 1, 1 ]
[]
[]
[ "paster", "pylons", "python", "web" ]
stackoverflow_0003920258_paster_pylons_python_web.txt
Q: How do I put a task back in the queue if the task fails? I have a script that looks something like this: #!/usr/bin/env python # encoding: utf-8 import time, random, os, multiprocessing def main(): NPROCESSES = 5 pool = multiprocessing.Pool(processes=NPROCESSES) a = [1,2,3,4,5,6,7,8,9,0] for _ i...
How do I put a task back in the queue if the task fails?
I have a script that looks something like this: #!/usr/bin/env python # encoding: utf-8 import time, random, os, multiprocessing def main(): NPROCESSES = 5 pool = multiprocessing.Pool(processes=NPROCESSES) a = [1,2,3,4,5,6,7,8,9,0] for _ in pool.imap_unordered(do_task, a): pass def do_task(n...
[ "You could collect results from do_task, check which results are instances of Hell, stuff those tasks into a list new_tasks, and loop until there are no new_tasks: \nimport time\nimport random\nimport os\nimport multiprocessing as mp\n\ndef main():\n NPROCESSES = 5\n pool=mp.Pool(NPROCESSES)\n a = [1,2,3,4...
[ 5 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005391131_multiprocessing_python.txt
Q: Is there a better way to do this? I'm have a table with 'cellid' 'date'(datetime) and 'block'(real) columns. I'm trying to find all the id's which had block > 1 for the last 3 days. I'm currently doing it like this: cells = npar.db.execute("SELECT cellid FROM data WHERE block > 1 AND date=?", (files[0][1],)).fetch...
Is there a better way to do this?
I'm have a table with 'cellid' 'date'(datetime) and 'block'(real) columns. I'm trying to find all the id's which had block > 1 for the last 3 days. I'm currently doing it like this: cells = npar.db.execute("SELECT cellid FROM data WHERE block > 1 AND date=?", (files[0][1],)).fetchall() cells1 = npar.db.execute("SELECT ...
[ "\"for the last 3 days\"? So the following could work?\ncells = npar.db.execute(\"SELECT cellid FROM data \"\n \"WHERE block > 1 \"\n \"AND date >= ? \"\n \"GROUP BY cellid \"\n \"HAVING COUNT(*) = 3\", (files[0][1],)).fetch...
[ 3 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005391181_python_sqlite.txt
Q: Is it possible to directly extend multiple lists using a tuple of lists returned by a function? I have a function that checks for file and directory changes within a given function and returns a tuple of lists, like this: addedFiles, removedFiles, addedDirs, removedDirs. Each of the named sublists in the tuple wil...
Is it possible to directly extend multiple lists using a tuple of lists returned by a function?
I have a function that checks for file and directory changes within a given function and returns a tuple of lists, like this: addedFiles, removedFiles, addedDirs, removedDirs. Each of the named sublists in the tuple will be a list of strings (or empty). I need to append the results return by the function to local versi...
[ "How about:\n for a,b in zip(lists, extendwith):\n a.extend(b)\n\n", "params = ('addedFiles', 'removedFiles', 'addedDirs', 'removedDirs')\nparamDict = dict((param, []) for param in params)\n\nfor dir in allDirs:\n for param, data in zip(params, scanDir(dir)):\n paramDict[param].extend(data)\n\nNow y...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005391577_python.txt
Q: Taskqueue set exact/approximate excution time Is it possible to set exact or at least approximate execution time of scheduled task on GAE that will execute at rate specified (5/s, 100/h)? A: If you want something to happen regularly at a particular time, then you should use cron. Create a handler that will spaw...
Taskqueue set exact/approximate excution time
Is it possible to set exact or at least approximate execution time of scheduled task on GAE that will execute at rate specified (5/s, 100/h)?
[ "If you want something to happen regularly at a particular time, then you should use cron. Create a handler that will spawn Tasks and have cron trigger it at a certain time.\nIf you need to do this programatically (ie, it's not regular enough to use cron) then you can set a countdown on a Taskqueue Task when it's c...
[ 6 ]
[]
[]
[ "batch_processing", "google_app_engine", "python", "task_queue" ]
stackoverflow_0005390938_batch_processing_google_app_engine_python_task_queue.txt
Q: Python dict.get() behavior when first arg exists but *default* doesn't So, I have some code which contains a dictionary, and I do some validation on the dictionary. The validation rule is basically that the dictionary may contain either a 'to' key, or a 'to[]' key. Whichever one it contains, I need the value back ...
Python dict.get() behavior when first arg exists but *default* doesn't
So, I have some code which contains a dictionary, and I do some validation on the dictionary. The validation rule is basically that the dictionary may contain either a 'to' key, or a 'to[]' key. Whichever one it contains, I need the value back so I can check the length against the length of another key in the dictionar...
[ "Arguments to a function or method are always evaluated before the function is called. If you don't want this then use a sentinel object instead of the expression as the default.\n" ]
[ 9 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005391968_dictionary_python.txt
Q: Set QBoxLayout maximum size? I clearly missing something here, please enlighten me. AttributeError: 'QVBoxLayout' object has no attribute 'setMaximumSize' I've been reading the Qt Docs for a while but just cant seem to be able to get this to work A: AFAIK you can't set a maximal size for a layout. Why would you...
Set QBoxLayout maximum size?
I clearly missing something here, please enlighten me. AttributeError: 'QVBoxLayout' object has no attribute 'setMaximumSize' I've been reading the Qt Docs for a while but just cant seem to be able to get this to work
[ "AFAIK you can't set a maximal size for a layout. Why would you want to - it makes no sense to me (which child widget should the layout limit?)\nRegarding setMaximumSize - there's no such method for layouts. There is however, a QLayout::SetMaximumSize constraint which you can set, but this constraint applies to the...
[ 4, 1, 0 ]
[]
[]
[ "pyqt", "python", "qt4" ]
stackoverflow_0005391894_pyqt_python_qt4.txt
Q: Does _PyString_Resize realloc memory? I'm working on a Python C extension module (for CPython 2.5). It calls some underlying network API that fills a buffer. Currently the code is written basically as follow: PyObject * buffer; char * cbuf; size_t buffer_size = 1024; int sz; buffer = PyString_FromStringAndSize(NUL...
Does _PyString_Resize realloc memory?
I'm working on a Python C extension module (for CPython 2.5). It calls some underlying network API that fills a buffer. Currently the code is written basically as follow: PyObject * buffer; char * cbuf; size_t buffer_size = 1024; int sz; buffer = PyString_FromStringAndSize(NULL, buffer_size); if (buffer == NULL) return...
[ "Yes, _PyString_Resize does realloc - after all, this is what you asked it to do :-)\nIf you want to save the reallocation, perhaps you can read into a buffer on the stack and then just create the string object from it. Something like (not compiled & tested, so treat it as pseudocode):\nchar cbuf[BUFFER_SIZE];\nint...
[ 3 ]
[]
[]
[ "c", "cpython", "python" ]
stackoverflow_0005392657_c_cpython_python.txt
Q: Odd Python threading problem with QT I have a module that multi-threads some code (using threading library) and on top of it, another module which implements GUI (using QT). Now, everything seems to work fine, except that when I compile the code to a pyc file, and change the extension to pyw to get rid of the blac...
Odd Python threading problem with QT
I have a module that multi-threads some code (using threading library) and on top of it, another module which implements GUI (using QT). Now, everything seems to work fine, except that when I compile the code to a pyc file, and change the extension to pyw to get rid of the black CMD screen, the GUI works, multithreadin...
[ "I would guess its do with Windows POpen Failures, you way want to look into using Qt's QThreads instead.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "qt" ]
stackoverflow_0004454089_multithreading_python_qt.txt
Q: Python: time.mktime returning the same value for different dates I was working on some python scripts to calculate the time spent since an older date, and surprisingly got a negative result. I realized that the problem may be in the time.mktime function. Let's get this code: import time import datetime before = d...
Python: time.mktime returning the same value for different dates
I was working on some python scripts to calculate the time spent since an older date, and surprisingly got a negative result. I realized that the problem may be in the time.mktime function. Let's get this code: import time import datetime before = datetime.datetime(2010, 10, 17, 0, 0, 0) after = datetime.datetime(2010...
[ "No. DST in Brazil started on October 17, 2010, so one hour is missing.\n", "Note that mktime gives you the representation of your local time, with Daylight Savings if applicable to your system locale. This can lead to some odd behaviors.\nYou may prefer calendar.timegm which gives you UTC time.\n" ]
[ 6, 1 ]
[]
[]
[ "datetime", "mktime", "python", "time" ]
stackoverflow_0005392814_datetime_mktime_python_time.txt
Q: Comparing file contents in Python I have two files, say source and target. I compare each element in source to check if it also exists in target. If it does not exist in target, I print it ( the end goal is to have 0 difference). Here is the code I have written. def finddefaulters(source,target): f = open(sourc...
Comparing file contents in Python
I have two files, say source and target. I compare each element in source to check if it also exists in target. If it does not exist in target, I print it ( the end goal is to have 0 difference). Here is the code I have written. def finddefaulters(source,target): f = open(source,'r') g = open(target,'r') refere...
[ "Some ideas:\n1) use [with] to open files safely:\nwith open(source) as f:\n .............\n\n\nThe with statement is used to wrap the\n execution of a block with methods\n defined by a context manager. This\n allows common try...except...finally\n usage patterns to be encapsulated for\n convenient reuse.\...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005392757_python.txt
Q: How to use python gettext with PO files from http://translationproject.org? I'm new to Python and Django. I want to start a Django multi langual project. I see that I should use gettext to translate the strings but I'm not getting how it works. For example. My main language is Portuguese, and I need to translate t...
How to use python gettext with PO files from http://translationproject.org?
I'm new to Python and Django. I want to start a Django multi langual project. I see that I should use gettext to translate the strings but I'm not getting how it works. For example. My main language is Portuguese, and I need to translate to English and Chinese. What PO files I need, and how to get the files? Sorry if t...
[ "\"Overview of GNU gettext\"\nI recommend taking some time to read over the document that article is part of, the Python documentation for the gettext module, and the Django i18n and l10n documentation.\n" ]
[ 1 ]
[]
[]
[ "django", "gettext", "python" ]
stackoverflow_0005393074_django_gettext_python.txt
Q: Cannot link boost.python with mingw I have already build boost.python lib by mingw,Got two lib files: libboost_python-mgw45-mt-1_46_1.a libboost_python-mgw45-mt-d-1_46_1.a But I cant link these libs in my test programs.And the other components like regex works fine.I dont know how to solve this. my user-config.j...
Cannot link boost.python with mingw
I have already build boost.python lib by mingw,Got two lib files: libboost_python-mgw45-mt-1_46_1.a libboost_python-mgw45-mt-d-1_46_1.a But I cant link these libs in my test programs.And the other components like regex works fine.I dont know how to solve this. my user-config.jam: using python : 2.7 : F:\\Pr...
[ "I don't know why (and I never really cared enough to dig for the reason), but Boost.Python refuses to link statically on Windows. This is easily solved, though — just rebuild it as a DLL (bjam toolset=gcc --with-python link=shared).\n" ]
[ 2 ]
[]
[]
[ "boost", "mingw", "python" ]
stackoverflow_0005392962_boost_mingw_python.txt
Q: QGraphicsPixmapItem won't appear after using cx_freeze I am having trouble understanding why my QGraphicsPixmapItem is not showing up after I build the application using cx_freeze. Are there any known issues with that class and cx_freeze or am I missing some settings with cx_freeze? Here is the part that is crea...
QGraphicsPixmapItem won't appear after using cx_freeze
I am having trouble understanding why my QGraphicsPixmapItem is not showing up after I build the application using cx_freeze. Are there any known issues with that class and cx_freeze or am I missing some settings with cx_freeze? Here is the part that is creating and displaying the QGraphicsPixmapItem and after that i...
[ "So I found the answer to my question. Apparently the problem wasn't with the QGraphicsPixmapItem class, it was with the QtSvg portion of the application. Which threw me off because cx_freeze's output showed that the QtSvg Module was included when creating the executable, but that is not all that is needed by the...
[ 5 ]
[]
[]
[ "cx_freeze", "pyqt4", "python", "python_3.x" ]
stackoverflow_0005383953_cx_freeze_pyqt4_python_python_3.x.txt
Q: Django Admin Changing Inline Admin Form based on class type I asked some questions about Django inheritance in a previous question. Now I am trying to figure out how to get the admin interface to work with it. If I had some models like this: class ContentItem(models.Model): title = models.CharField(max_le...
Django Admin Changing Inline Admin Form based on class type
I asked some questions about Django inheritance in a previous question. Now I am trying to figure out how to get the admin interface to work with it. If I had some models like this: class ContentItem(models.Model): title = models.CharField(max_length=1000) page_order = models.IntegerField() last_update...
[ "So it turns out that if you use django-model-utils and do the inheritance. Then you can add inlines for each of the sub classes. The Django admin will figure it out. It will show the right form for the class.\nProblem solved.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "django_templates", "python" ]
stackoverflow_0005383332_django_django_admin_django_templates_python.txt
Q: Python - Convert CSV to DBF I would like to convert a csv file to dbf using python (for use in geocoding which is why I need the dbf file) - I can easily do this in stat/transfer or other similar programs but I would like to do as part of my script rather than having to go to an outside program. There appears to b...
Python - Convert CSV to DBF
I would like to convert a csv file to dbf using python (for use in geocoding which is why I need the dbf file) - I can easily do this in stat/transfer or other similar programs but I would like to do as part of my script rather than having to go to an outside program. There appears to be a lot of help questions/answers...
[ "Duplicate question at: Convert .csv file into .dbf using Python?\nPromising answer there (among others) is\nUse the csv library to read your data from the csv file. The third-party dbf library can write a dbf file for you. \n", "For example, you could try:\n\nhttp://packages.python.org/dbf/\nhttp://code.activest...
[ 1, 0 ]
[]
[]
[ "csv", "dbf", "python" ]
stackoverflow_0003897694_csv_dbf_python.txt
Q: Why was PyPI called the cheese shop? I was running through the tutorials to build a Python distro package yesterday and the PyPI site kept on being calling the Cheese Shop. Why is that? A: Following the fact that the name of the Python language is taken from the Monty Python comedy group, it's a reference to the...
Why was PyPI called the cheese shop?
I was running through the tutorials to build a Python distro package yesterday and the PyPI site kept on being calling the Cheese Shop. Why is that?
[ "Following the fact that the name of the Python language is taken from the Monty Python comedy group, it's a reference to the \"Cheese Shop\" sketch they did.\nIn the sketch, a customer becomes frustrated because the cheese shop apparently does not have very many kinds of cheese available. Similarly, the package in...
[ 57 ]
[]
[]
[ "pypi", "python" ]
stackoverflow_0005393986_pypi_python.txt
Q: How do I delete all Entities in all namespaces in GAE? Google App Engine allows to administrate the Datastore http://code.google.com/appengine/docs/adminconsole/datastoreadmin.html but there is no mention about namespaces, except default namespace. I have alot of namespaces and now I want to delete all entities/na...
How do I delete all Entities in all namespaces in GAE?
Google App Engine allows to administrate the Datastore http://code.google.com/appengine/docs/adminconsole/datastoreadmin.html but there is no mention about namespaces, except default namespace. I have alot of namespaces and now I want to delete all entities/namespaces in the Datastore. Is there simple way to do it?
[ "Not sure if this would qualify for simple, but...\nYou could use the mapper api to create functions that will iterate over entire collections, and you can get all the namespaces used via db.GqlQuery(\"SELECT * FROM __namespace__\")\nSo assuming you have a function for mapping over all of your entitys like this one...
[ 7 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "namespaces", "python" ]
stackoverflow_0005389973_google_app_engine_google_cloud_datastore_namespaces_python.txt
Q: Python: Retrieving only POP3 message text, no headers I'm trying to make a Python program that retrieves only the body text of an email without passing headers or any other parameters. I'm not sure how to go about this. The goal is to be able to send basic commands to a program via message text. What I have now is...
Python: Retrieving only POP3 message text, no headers
I'm trying to make a Python program that retrieves only the body text of an email without passing headers or any other parameters. I'm not sure how to go about this. The goal is to be able to send basic commands to a program via message text. What I have now is this: import poplib host = "pop.gmail.com" mail = poplib....
[ "I would use email module to get the body of email message with get_payload() method which skips header info.\nI added few lines to your code (they are marked with # new statement at the end of line)\nimport poplib\nimport email # new statement\n\nhost = \"pop.gmail.com\"\nmail = poplib.POP3_SSL(host)\nprint mail.g...
[ 5, 4, 2 ]
[]
[]
[ "email", "pop3", "poplib", "python", "text" ]
stackoverflow_0002218066_email_pop3_poplib_python_text.txt
Q: How to close cursor in MongoKit I'm using MongoKit to perform iteration over a huge amount of data. During this process my cursor becomes invalid, and I'm getting OperationFailure: cursor id '369397057360964334' not valid at server I've read in mailing lists that I can pass parameter timeout=False to .find() metho...
How to close cursor in MongoKit
I'm using MongoKit to perform iteration over a huge amount of data. During this process my cursor becomes invalid, and I'm getting OperationFailure: cursor id '369397057360964334' not valid at server I've read in mailing lists that I can pass parameter timeout=False to .find() method, but PyMongo FAQ says that I vave t...
[ "You'll have to close the cursor since the MongoDB server won't time out the cursor for you, given that you specifically asked it not to.\nsimply call del on your cursor. The default pymongo implementation for __del__ will notify the server to kill the cursor.\nAssuming something like:\ncursor = db.test.find(timeou...
[ 9 ]
[]
[]
[ "database_cursor", "mongodb", "mongokit", "pymongo", "python" ]
stackoverflow_0005392318_database_cursor_mongodb_mongokit_pymongo_python.txt
Q: Help with django bugtrack comments system using ModelForm I'm trying to add a comments component to a bug tracking application using django. I have a text field for comments and a by field--auto-propagated by user id. I want the comments text field to become read-only after someone saves a comment. I've tried doin...
Help with django bugtrack comments system using ModelForm
I'm trying to add a comments component to a bug tracking application using django. I have a text field for comments and a by field--auto-propagated by user id. I want the comments text field to become read-only after someone saves a comment. I've tried doing this several ways. The best way I have come up with so far is...
[ "Don't instantiate the form in the TabularInline subclass:\n form = CommentForm\n\n" ]
[ 1 ]
[]
[]
[ "bug_tracking", "comments", "django", "django_forms", "python" ]
stackoverflow_0005393952_bug_tracking_comments_django_django_forms_python.txt
Q: adding nodes to xml file with same node name but different attributes with Python Dom is it possible to add two nodes with the same name to a xml document ? That is something like that : Initial file : <Files> <Filter> </Filter> </Files> Wanted file : <Files> <Filter> <File RelativePath=".\src\aaa.cxx" ...
adding nodes to xml file with same node name but different attributes with Python Dom
is it possible to add two nodes with the same name to a xml document ? That is something like that : Initial file : <Files> <Filter> </Filter> </Files> Wanted file : <Files> <Filter> <File RelativePath=".\src\aaa.cxx" ></File> <File RelativePath=".\src\bbb.cxx"></File> </Filter> </Files> I would like...
[ "Not sure where your code is going wrong, as you've not provided a testable example. I'm not particularly familiar with minidom, I prefer lxml.\nI suspect you need to instantiate each new child node separately.\nThis works for me:\n>>> import xml.dom.minidom\n>>>\n>>> data_in = \"\"\"<Files>\n... <Filter>\n... ...
[ 3 ]
[]
[]
[ "dom", "minidom", "python", "xml" ]
stackoverflow_0005393557_dom_minidom_python_xml.txt
Q: Unable to select Checkbox inside TreeView I tried creating a treeview with checkboxes but I'm unable to select the checkboxes. on the flag method I had mentioned it as ItemisuserCheckable but still could not get it working... am I missing something here to enable the selection of checkboxes. A snippet of the code ...
Unable to select Checkbox inside TreeView
I tried creating a treeview with checkboxes but I'm unable to select the checkboxes. on the flag method I had mentioned it as ItemisuserCheckable but still could not get it working... am I missing something here to enable the selection of checkboxes. A snippet of the code is: import sys from PyQt4.QtCore import * from...
[ "you need to hold somewhere current item state (checked\\unchecked) and change it once setdata() method is called. Your items are always unchecked because you're always returning QVariant(Qt.Unchecked) for them in the data() method. \nI've changed a bit your code, see it would work for you:\nimport sys\n\nfrom PyQt...
[ 3, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "treeview" ]
stackoverflow_0005374168_pyqt_pyqt4_python_qt_treeview.txt
Q: Condition checking when using numpy.piecewise to generate a piecewise periodic plot I'm trying to generate a piecewise periodic plot using Numpy and matplotlib, like this: import numpy as np import matplotlib.pyplot as plt Q1 = lambda t, f, Q_max: Q_max * np.sin(2 * np.pi *f * t) Q2 = lambda t, f, Q_max: 0 def Q...
Condition checking when using numpy.piecewise to generate a piecewise periodic plot
I'm trying to generate a piecewise periodic plot using Numpy and matplotlib, like this: import numpy as np import matplotlib.pyplot as plt Q1 = lambda t, f, Q_max: Q_max * np.sin(2 * np.pi *f * t) Q2 = lambda t, f, Q_max: 0 def Q_true(t, f, stat): while(t >= 1/f): t -= 1/f while(t < 0): t +=...
[ "The following version of Q_true works:\ndef Q_true(t, f, stat):\n period = 1/f\n return (t % period < period/2) == stat\n\nNote that you are naming your anonymous functions (Q1 = lambda ...). In this case you should just define the function using def.\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "numpy", "piecewise", "python" ]
stackoverflow_0005393205_matplotlib_numpy_piecewise_python.txt
Q: How to read only last buffer from telnetlib command I have following python code: import telnetlib ts = telnetlib.Telnet('192.168.0.2') ts.set_debuglevel(10) ts.read_until("assword:", 5) ts.write("xxxxx\n") ts.write("enable\n") ts.read_until("assword:", 5) ts.write("xxxxx\n") ts.write("term len 0\n") ts.write("sho...
How to read only last buffer from telnetlib command
I have following python code: import telnetlib ts = telnetlib.Telnet('192.168.0.2') ts.set_debuglevel(10) ts.read_until("assword:", 5) ts.write("xxxxx\n") ts.write("enable\n") ts.read_until("assword:", 5) ts.write("xxxxx\n") ts.write("term len 0\n") ts.write("show start\n") But how can i read the buffer only from "sho...
[ "Try using ts.read_until(\"\") before the command whose output you want to grab\nimport telnetlib \nts = telnetlib.Telnet('192.168.0.2') \nts.set_debuglevel(10) \nts.read_until(\"assword:\", 5) \nts.write(\"xxxxx\\n\") \nts.write(\"enable\\n\") \nts.read_until(\"assword:\", 5) \nts.write(\"xxxxx\\n\") \nts....
[ 4 ]
[]
[]
[ "python", "telnetlib" ]
stackoverflow_0003468523_python_telnetlib.txt
Q: Generic relation with sqlalchemy as in django contenttypes I'm trying to make some generic apps using Sql Alchemy, such as tags or rating for any model. But I couldn't find any help in the docs. I really liked what I could do with the django contenttypes framework ? Is there any similar functionality in Sql Alchem...
Generic relation with sqlalchemy as in django contenttypes
I'm trying to make some generic apps using Sql Alchemy, such as tags or rating for any model. But I couldn't find any help in the docs. I really liked what I could do with the django contenttypes framework ? Is there any similar functionality in Sql Alchemy ?
[ "I once wrote some example code about something similar to this (see http://taketwoprogramming.blogspot.com/2009/08/reusable-sqlalchemy-models.html).\nThe basic idea is that you can create a model like this:\n@commentable\nclass Post(Base):\n __tablename__ = 'posts'\n id = sa.Column(sa.Integer, primary_key=Tr...
[ 4 ]
[]
[]
[ "django", "flask", "python", "sqlalchemy" ]
stackoverflow_0005385992_django_flask_python_sqlalchemy.txt
Q: How to draw an axis in the middle of the figure using Matplotlib I would like to draw a static vertical line that is parallel to the y-axis and which is at the middle of the x-axis. This line should not move when one pan in the figure. My goal is to have this vertical line in the middle of the figure as a referenc...
How to draw an axis in the middle of the figure using Matplotlib
I would like to draw a static vertical line that is parallel to the y-axis and which is at the middle of the x-axis. This line should not move when one pan in the figure. My goal is to have this vertical line in the middle of the figure as a reference line. I will have some other figures which represent data that will ...
[ "The coordinates of the endpoints of that line are (0.5, 0) and (0.5, 1) in axis coordinates:\nfrom matplotlib.lines import Line2D\nfrom matplotlib import pyplot\n\nf=pyplot.figure()\na=f.add_subplot(111)\na.plot([3,1,4,1,5,9,2], color='k') # so you have some content\na.add_line(Line2D([0.5, 0.5], [0, 1], transform...
[ 4 ]
[]
[]
[ "axes", "line", "matplotlib", "python" ]
stackoverflow_0005394527_axes_line_matplotlib_python.txt
Q: why are my weakrefs dead in the water when they point to a method? Possible Duplicate: Why doesn't the weakref work on this bound method? I'm using weakrefs in an observer-pattern and noticed an interesting phenomenon. If I create an object and add one of it's methods as an observer of an Observable, the referen...
why are my weakrefs dead in the water when they point to a method?
Possible Duplicate: Why doesn't the weakref work on this bound method? I'm using weakrefs in an observer-pattern and noticed an interesting phenomenon. If I create an object and add one of it's methods as an observer of an Observable, the reference is dead almost instantly. Can anyone explain what is happening? I'm ...
[ "Whenever you do reference an object method, there's a bit of magic that happens, and it's that magic that's getting in your way.\nSpecifically, Python looks up the method on the object's class, then combines it with the object itself to create a kind of callable called a bound method. Every time e.g. the expressi...
[ 4, 3 ]
[]
[]
[ "observer_pattern", "python", "weak_references" ]
stackoverflow_0005394772_observer_pattern_python_weak_references.txt
Q: pylint import and dynamic path modification My projects are generally structured like this: projectname/ __init__.py python/ mymodule.py other_stuff/ more_stuff/ where __init__.py contains the following code import os mypath = os.path.dirname(os.path.realpath(os.path.abspath(__file__))) __...
pylint import and dynamic path modification
My projects are generally structured like this: projectname/ __init__.py python/ mymodule.py other_stuff/ more_stuff/ where __init__.py contains the following code import os mypath = os.path.dirname(os.path.realpath(os.path.abspath(__file__))) __path__ = [mypath, mypath+"/python"] This "skips"...
[ "I think you're kind of stuck. Pylint doesn't process your __init__.py file so unless you can find another way of getting that information into pylint, I don't think it's going to work. Good luck.\n" ]
[ 3 ]
[]
[]
[ "pydev", "pylint", "python", "pythonpath" ]
stackoverflow_0005394786_pydev_pylint_python_pythonpath.txt
Q: how do i get the value of a function i'm using in an if condition in python? how do i get the value of a function i'm using to trigger an if condition in python? something like... def is_a_banana(a): if a == "Banana": return True else: return False v = "Banana" if ban = is_a_banana(v): prin...
how do i get the value of a function i'm using in an if condition in python?
how do i get the value of a function i'm using to trigger an if condition in python? something like... def is_a_banana(a): if a == "Banana": return True else: return False v = "Banana" if ban = is_a_banana(v): print ban >> True i know i could just split it into... ban = is_a_banana(v) if ban: ...
[ "Update: other answers satisfactorily explained why you can't do what you want directly in Python - I added this just to show that a version that only calculates each ratio a minimum number of times (so still has good performance) is still readable and clear...\nPersonally, I think this is pretty clear:\nif s.real_...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005394447_python.txt
Q: is it possible to call a function every x-number of lines that get interpreted? I am trying to do a progress bar. Would it be possible to count the number of execution lines on a script and associate each execution line with a function so that it is executed every line or every 5 lines? My plan is to update a prog...
is it possible to call a function every x-number of lines that get interpreted?
I am trying to do a progress bar. Would it be possible to count the number of execution lines on a script and associate each execution line with a function so that it is executed every line or every 5 lines? My plan is to update a progress bar every time a line is executed. Is it possible? Can I use decorators to do it...
[ "Yep, you can do that by asking Python to alert you every time it processes a line. Here's an example that prints to stdout after every updatelines times a line is executed:\nimport sys\n\nclass EveryNLines(object):\n def __init__(self, updatelines):\n self.processed = 0\n self.updatelines = update...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005394929_python.txt
Q: python using iteration to create a single row of values vs many rows of values from CouchDB I have some code that iterates through 'Documents' in couchDB for docid in db: test = db.get(docid) try: type = test['type'] except: type = "dontTestMe" if type == 'file': fileName =...
python using iteration to create a single row of values vs many rows of values from CouchDB
I have some code that iterates through 'Documents' in couchDB for docid in db: test = db.get(docid) try: type = test['type'] except: type = "dontTestMe" if type == 'file': fileName = test['AliasName'] fileID = test['fileid'] testName = None if type == 'job':...
[ "print fileName, testName, diff,\n\nnotice the trailing ,\n" ]
[ 2 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0005395142_couchdb_python.txt
Q: SQL Injection Prevention in Python - is using parameterized query enough? I have the following python code: row = conn.execute('''SELECT admin FROM account WHERE password = ?''', (request.headers.get('X-Admin-Pass'),)).fetchone() My question is whether this code is secure for SQL injection? Since I use parameteri...
SQL Injection Prevention in Python - is using parameterized query enough?
I have the following python code: row = conn.execute('''SELECT admin FROM account WHERE password = ?''', (request.headers.get('X-Admin-Pass'),)).fetchone() My question is whether this code is secure for SQL injection? Since I use parameterized query it should be. However, since I am passing user information straight f...
[ "The way that you are inserting the data into the database will ensure that an SQL attack will not work, the execute method will automatically escape the parameters that you passed as a tuple as its second parameter to the query.\nYou are doing that correctly.\n", "If your module uses the DBI specs, then you're p...
[ 2, 1 ]
[]
[]
[ "python", "sql_injection" ]
stackoverflow_0005395290_python_sql_injection.txt
Q: How do I obtain values(lines) from file2 using only indices in file1? I have one file1 with only indices, and second file2 contains the values of these indices of file1. How do I obtain these values from file2 using the indices in file1, and output its value to a third file.For simplicity sake, every index in file...
How do I obtain values(lines) from file2 using only indices in file1?
I have one file1 with only indices, and second file2 contains the values of these indices of file1. How do I obtain these values from file2 using the indices in file1, and output its value to a third file.For simplicity sake, every index in file1 has its associated values in file2. For example: file1: 2 3 4 file2 con...
[ "These solutions do not rely on file1 being ordered, however they do load file2 into memory, which could be costly if file2 is large. you will notice however that wanted_lines and lines_out are generators in the first example, which should save a small amount of memory. \nThis example has no error handling, but is ...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005393150_python.txt
Q: Python pack data to PHP pack data could someone help me get this data into the PHP equivalent: >4siiiiiiiiiiiii8x It is used in struct.pack() in Python. this is what i got so far: N14si13x8 it's supposed to be returning: ('P3TF', 272, 64, 6832, 6896, 1426, 8336, 312, 8656, 0, 8656, 0, 8656, 2924384) The PHP versi...
Python pack data to PHP pack data
could someone help me get this data into the PHP equivalent: >4siiiiiiiiiiiii8x It is used in struct.pack() in Python. this is what i got so far: N14si13x8 it's supposed to be returning: ('P3TF', 272, 64, 6832, 6896, 1426, 8336, 312, 8656, 0, 8656, 0, 8656, 2924384) The PHP version results: array 'si13x81' => int ...
[ "I guess the main problem is that i and s have different meaning in PHP. To recreate your original list in PHP this seems to work:\nprint_r(unpack(\"a4header/N13int/x8fill\", $p));\n\nGives me:\nArray(\n [header] => P3TF\n [int1] => 272\n [int2] => 64\n [int3] => 6832\n [int4] => 6896\n [int5] => ...
[ 1 ]
[]
[]
[ "pack", "php", "python", "struct" ]
stackoverflow_0005395015_pack_php_python_struct.txt
Q: Type of an instance variable Suppose that I have a class like this class Employee: pass I create two objects for Employee as below john = Employee() rob = Employee() ..and create instance variables john.age = 12 rob.age = '15' The compiler accepts both and prints the age (john's age in int and rob's age in ...
Type of an instance variable
Suppose that I have a class like this class Employee: pass I create two objects for Employee as below john = Employee() rob = Employee() ..and create instance variables john.age = 12 rob.age = '15' The compiler accepts both and prints the age (john's age in int and rob's age in string). How is this logical? The ...
[ "Be sure to understand this fundamental principle: in Python, variables don't have types. Values have types. This is the essence of Python's being a dynamically-typed language similarly to Lisp and Javascript, but unlike C, C++ and Java.\n>>> foo = 5 # foo now holds a value of type int\n>>> foo = 'hello' # fo...
[ 7, 2, 1, 1, 0 ]
[]
[]
[ "class", "member", "python" ]
stackoverflow_0005390286_class_member_python.txt
Q: access numpy array from a functional language My primary language is Python. Often when I need to do some cpu heavy task on a numpy array I use scipy.weave.inline to hook up c++ with great results. I suspect many of the algorithms (machine learning stuff) can however be written simpler in a functional language (sc...
access numpy array from a functional language
My primary language is Python. Often when I need to do some cpu heavy task on a numpy array I use scipy.weave.inline to hook up c++ with great results. I suspect many of the algorithms (machine learning stuff) can however be written simpler in a functional language (scheme, haskell...). I was thinking. Is it possible t...
[ "You might have a look at using a shared-memory array of some sort. This implementation would probably be a good place to start: https://bitbucket.org/cleemesser/numpy-sharedmem/src\nThis implementation is intended to be shared between python processes, but it's using named shared memory to do it, so you should be...
[ 4, 4, 1 ]
[ "I can't imagine trying to use numpy through haskell or scheme will be easier than just writing functional python. Try using itertools and functools if you want a more functional flavored python.\n" ]
[ -2 ]
[ "functional_programming", "haskell", "numpy", "python", "scipy" ]
stackoverflow_0005392551_functional_programming_haskell_numpy_python_scipy.txt
Q: Django: Edit Function while not changing the Image data I have an edit function that I want the user to be able to edit the Picture object (tags), while keeping the old image. The form is looking for a photo but I do want the user to be able to change the image - just the other information. How do you pass the or...
Django: Edit Function while not changing the Image data
I have an edit function that I want the user to be able to edit the Picture object (tags), while keeping the old image. The form is looking for a photo but I do want the user to be able to change the image - just the other information. How do you pass the original image data from the picture object into the PictureFor...
[ "I guess I am not sure how to just comment on the original question, but what do you mean by validate? If you are just needing to ensure that the picture object's picture is actually the same after the form is done can you not make some custom clean methods for the form? in a clean method you could compare all met...
[ 0, 0 ]
[]
[]
[ "django_forms", "django_views", "python" ]
stackoverflow_0005394474_django_forms_django_views_python.txt
Q: Finding matches in a Python multi-dimensional list i'm going nuts here with this and i have a deadline. So i have this multi-d list in python: list_a = [[['a', 'b'],['c', 'd'], ['e', 'CB'], ['g', 'h'], ['a', 'j', 'k']]] Notice, that the whole thing is in 2 brackets. I need to compare elements like this: a to c, a...
Finding matches in a Python multi-dimensional list
i'm going nuts here with this and i have a deadline. So i have this multi-d list in python: list_a = [[['a', 'b'],['c', 'd'], ['e', 'CB'], ['g', 'h'], ['a', 'j', 'k']]] Notice, that the whole thing is in 2 brackets. I need to compare elements like this: a to c, a to d, b to c, b to d, a to e, a to CB...until the first...
[ "You can use itertools to get all pairs from a list and then find all products of them:\nimport itertools\nfor l1, l2 in itertools.combinations(list_a[0], 2):\n for e1, e2 in itertools.product(l1, l2):\n print e1, e2\n\nprints:\na c\na d\nb c\nb d\na e\na CB\nb e\nb CB\na g\na h\nb g\nb h\na a\na j\na k\n...
[ 5, 0, 0 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0005389163_multidimensional_array_python.txt
Q: Does python's xml.etree.ElementTree support DTD? Does xml.etree.ElementTree support DTD? if it supports it, can I force ElementTree check a XML file against a dtd file, even if the XML file already has one. (internal or external). A: I'm not sure about xml.etree, but lxml supports DTD validation: http://lxml.de/...
Does python's xml.etree.ElementTree support DTD?
Does xml.etree.ElementTree support DTD? if it supports it, can I force ElementTree check a XML file against a dtd file, even if the XML file already has one. (internal or external).
[ "I'm not sure about xml.etree, but lxml supports DTD validation:\nhttp://lxml.de/validation.html\n" ]
[ 3 ]
[]
[]
[ "dtd", "elementtree", "python", "xml" ]
stackoverflow_0005396135_dtd_elementtree_python_xml.txt
Q: Incredibly basic lxml questions: getting HTML/string content of lxml.etree._Element? This is such a basic question that I actually can't find it in the docs :-/ In the following: img = house_tree.xpath('//img[@id="mainphoto"]')[0] How do I get the HTML of the <img/> tag? I've tried adding html_content() but get A...
Incredibly basic lxml questions: getting HTML/string content of lxml.etree._Element?
This is such a basic question that I actually can't find it in the docs :-/ In the following: img = house_tree.xpath('//img[@id="mainphoto"]')[0] How do I get the HTML of the <img/> tag? I've tried adding html_content() but get AttributeError: 'lxml.etree._Element' object has no attribute 'html_content'. Also, it was ...
[ "I suppose it will be as simple as:\nfrom lxml.etree import tostring\ninner_html = tostring(img)\n\nAs for getting content from inside <p>, say, some selected element el:\ncontent = el.text_content()\n\n" ]
[ 65 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0005395948_lxml_python.txt
Q: Python Dynamic Object Generation Confusion I'm writing a Python script that takes a directory, and for each file of a specific type in that directory, creates a dictionary or custom object. I feel like an idiot, but when I get to the part of actually creating the dictionary..I'm confused on how to instantiate and...
Python Dynamic Object Generation Confusion
I'm writing a Python script that takes a directory, and for each file of a specific type in that directory, creates a dictionary or custom object. I feel like an idiot, but when I get to the part of actually creating the dictionary..I'm confused on how to instantiate and track the dynamic objects. #Pseudocode for each...
[ "track_list = [custom_object(filename) for filename in directory]\n\nwhere directory is a list of the file names you care about is a pretty common pattern. If you want a dictionary with file names for keywords, you can do this:\ncustom_dict = dict((filename, custom_object(filename)) for filename in directory)\n\n",...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "object", "python" ]
stackoverflow_0005396335_dictionary_object_python.txt
Q: Security measures for controlling access to web-services/API I have a webapp with some functionality that I'd like to be made accessible via an API or webservice. My problem is that I want to control where my API can be accessed from, that is, I only want the apps that I create or approve to have access to my API...
Security measures for controlling access to web-services/API
I have a webapp with some functionality that I'd like to be made accessible via an API or webservice. My problem is that I want to control where my API can be accessed from, that is, I only want the apps that I create or approve to have access to my API. The API would be a web-based REST service. My users do not log...
[ "The easiest solution would be IP whitelisting if you expect the API consumer to be requesting from the same IP all the time. \nIf you want to support the ability to 'authenticate' from anywhere, then you're on the right track; it would be a lot easier to share an encryption method and then requesting users send a ...
[ 2, 0, 0 ]
[]
[]
[ "api", "objective_c", "python", "rsa", "security" ]
stackoverflow_0005395588_api_objective_c_python_rsa_security.txt
Q: Python, removing whole list if it contains a matching tuple I hope this hasn't been asked before but it's hard for me to put into words what it is I'm trying to do! It might be easier if I explain my input, and desired output l1 = [[(14, 'h'), (14, 'd')], [(14, 'h'), (14, 'c')], [(14, 'h'), (14, 's')], [(14, 'd'),...
Python, removing whole list if it contains a matching tuple
I hope this hasn't been asked before but it's hard for me to put into words what it is I'm trying to do! It might be easier if I explain my input, and desired output l1 = [[(14, 'h'), (14, 'd')], [(14, 'h'), (14, 'c')], [(14, 'h'), (14, 's')], [(14, 'd'), (14, 'c')], [(14, 'd'), (14, 's')], [(14, 'c'), (14, 's')], [(13...
[ "l2_set = set(l2)\n# or use \n# l2_set = {(13,'h'),(13,'d'),(14,'c'),(14,'s'),(14,'h')}\n# directly\n\nl1 = [hand for hand in l1 if not (hand[0] in l2_set or hand[1] in l2_set)]\n\nIf the entry may contain ≥2 members, you could generalize the filter condition to\nl1 = [hand for hand in l1 if all(subhand not in l2...
[ 5, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0005396447_list_python_tuples.txt
Q: regular expressions in python I find regular expressions pretty tough to understand in python. The documentation is too cryptic. For instance what would be the re for removing all instances of #if DEBUG and everything enclosed between it and its corresponding #endif in a C file. The following is not working: buf ...
regular expressions in python
I find regular expressions pretty tough to understand in python. The documentation is too cryptic. For instance what would be the re for removing all instances of #if DEBUG and everything enclosed between it and its corresponding #endif in a C file. The following is not working: buf = file.read() a = re.compile("#if....
[ "If you want to remove all instances of #if DEBUG all you have to do is define DEBUG to 0, and run the preprocessor on it. No need for nasty regular expressions.\nAlso, it's generally not a good idea to operate on a context free grammar (C source, for example, or more notoriously, html) using regular expressions. U...
[ 3, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0005396013_python_regex_string.txt
Q: Python Config Parser (Duplicate Key Support) So I recently started writing a config parser for a Python project I'm working on. I initially avoided configparser and configobj, because I wanted to support a config file like so: key=value key2=anothervalue food=burger food=hotdog food=cake icecream In short, this ...
Python Config Parser (Duplicate Key Support)
So I recently started writing a config parser for a Python project I'm working on. I initially avoided configparser and configobj, because I wanted to support a config file like so: key=value key2=anothervalue food=burger food=hotdog food=cake icecream In short, this config file is going to be edited via the command ...
[ "Crazy idea: make your dictionary values as a list of 3-tuples with line number, col number and value itself and add special key for comment.\nCommentSymbol = ';'\ndef readConfig(filename):\n f = open(filename, 'r')\n if not f:\n return\n def addValue(dict, key, lineIdx, colIdx, value):\n if ...
[ 0, 0 ]
[]
[]
[ "config", "configuration", "python", "yaml" ]
stackoverflow_0005396144_config_configuration_python_yaml.txt
Q: Python: Get list of applications associated with file (Linux) Am making an application in Python and I need to provide "Open with" menu to user. Currently I am parsing /usr/share/applications/mimeinfo.cashe and ~/.local/share/applications/mimeapps.list but with very poor results. Nautilus has more entries in "Open...
Python: Get list of applications associated with file (Linux)
Am making an application in Python and I need to provide "Open with" menu to user. Currently I am parsing /usr/share/applications/mimeinfo.cashe and ~/.local/share/applications/mimeapps.list but with very poor results. Nautilus has more entries in "Open with" menu. Do you know a better way for getting list of applicat...
[ "I've found a bit more elegant solution. In gnomevfs module there is function named mime_get_all_applications which returns proper list of associated applications.\nMore information can be found here.\nEdit:\nSince the time this answer was written, GnomeVFS was marked as deprecated. GIO does provide this functional...
[ 4, 2 ]
[]
[]
[ "linux", "open_with", "python" ]
stackoverflow_0005395471_linux_open_with_python.txt
Q: Python type inference for autocompletion Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python? The idea is to propose autocompletion for example in the following cases: class A: def m1(self): pass def m2(self): pass a = A() a. <--- suggest he...
Python type inference for autocompletion
Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python? The idea is to propose autocompletion for example in the following cases: class A: def m1(self): pass def m2(self): pass a = A() a. <--- suggest here 'm1' and 'm2' fun1(a) def fun1(b): b. ...
[ "Excellent discussion, with many pointers, here (a bit dated). I don't believe any \"production\" editors aggressively try type-inferencing for autocomplete purposes (but I haven't used e.g. wingware's in a while, so maybe they do now).\n", "You could have a look at ECompletion and OCompletion in Pharo Smalltalk....
[ 9, 2, 1, 1 ]
[]
[]
[ "algorithm", "haskell", "ide", "ocaml", "python" ]
stackoverflow_0001478044_algorithm_haskell_ide_ocaml_python.txt
Q: Turning returned string into dictionary? I'm working on a simple python script. It uses urllib to read from a web page and turn it into a dictionary. The way the webserver outputs is a dictionary because it uses JSON. Here is what I have: import urllib2 d = 'http://www.somewebserver.com/tools/dictionary.php?strin...
Turning returned string into dictionary?
I'm working on a simple python script. It uses urllib to read from a web page and turn it into a dictionary. The way the webserver outputs is a dictionary because it uses JSON. Here is what I have: import urllib2 d = 'http://www.somewebserver.com/tools/dictionary.php?string=hello' r = urllib2.urlopen(d) data = r.read(...
[ "import json\ndictionary = json.loads(data)\n\nOr to save some steps you can pass your file object r to json.load:\ndictionary = json.load(r)\n\n", "Use the JSON routines in the json module to turn it into Python objects.\n", "You first need to de-marshall your json data into a dictionary.\nimport json\ndiction...
[ 6, 1, 1, 1 ]
[]
[]
[ "dictionary", "python", "urllib2" ]
stackoverflow_0005396875_dictionary_python_urllib2.txt
Q: How to display GAE Query object contents and structure? I want to print out the structure of a Query object, similar to how you can print out the contents of a dict or list at the interactive python prompt. I've found I'm having trouble visualizing what the data structures look like, which of course makes passing ...
How to display GAE Query object contents and structure?
I want to print out the structure of a Query object, similar to how you can print out the contents of a dict or list at the interactive python prompt. I've found I'm having trouble visualizing what the data structures look like, which of course makes passing in template arguments much harder. For example, here is a ver...
[ "Query objects don't themselves hold any db.Model entities they are returned by get() or fetch(). So you would have to to switch UserProfile.all() for something like:\nprofiles = UserProfile.all().fetch(1000)\n\nPersonally I like to subclass the db.Model class and add a few conveniences for serialising my models. I...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005393892_google_app_engine_python.txt
Q: Why is `global var` needed in a class variable for class method to access it? class Test: num1 = 1 # CASE 1 # WHY GLOBAL HERE? But no global below in CASE 2 global num2 num2 = 2 def printNum2(self): return num2 ## FAILURE WITH NON-GLOBAL num2, why? # should print 2, with instance i = Tes...
Why is `global var` needed in a class variable for class method to access it?
class Test: num1 = 1 # CASE 1 # WHY GLOBAL HERE? But no global below in CASE 2 global num2 num2 = 2 def printNum2(self): return num2 ## FAILURE WITH NON-GLOBAL num2, why? # should print 2, with instance i = Test() print i.printNum2() # CASE 2 # #AUTOMATICALLY GLOBAL SCOPE? num1=1 def prin...
[ "You don't need global to make printNum2 work correctly. Instead, use this:\nclass Test:\n num1 = 1\n num2 = 2\n\n def printNum2(self):\n return self.num2\n\nYou only need global if you want to do the following:\nx = Test()\nprint num2\n//instead of \nprint x.num2\n\n", "class creates a new scope. Since y...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "global", "python" ]
stackoverflow_0005396983_global_python.txt
Q: How to extend h5py so that I can access data within a hdf5 file? I have a small python program which creates a hdf5 file using the h5py module. I want to write a python module to work on the data from the hdf5 file. How could I do that? More specifically, I can set the numpy arrays to PyArrayObject and read them u...
How to extend h5py so that I can access data within a hdf5 file?
I have a small python program which creates a hdf5 file using the h5py module. I want to write a python module to work on the data from the hdf5 file. How could I do that? More specifically, I can set the numpy arrays to PyArrayObject and read them using PyArg_ParseTuple. This way, I can read elements from the numpy ar...
[ "h5py gives you a direct interface for reading/writing and manipulating data stored in an hdf5 file. Have you looked at the docs? \nhttp://docs.h5py.org/\nI advise starting with these. These have pretty clear examples of how to do simple data access. If there are specific things that you are trying to do that aren'...
[ 2, 1 ]
[]
[]
[ "h5py", "hdf5", "numpy", "python", "python_module" ]
stackoverflow_0005396768_h5py_hdf5_numpy_python_python_module.txt