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: implementing a basic queue/thread process within python looking for some eyeballs to verifiy that the following chunk of psuedo python makes sense. i'm looking to spawn a number of threads to implement some inproc functions as fast as possible. the idea is to spawn the threads in the master loop, so the app will r...
implementing a basic queue/thread process within python
looking for some eyeballs to verifiy that the following chunk of psuedo python makes sense. i'm looking to spawn a number of threads to implement some inproc functions as fast as possible. the idea is to spawn the threads in the master loop, so the app will run the threads simultaneously in a parallel/concurrent manner...
[ "If I understand this right: You spawn lots of threads to get things done faster. \nThis only works if the main part of the job done in each thread is done without holding the GIL. So if there is a lot of waiting for data from network, disk or something like that, it might be a good idea.\nIf each of the tasks are ...
[ 0 ]
[]
[]
[ "multithreading", "parallel_processing", "python", "queue", "simultaneous" ]
stackoverflow_0003357078_multithreading_parallel_processing_python_queue_simultaneous.txt
Q: How to use csv.reader in python with french character like é,à,ç,ê,ë, I have a csv file like 120 column by 4500 row. I read the field "customer name" in the first column, first row. I then look fot this field in a second cvs file containing the "customer name , and customer ID" I write a new cvs file with "custo...
How to use csv.reader in python with french character like é,à,ç,ê,ë,
I have a csv file like 120 column by 4500 row. I read the field "customer name" in the first column, first row. I then look fot this field in a second cvs file containing the "customer name , and customer ID" I write a new cvs file with "customer name", customer ID", and all the rest of the 119 colunm.and continue un...
[ "Although I am not familiar with csv.reader or writer, I have been dealing with utf-8 file reading recently and perhaps using the codecs module might help you out. \nInstead of,\ndata = open(..., \"wb\")\n\ntry,\nimport codecs\n\nand then for all your utf-8 files, use,\ndata = codecs.open(..., \"rb\", \"utf-8\")\n\...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003356074_csv_python.txt
Q: Django, Borg pattern, API calls, caching results I'm using an API from a different site that returns a couple of 'pricepoint URL's that my users use to buy Virtual Goods. I'm supposed to cache those results for at least an hour, since they don't change the price points on their system much. (And we want to save bo...
Django, Borg pattern, API calls, caching results
I'm using an API from a different site that returns a couple of 'pricepoint URL's that my users use to buy Virtual Goods. I'm supposed to cache those results for at least an hour, since they don't change the price points on their system much. (And we want to save both our's and their bandwidth.) After looking for singl...
[ "\nI seem to be hitting their API with\n every time that PriceStore is\n initialized, though. Can anyone spot\n my problem?\n\nYep, it's easy to spot:\ndef __init__(self):\n self.__dict__ = self.__shared_state\n self.lastUpdate = None\n\nthe self.lastUpdate = None absolutely guarantees that the immediately...
[ 4, 1, 0 ]
[]
[]
[ "api", "caching", "django", "python" ]
stackoverflow_0003357158_api_caching_django_python.txt
Q: using Python/Pexpect to crawl a network This is more a logical thinking issue rather than coding. I already have some working code blocks - one which telnets to a device, one which parses results of a command, one which populates a dictionary etc etc Now lets say I want to analyse a network with unknown nodes, a,b...
using Python/Pexpect to crawl a network
This is more a logical thinking issue rather than coding. I already have some working code blocks - one which telnets to a device, one which parses results of a command, one which populates a dictionary etc etc Now lets say I want to analyse a network with unknown nodes, a,b,c etc (but I only know about 1) I give my co...
[ "You are looking at graph algorithms, specifically DFS or BFS. Are you asking specifically about implementation details, or more generally about the algorithms?\nRecursion would be a very neat way of doing this.\nseen = {}\ndef DFS( node ):\n for neighbour in node.neighbours():\n if neighbour not in seen:...
[ 2 ]
[]
[]
[ "dictionary", "pexpect", "python" ]
stackoverflow_0003357396_dictionary_pexpect_python.txt
Q: python: iterating through array i have a list like this: brand_names={'MORPHINE':['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH', 'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH', 'ORAMORPH SR','ROXANOL','ROXANOL 100'], 'OXYCODONE':['COMBUNOX','DIHYDRONE','...
python: iterating through array
i have a list like this: brand_names={'MORPHINE':['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH', 'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH', 'ORAMORPH SR','ROXANOL','ROXANOL 100'], 'OXYCODONE':['COMBUNOX','DIHYDRONE','DINARCON','ENDOCET','ENDODAN', ...
[ "for brand in ['OXYCODONE','HYDROCODONE']:\n if some_value in brand_names[brand]:\n print brand\n\n", "Instead of writing a for loop and appending to a list, you can instead write it as a list comprehension:\nsomevalue = 'EUKODAL'\nresult = [brand_name for brand_name in ['OXYCODONE', 'HYDROCODONE']\n ...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003356548_list_python.txt
Q: Django Admin "Helper" Functionality Not Working on Server In my localhost Django administrator I am able to fill-in Date and Time fields by clicking on the little "Date" and "Time" helper icons next to my pub_date field. However, the same administrator on my Server does NOT show these icons. The server-side admin ...
Django Admin "Helper" Functionality Not Working on Server
In my localhost Django administrator I am able to fill-in Date and Time fields by clicking on the little "Date" and "Time" helper icons next to my pub_date field. However, the same administrator on my Server does NOT show these icons. The server-side admin also doesn't pop open a pop-up window for the little "+" plus s...
[ "You are probably not serving javascript files properly. To have this functionality, proper javascript must loaded.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003357779_django_django_admin_python.txt
Q: Request whith Q() object There is code and Tracebeck. What I'm doing wrong? media=MediaObject.objects.get( Q(on_air__range=(strt_time,end_time)), Q(channel=3), Q(name__icontains="qwwwwwww".decode('utf-8')|Q(name__icontains="cccccccc dddddd".decode('utf-8'))) ) Traceback (most recent call last): ...
Request whith Q() object
There is code and Tracebeck. What I'm doing wrong? media=MediaObject.objects.get( Q(on_air__range=(strt_time,end_time)), Q(channel=3), Q(name__icontains="qwwwwwww".decode('utf-8')|Q(name__icontains="cccccccc dddddd".decode('utf-8'))) ) Traceback (most recent call last): File "C:\Documents and Set...
[ "You are just missing a right parenthesis:\nQ(name__icontains=\"Малахов\".decode('utf-8'))|Q(name__icontains=\"Давай поженимся\".decode('utf-8'))\n# here ---^\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_q", "python" ]
stackoverflow_0003357908_django_django_q_python.txt
Q: win32api vs Python What are the Pro's and Con's of using win32api for I/O and other things instead of simply Python, if both have a specific function for it I mean, using PyWin32 vs Win32Api A: con (lack of) portability harder/more error prone pro performance (potentially, it must be measured, as will depend ...
win32api vs Python
What are the Pro's and Con's of using win32api for I/O and other things instead of simply Python, if both have a specific function for it I mean, using PyWin32 vs Win32Api
[ "con\n\n(lack of) portability\nharder/more error prone\n\npro\n\nperformance (potentially, it must be measured, as will depend on more than just the api calls)\n\n", "The most obvious thing seems to be losing cross-platform compatibilty. Python runs on a number of different platforms, none of which has a win32 AP...
[ 5, 4 ]
[]
[]
[ "io", "python", "winapi" ]
stackoverflow_0003358126_io_python_winapi.txt
Q: debugging in python i am using the python shell to try to do debugging i set a breakpoint i did: >>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()') but it is just running my program without stopping at the breakpoint! what am i donig wrong? A: How did you set a breakpoint? Try adding the line in...
debugging in python
i am using the python shell to try to do debugging i set a breakpoint i did: >>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()') but it is just running my program without stopping at the breakpoint! what am i donig wrong?
[ "How did you set a breakpoint? Try adding the line in your code:\nimport pdb\npdb.set_trace()\n\nand then run it. If you're in the pdb shell, then \"break foo.py:45\" will break on line 45 of file foo.py.\nHere are some useful commands:\nh help, list commands\ns step through current line\nn step to next ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003358153_python.txt
Q: Is it considered bad practice to use a widgets title attribute to refer to it? Would it be considered bad practice to use a widgets title attribute to refer it? For example I have a number of custom radioBoxCtrls on a panel I only ever need to get/set all the values at once so the container class(a panel) for ...
Is it considered bad practice to use a widgets title attribute to refer to it?
Would it be considered bad practice to use a widgets title attribute to refer it? For example I have a number of custom radioBoxCtrls on a panel I only ever need to get/set all the values at once so the container class(a panel) for the radioBoxCtrls objects has the following methods get_options() set_options() To...
[ "I can't tell whether the gurus would call it bad practive. I just know I'd never do it - it is slower, more error-prone, possibly makes it very hard to change a title's name (admittedly, only if you hardcode it everywhere) and (arguably) very inelegant. At least you should associate te options with the widget's id...
[ 2 ]
[]
[]
[ "oop", "python", "user_interface" ]
stackoverflow_0003357831_oop_python_user_interface.txt
Q: Should I use Pylon's Paste to host my Pylons website? Or can I use Apache? I'm looking into Pylons and was wondering, should I use Paste as the webserver or can I use Apache? Are there advantages to using Paste? Would you recommend against using Apache? How should I host the sites? A: I guess it depends on whet...
Should I use Pylon's Paste to host my Pylons website? Or can I use Apache?
I'm looking into Pylons and was wondering, should I use Paste as the webserver or can I use Apache? Are there advantages to using Paste? Would you recommend against using Apache? How should I host the sites?
[ "I guess it depends on whether you need webserver for development or production. For development just stick to Paste. I don't think there's one best way to host production application, but if you're not a pro in system administration, you can just go with Apache and mod_wsgi.\nBy the way, there's a great and compre...
[ 2, 0 ]
[]
[]
[ "pylons", "python", "web_services" ]
stackoverflow_0003333113_pylons_python_web_services.txt
Q: python: casting to upper and finding string i am getting stuck on this line: row[1].upper().find('CELEBREX',1) (this is returning -1) it seems to not find CELEBREX even though it is there row[1] = 'celebrex, TRAMADOL' am i casting to UPPER incorrectly? A: The second argument of find() shouldn't be 1, because it...
python: casting to upper and finding string
i am getting stuck on this line: row[1].upper().find('CELEBREX',1) (this is returning -1) it seems to not find CELEBREX even though it is there row[1] = 'celebrex, TRAMADOL' am i casting to UPPER incorrectly?
[ "The second argument of find() shouldn't be 1, because it will start search after the first character of the string.\n>>> s = 'celebrex, TRAMADOL'\n>>> print s.upper().find('CELEBREX')\n0\n\nFind() will return 0 because it found the first match at position 0, the first position in the string. So it's important to n...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003358301_python.txt
Q: Iterating variables to change its features in Python I assigned values with setattr() function in a loop: for i in range(30): for j in range(6): setattr(self, "e"+str(i)+str(j), Entry(self.top)) , then I want to apply .grid() func. to all these variables with a loop. For example, self.e00...
Iterating variables to change its features in Python
I assigned values with setattr() function in a loop: for i in range(30): for j in range(6): setattr(self, "e"+str(i)+str(j), Entry(self.top)) , then I want to apply .grid() func. to all these variables with a loop. For example, self.e00.grid(row= 0, column= 0) How can I do that?
[ "This is not the right way to go about things. Make one attribute and put all the data in it.\nimport numpy as np\nself.matrix = np.array( ( 6, 30 ), Entry( self.top ) )\n\nfor row in self.matrix:\n for elt in row:\n elt.grid( ... )\n\n", "Use getattr():\ngetattr(self, \"e00\").grid(row=0, column=0)\n\n...
[ 6, 3, 1 ]
[]
[]
[ "loops", "naming", "python", "variables" ]
stackoverflow_0003357845_loops_naming_python_variables.txt
Q: What is the best way to load a CCITT T.3 compressed tiff using python? I am trying to load a CCITT T.3 compressed tiff into python, and get the pixel matrix from it. It should just be a logical matrix. I have tried using pylibtiff and PIL, but when I load it with them, the matrix it returns is empty. I have read ...
What is the best way to load a CCITT T.3 compressed tiff using python?
I am trying to load a CCITT T.3 compressed tiff into python, and get the pixel matrix from it. It should just be a logical matrix. I have tried using pylibtiff and PIL, but when I load it with them, the matrix it returns is empty. I have read in a lot of places that these two tools support loading CCITT but not access...
[ "It seems the best way is to not use Python entirely but lean on netpbm:\nimport Image\nimport ImageFile\nimport subprocess\n\ntiff = 'test.tiff'\nim = Image.open(tiff)\nprint 'size', im.size\ntry:\n print 'extrema', im.getextrema()\nexcept IOError as e:\n print 'help!', e, '\\n'\n\nprint 'I Get by with a Lit...
[ 1, 0 ]
[]
[]
[ "compression", "image_formats", "imaging", "python", "tiff" ]
stackoverflow_0003355962_compression_image_formats_imaging_python_tiff.txt
Q: How can I create a session-local cookie-aware HTTP client in Django? I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(...
How can I create a session-local cookie-aware HTTP client in Django?
I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(myTargetService) but this doesn't pass the cookie for the current session ...
[ "Here: http://docs.python.org/library/cookielib.html#examples are examples of doing exactly what you try to do with urllib2 and cookielib. So according to docs you need to create cookielib.CookieJar, set cookie with correct data (from session), build an opener that uses your CookieJar and use it to fetch yourTarget...
[ 0 ]
[]
[]
[ "cookies", "django", "http", "python", "urllib2" ]
stackoverflow_0003358030_cookies_django_http_python_urllib2.txt
Q: Convert multiline string to single line string I'm using Google App Engine and I need to put a multiline string in the datastore. Unfortunately, GAE does not allow that. I need this string to be multiline, so is there any way to convert a multiline string to a single line string and store it? A: You don't need n...
Convert multiline string to single line string
I'm using Google App Engine and I need to put a multiline string in the datastore. Unfortunately, GAE does not allow that. I need this string to be multiline, so is there any way to convert a multiline string to a single line string and store it?
[ "You don't need no conversion:\ngoogle.appengine.ext.db.StringProperty(multiline=True)\n", "Replace all newlines with \"\\n\", and replace all \"\\\" with \"\\\\\", just like the way you do with string literals:\ndef encode(s):\n return s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\n\", \"\\\\n\")\ndef decode(...
[ 7, 0 ]
[]
[]
[ "google_app_engine", "python", "string" ]
stackoverflow_0003358426_google_app_engine_python_string.txt
Q: Pylons 1.0 and SQLAlchemy 0.6 - How do I Model? I've been reading http://pylonsbook.com/en/1.1/starting-the-simplesite-tutorial.html and following along with their SimpleSite tutorial but am having some issues with creating the Model. The Model imports they use on the tutorial are: """The application's model objec...
Pylons 1.0 and SQLAlchemy 0.6 - How do I Model?
I've been reading http://pylonsbook.com/en/1.1/starting-the-simplesite-tutorial.html and following along with their SimpleSite tutorial but am having some issues with creating the Model. The Model imports they use on the tutorial are: """The application's model objects""" import sqlalchemy as sa from sqlalchemy import ...
[ "Pylons 1.0 use declarative Base as default to model.\nexemple:\nfrom sqlalchemy import Column\nfrom sqlalchemy.types import Integer, Unicode,\nfrom MYPROJECT.model.meta import Base\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key=True)\n username = Column(Unicode(100))\n\...
[ 3, 1, 1 ]
[]
[]
[ "model", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003353755_model_pylons_python_sqlalchemy.txt
Q: Handling missing packages or DLLs in a PyQt app What's a good way to handle fatal errors - missing packages, .ui files not compiled, Qt DLLs or shared objects not found, etc. - in a PyQt app (or other Python app)? Displaying a cross-platform message box without Qt DLLs or shared objects seems like a lot of work. ...
Handling missing packages or DLLs in a PyQt app
What's a good way to handle fatal errors - missing packages, .ui files not compiled, Qt DLLs or shared objects not found, etc. - in a PyQt app (or other Python app)? Displaying a cross-platform message box without Qt DLLs or shared objects seems like a lot of work. Dumping a message to the console seems not very helpf...
[ "The distutils model handles installing a python app correctly, or there is a third party setuptools package that is even easier for end users.\n" ]
[ 1 ]
[]
[]
[ "error_handling", "installation", "package", "pyqt", "python" ]
stackoverflow_0003358759_error_handling_installation_package_pyqt_python.txt
Q: how to set up python web dev environment the set the i have so far is: windows 7 64bit Apache 2.2.14/mysql/php 5.3.1 i installed python 2.7. not configured. i tried installing mod_python but it kept telling python 2.5 is required A: Dump mod_python. It's dead, Jim.
how to set up python web dev environment
the set the i have so far is: windows 7 64bit Apache 2.2.14/mysql/php 5.3.1 i installed python 2.7. not configured. i tried installing mod_python but it kept telling python 2.5 is required
[ "Dump mod_python. It's dead, Jim.\n" ]
[ 1 ]
[]
[]
[ "apache", "python" ]
stackoverflow_0003358817_apache_python.txt
Q: Using a remote stylesheet that includes other stylesheets with relative paths I'd like to do an XSL transform on a DocBook document using lxml.etree.XSLT. Although the documentation mentions that etree.XSLT() takes a first parameter of xslt_input, I can't seem to find any docs on what this parameter is meant to be...
Using a remote stylesheet that includes other stylesheets with relative paths
I'd like to do an XSL transform on a DocBook document using lxml.etree.XSLT. Although the documentation mentions that etree.XSLT() takes a first parameter of xslt_input, I can't seem to find any docs on what this parameter is meant to be. Passing it a file that is open for reading seems to work; passing it a filename ...
[ "This is actually dead easy, I just had mental indigestion, and forgot that there was that all-important intermediate step of parsing the XSL stylesheet. It's at that point that you let it know the base URL for the stylesheet.\nIf you grab the stylesheet from an URL, it just deducts it from the URL. I didn't real...
[ 1, 0 ]
[]
[]
[ "docbook", "lxml", "python", "xslt" ]
stackoverflow_0003358481_docbook_lxml_python_xslt.txt
Q: How can I get html content from a browser that can do the html correction and js scripting? I need a solution for getting HTML content from a browser. As rendering in a browser, js will be ran, and if not, js won't be ran. So any html libraries like lxml, beautifulsoup and others are all not gonna work. I've searc...
How can I get html content from a browser that can do the html correction and js scripting?
I need a solution for getting HTML content from a browser. As rendering in a browser, js will be ran, and if not, js won't be ran. So any html libraries like lxml, beautifulsoup and others are all not gonna work. I've searched a project named pywebkitgtk, but it's purpose is to create a browser with a front end. Is the...
[ "selenium-rc lets you drive an actual browser for your purpose, under control of any of several languages at your choice, which include both Python and Java. Check it out!\nFor a detailed example of use with Python, see here.\n" ]
[ 3 ]
[]
[]
[ "browser", "java", "python" ]
stackoverflow_0003359141_browser_java_python.txt
Q: A forgiving dictionary I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] In order not to get one I would 1. Have to catch the exception or use get. I...
A forgiving dictionary
I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] In order not to get one I would 1. Have to catch the exception or use get. I would like to not to have t...
[ "import collections\na = collections.defaultdict(lambda: 3)\na.update({'one':1,'two':2})\nprint a['three']\n\nemits 3 as required. You could also subclass dict yourself and override __missing__, but that doesn't make much sense when the defaultdict behavior (ignoring the exact missing key that's being looked up) s...
[ 22, 7, 6, 3, 0 ]
[]
[]
[ "defaultdict", "dictionary", "dictionary_missing", "python" ]
stackoverflow_0003358580_defaultdict_dictionary_dictionary_missing_python.txt
Q: How can I remove all elements matching an xpath in python using lxml? So I have some XML like this: <bar> <foo>Something</foo> <baz> <foo>Hello</foo> <zap>Another</zap> <baz> <bar> And I want to remove all the foo nodes. Something like this doesn't work params = xml.xpath('//foo') for n in params:...
How can I remove all elements matching an xpath in python using lxml?
So I have some XML like this: <bar> <foo>Something</foo> <baz> <foo>Hello</foo> <zap>Another</zap> <baz> <bar> And I want to remove all the foo nodes. Something like this doesn't work params = xml.xpath('//foo') for n in params: xml.getroot().remove(n) Giving ValueError: Element is not a child of th...
[ "try:\n for elem in xml.xpath( '//foo' ) :\n elem.getparent().remove(elem)\n\nremove it from it's parent, not the root \n( unless it IS a child of the root element )\n" ]
[ 21 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003359151_lxml_python.txt
Q: GUI in python programing the fallowing is a tic tak toe game code in python, can some one show me how i can make it in GUI form with a reset option and shows who wins at the end. like X win or O win? board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9" . checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8...
GUI in python programing
the fallowing is a tic tak toe game code in python, can some one show me how i can make it in GUI form with a reset option and shows who wins at the end. like X win or O win? board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9" . checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8,3,6,9,1,5,9,3,5,7] spaces=ran...
[ "Clearly you need to choose a GUI toolkit (Python supports many of them), use it to paint the board as a 3 x 3 grid of squares, and change the playerinput function to accept input by (e.g.) the current player double clicking on the empty square he or she wants to play in.\nThen, you need to change the print stateme...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003359289_python.txt
Q: How to create a table and its related model.py automatically from a csv file in Django Think of this: You create a CMS of some sort, which asks you for an application name and a csv file for that application. Then it automatically creates that app on the fly, creates the required model.py based on the csv columns,...
How to create a table and its related model.py automatically from a csv file in Django
Think of this: You create a CMS of some sort, which asks you for an application name and a csv file for that application. Then it automatically creates that app on the fly, creates the required model.py based on the csv columns, activates the admin page for it and allows only you to have the full permission to this new...
[ "While this does not involve creating an actual models.py and application, you may want to look into dynamically creating Model classes at runtime. You could have \"meta\" models that store the information on the dynamic models, and then have your CSV view import the data into those models, create the classes, and ...
[ 0 ]
[]
[]
[ "csv", "django", "django_admin", "django_models", "python" ]
stackoverflow_0003359336_csv_django_django_admin_django_models_python.txt
Q: Python string split what would be the best way to split this in python. (address, city, state, zip) <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div> in some case zip code is as <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634</div> A: Depending on how tight or lax you want to...
Python string split
what would be the best way to split this in python. (address, city, state, zip) <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div> in some case zip code is as <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634</div>
[ "Depending on how tight or lax you want to be on various aspects that can't be deduced from a single example, something like the following should work...:\nimport re\n\ns = re.compile(r'^<div.*?>([^<]+)<br.*?>([^,]+), (\\w\\w) (\\d{5}-\\d{4})</div>$')\nmo = s.match(thestring)\nif mo is None:\n raise ValueError('No...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003359614_python.txt
Q: pydev eclipse configuration for __builtins__? suppose on init I've install my function under builtins then throughout my project I can access it directly that function, no need to import, but how can I tell this to eclipse - so it should not show RED Error "undefined variable" __builtins__['_'] = gettext.gettext ...
pydev eclipse configuration for __builtins__?
suppose on init I've install my function under builtins then throughout my project I can access it directly that function, no need to import, but how can I tell this to eclipse - so it should not show RED Error "undefined variable" __builtins__['_'] = gettext.gettext
[ "Look in Preferences -> PyDev -> Editor -> Code Analysis. There's a bunch of options for adjusting code analysis in there. \nOn my PyDev, _ is already in the Consider the following names as globals list though - which version of PyDev do you have? \n" ]
[ 2 ]
[]
[]
[ "built_in", "configuration", "eclipse", "python" ]
stackoverflow_0003359697_built_in_configuration_eclipse_python.txt
Q: Removing values from a list in python I have a large file of names and values on a single line separated by a space: name1 name2 name3.... Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the ...
Removing values from a list in python
I have a large file of names and values on a single line separated by a space: name1 name2 name3.... Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na. ...
[ "Let's say you read the names into one list, then the values into another. Once you have a names and values list, you can do something like:\nresult = [n for n, v in zip(names, values) if v != 'na']\n\nresult is now a list of all names whose value is not \"na\".\n", "s = \"name1 name2 name3 v1 na v2\"\ns = s.spl...
[ 5, 4, 1, 1, 0, 0 ]
[]
[]
[ "python", "text_parsing" ]
stackoverflow_0003356460_python_text_parsing.txt
Q: String search in mysqltable using python I want to search the matching strings from a mysql table. The search string is not a correct sentence, its only a part of the sentence.Any one can help me.? Thanks in advance... Nimmy A: Something like this? SELECT * FROM table WHERE string LIKE '%substring%' http://dev....
String search in mysqltable using python
I want to search the matching strings from a mysql table. The search string is not a correct sentence, its only a part of the sentence.Any one can help me.? Thanks in advance... Nimmy
[ "Something like this?\nSELECT * FROM table WHERE string LIKE '%substring%'\n\nhttp://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003360263_mysql_python.txt
Q: How to simulate clicks on text using python? I want to simulate such clicks without controlling web browsers to do the job. I don't know much about javascript and actually don't know where to start. Any ideas? A: Althoug I have no use it, I think that maybe twill is what you need: twill: a simple scripting lan...
How to simulate clicks on text using python?
I want to simulate such clicks without controlling web browsers to do the job. I don't know much about javascript and actually don't know where to start. Any ideas?
[ "Althoug I have no use it, I think that maybe twill is what you need:\n\ntwill: a simple scripting language for Web browsing\n\nHave a look at this too:\n\nTesting Web Applications with Python and Twill\n\n", "You can use iMacros in combination with Python... \nThis isn't the most direct solution as it requires y...
[ 1, 0, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0003334278_javascript_python.txt
Q: python : read a line, then instantiate a class named in the line I'm sorry if I wasn't clear enough in the title, don't hesitate to correct it if you find a better way to express that: I have a file where there are class names, i.e.: classa classb classb classc classc classc Then I want to read it line by line an...
python : read a line, then instantiate a class named in the line
I'm sorry if I wasn't clear enough in the title, don't hesitate to correct it if you find a better way to express that: I have a file where there are class names, i.e.: classa classb classb classc classc classc Then I want to read it line by line and to dynamically create that class. I would do something like that in ...
[ "Assuming your classes are already in scope (i.e. they're not in a separate module), you can refer to a class by its name very easily through the globals() dict. For example:\nclass Foo:\n pass\n\nfoo_cls = globals()['Foo']\nfoo = foo_cls()\n# foo is now an instance of __main__.Foo\n\n", "The other answers do...
[ 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "dynamic", "python" ]
stackoverflow_0003357693_dynamic_python.txt
Q: Python: Locate 3 adjacent list items and determine list index of first of them I need to process weather station data which is in a format like this (SYNOP), where each line represents one measurement and I have thousands of measurements: line = 'AAXX 01004 60265 32970 03404 10048 20010 38997 48605 51014=' Starti...
Python: Locate 3 adjacent list items and determine list index of first of them
I need to process weather station data which is in a format like this (SYNOP), where each line represents one measurement and I have thousands of measurements: line = 'AAXX 01004 60265 32970 03404 10048 20010 38997 48605 51014=' Starting with the 6th block, the blocks are numbered (1xxxx 2xxxx 3xxxx etc, sometimes onl...
[ "There is more than one way to do this. One way would be to search the list for the index and subtract two:\nlist[ (i for i, j in enumerate( list ) if j.startswith( \"1\" ) ).next() - 2 ]\n\nAnother way would be to match a regex onto the (unsplit) string:\nimport re\nre.search( \"\\d{5}(?= \\d{5} 1\\d{4} 2\\d{4} 3\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003360447_python.txt
Q: Python: multiple files download by turn In script loop performs files downloading and saving (curl). But loop iterations too quick, so downloading and saving actions have no time to complete it's operations. Thereat result files comes broken def get_images_thread(table): class LoopThread ( threading.Thread ):...
Python: multiple files download by turn
In script loop performs files downloading and saving (curl). But loop iterations too quick, so downloading and saving actions have no time to complete it's operations. Thereat result files comes broken def get_images_thread(table): class LoopThread ( threading.Thread ): def run ( self ): global...
[ "This is an excerpt from the examples for the PycURL library,\n# Make a queue with (url, filename) tuples\nqueue = Queue.Queue()\nfor url in urls:\n url = url.strip()\n if not url or url[0] == \"#\":\n continue\n filename = \"doc_%03d.dat\" % (len(queue.queue) + 1)\n queue.put((url, filename))\n\...
[ 4 ]
[ "If you're asking what I think you're asking, \nfrom time import sleep\nsleep(1)\n\nshould \"solve\"(It's hacky to the max!) your problem. Docs here. I would check that that really is your problem, though. It seems catastrophically unlikely that pausing for a few seconds would stop files from downloading brokenly. ...
[ -1 ]
[ "python" ]
stackoverflow_0003359929_python.txt
Q: Simple list comprehension I want a dictionary of files: files = [files for (subdir, dirs, files) in os.walk(rootdir)] But I get, files = [['filename1', 'filename2']] when I want files = ['filename1', 'filename2'] How do I prevent looping through that tuple? Thanks! A: Both of these work: [f for (subdir, dir...
Simple list comprehension
I want a dictionary of files: files = [files for (subdir, dirs, files) in os.walk(rootdir)] But I get, files = [['filename1', 'filename2']] when I want files = ['filename1', 'filename2'] How do I prevent looping through that tuple? Thanks!
[ "Both of these work:\n[f for (subdir, dirs, files) in os.walk(rootdir) for f in files]\n\nsum([files for (subdir, dirs, files) in os.walk(rootdir)], [])\n\nSample output:\n$ find /tmp/test\n/tmp/test\n/tmp/test/subdir1\n/tmp/test/subdir1/file1\n/tmp/test/subdir2\n/tmp/test/subdir2/file2\n$ python\n>>> import os\n>>...
[ 7, 2, 2, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003326428_list_comprehension_python.txt
Q: Crawl Images, Whole Web Pages and cache them I am starting a project and wonder the relationship between the characters in images and the whole web page where the images reside. I want to crawl some images and their web pages. I need to save the crawl result in local disk for further analysis. I wonder if there is...
Crawl Images, Whole Web Pages and cache them
I am starting a project and wonder the relationship between the characters in images and the whole web page where the images reside. I want to crawl some images and their web pages. I need to save the crawl result in local disk for further analysis. I wonder if there is any open source for this issue?
[ "Here's a list of open source crawlers\nhttp://www.google.co.uk/#hl=en&source=hp&q=open+source+web+crawler&aq=f&aqi=g9g-m1&aql=&oq=&gs_rfai=&fp=77130048d7e0701a\nNear top of the list are Java crawlers, and the Wikipedia article has some more as well\n", "You can use crawler4j for this purpose. It is a simple java...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003052348_python.txt
Q: Dynamically Created Top Articles List in Django? I'm creating a Django-powered site for my newspaper-ish site. The least obvious and common-sense task that I have come across in getting the site together is how best to generate a "top articles" list for the sidebar of the page. The first thing that came to mind w...
Dynamically Created Top Articles List in Django?
I'm creating a Django-powered site for my newspaper-ish site. The least obvious and common-sense task that I have come across in getting the site together is how best to generate a "top articles" list for the sidebar of the page. The first thing that came to mind was some sort of database column that is updated (based...
[ "I would give celery a try (with django-celery). While it's not so easy to configure and use as cache, it enables you to queue tasks like incrementing counters and do them in background. It could be even combined with cache technique - in views increment counters in cache and define PeriodicTask that will run every...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003359214_django_mysql_python.txt
Q: How do I get the stack trace from an Exception Object in Python? How can I get the full stack trace from the Exception object itself? Consider the following code as reduced example of the problem: last_exception = None try: raise Exception('foo failed') except Exception as e: last_exception = e # this happ...
How do I get the stack trace from an Exception Object in Python?
How can I get the full stack trace from the Exception object itself? Consider the following code as reduced example of the problem: last_exception = None try: raise Exception('foo failed') except Exception as e: last_exception = e # this happens somewhere else, decoupled from the original raise print_exception_...
[ "Edit: I lied, sorry. e.__traceback__ is what you want.\ntry:\n raise ValueError\nexcept ValueError as e:\n print( e.__traceback__ )\n\n>c:/python31/pythonw -u \"test.py\"\n<traceback object at 0x00C964B8>\n>Exit code: 0\n\nThis is only valid in Python 3; you can't do it in earlier versions.\n" ]
[ 3 ]
[]
[]
[ "exception_handling", "python", "stack_trace" ]
stackoverflow_0003361853_exception_handling_python_stack_trace.txt
Q: How to parse RSS link (get ulr to RSS) from the page in Python framework Scrapy? I want to parse Google search and get links to RSS from each item from the search results. I use Scrapy. I tried this construction, ... def parse_second(self, response): hxs = HtmlXPathSelector(response) qqq = hxs.select('/h...
How to parse RSS link (get ulr to RSS) from the page in Python framework Scrapy?
I want to parse Google search and get links to RSS from each item from the search results. I use Scrapy. I tried this construction, ... def parse_second(self, response): hxs = HtmlXPathSelector(response) qqq = hxs.select('/html/head/link[@type=application/rss+xml]/@href').extract() print qqq item = re...
[ "Found a mistake:\nqqq = hxs.select(\"/html/head/link[@type='application/rss+xml']/@href\").extract()\n\nthat works\n" ]
[ 1 ]
[]
[]
[ "parsing", "python", "rss", "scrapy", "xpath" ]
stackoverflow_0003362133_parsing_python_rss_scrapy_xpath.txt
Q: Is there a faster way to get subtrees from tree like structures in python than the standard "recursive"? Let's assume the following data structur with three numpy arrays (id, parent_id) (parent_id of the root element is -1): import numpy as np class MyStructure(object): def __init__(self): """ Default st...
Is there a faster way to get subtrees from tree like structures in python than the standard "recursive"?
Let's assume the following data structur with three numpy arrays (id, parent_id) (parent_id of the root element is -1): import numpy as np class MyStructure(object): def __init__(self): """ Default structure for now: 1 / \ 2 3 / \ 4 5 """ self.ids =...
[ "Have you tried to use psyco module if you are using Python 2.6? It can sometimes do dramatic speed up of code.\nHave you considered recursive data structure: list?\nYour example is also as standard list:\n\n[1, 2, [3, [4],[5]]]\n\nor\n\n[1, [2, None, None], [3, [4, None, None],[5, None, None]]]\n\nBy my pretty pri...
[ 4, 4, 3, 0 ]
[]
[]
[ "python", "subtree", "tree" ]
stackoverflow_0003350413_python_subtree_tree.txt
Q: What libraries for modeling complex questionaire in Python? For a medical website I'm trying to model a questionnaire that should result in a range of possible diagnoses. The questionnaire is fairly complex with a lot of conditionals. I made a flowchart/decision tree to reflect this questionnaire. I'm using Django...
What libraries for modeling complex questionaire in Python?
For a medical website I'm trying to model a questionnaire that should result in a range of possible diagnoses. The questionnaire is fairly complex with a lot of conditionals. I made a flowchart/decision tree to reflect this questionnaire. I'm using Django to make the website. Currently I'm thinking of using Python Grap...
[ "You are modelling a deterministic finite-state automaton. Have a look at python-automata.\n" ]
[ 2 ]
[]
[]
[ "decision_tree", "django", "python" ]
stackoverflow_0003362034_decision_tree_django_python.txt
Q: subprocess unable to capture STDOUT - what could be program be doing? I have this program, which when executed on the console like this: prog 1> output 2> error Has the valid output and error. However, when I execute the same program using the subprocess module. p = subprocess.Popen(['prog'],stdout=PIPE, stderr=...
subprocess unable to capture STDOUT - what could be program be doing?
I have this program, which when executed on the console like this: prog 1> output 2> error Has the valid output and error. However, when I execute the same program using the subprocess module. p = subprocess.Popen(['prog'],stdout=PIPE, stderr=PIPE,close_fds=True) out, err = p.communicate() The out is empty but err i...
[ "Are you trying this on Windows?\nThe use of close_fds is\nplatform dependent, according to the subprocess.Popen() doc.\n\nIf close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inher...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003359590_python.txt
Q: How to organise the file structure of my already working plugin system? I am working on a project whose main design guiding principle is extensibility. I implemented a plugin system by defining a metaclass that register - with a class method - the class name of any plugin that gets loaded (each type of plugin inhe...
How to organise the file structure of my already working plugin system?
I am working on a project whose main design guiding principle is extensibility. I implemented a plugin system by defining a metaclass that register - with a class method - the class name of any plugin that gets loaded (each type of plugin inherit from a specific class defined in the core code, as there are different ty...
[ "The question is hard to address, because the needs are complex.\nAnyway I will try with some suggestions.\nAbout\n\nPlacing plugins in two different\n locations: is there a standard way /\n best practice (under gnu/linux, at\n least) to do that?\n\nA good approach is virtualenv. Virtualenv is a python module to...
[ 3, 1 ]
[]
[]
[ "file_management", "introspection", "plugins", "python", "software_design" ]
stackoverflow_0003360102_file_management_introspection_plugins_python_software_design.txt
Q: Is Python good for writing standard, compatible and complete SOAP web services? I have used few python soap libraries (SOAPpy, soaplib and Twisted wrapper around SOAPpy) to write my soap web service. When I used python clients (SOAPpy.SOAPProxy and SUDS), I was able to communicate with my web service (returning si...
Is Python good for writing standard, compatible and complete SOAP web services?
I have used few python soap libraries (SOAPpy, soaplib and Twisted wrapper around SOAPpy) to write my soap web service. When I used python clients (SOAPpy.SOAPProxy and SUDS), I was able to communicate with my web service (returning simple and complex type objects). But, when I tried with C# ASP.net, I got many issues....
[ "In my personal opinion, the compatibility of Python SOAP libraries with other platforms is not good.\nI think that there are two issues here:\n\nFirst, the compatibility of web services among web service stacks is an aspiration rather than reality. For example, look at this question to see how to use web services ...
[ 1 ]
[]
[]
[ "c#", "python", "soap", "twisted" ]
stackoverflow_0003358792_c#_python_soap_twisted.txt
Q: Django: limiting model data I'm searching in a way to limit the queryset which I can get through a model. Suppose I have the following models (with dependencies): Company |- Section | |- Employee | |- Task | `- more models... |- Customer | |- Contract | |- Accounts | `- other great models ... ...
Django: limiting model data
I'm searching in a way to limit the queryset which I can get through a model. Suppose I have the following models (with dependencies): Company |- Section | |- Employee | |- Task | `- more models... |- Customer | |- Contract | |- Accounts | `- other great models ... `- some more models... It should...
[ "I solved it the following way:\nFirst I've created a CurrentCompanyManager.\nclass CurrentCompanyManager(models.Manager):\n def __init__(self,field,*args,**kwargs):\n super(CurrentCompanyManager,self).__init__(*args,**kwargs)\n self.__field_name = field\n\n def on(self,company):\n return...
[ 1, 0 ]
[]
[]
[ "database_design", "django", "django_models", "python" ]
stackoverflow_0003331310_database_design_django_django_models_python.txt
Q: mplot3d in wxPython frame I'm writing an application in wxPython. The button "Plot" shows the wxFrame with 3D surface but I can't rotate the surface. Is it possible to rotate a 3D plot placed in a wxFrame? How can I do? Example: import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg impor...
mplot3d in wxPython frame
I'm writing an application in wxPython. The button "Plot" shows the wxFrame with 3D surface but I can't rotate the surface. Is it possible to rotate a 3D plot placed in a wxFrame? How can I do? Example: import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCa...
[ "You'd probably be better off asking on the wxPython google group since I've seen people on there using matplotlib. Anyway, looking at the matplotlib website, it appears that there is a wxMpl module that might help: http://agni.phys.iit.edu/~kmcivor/wxmpl/\nMy guess is, if matplotlib can rotate the plot outside of ...
[ 3 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0003362292_matplotlib_python_wxpython.txt
Q: Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation? >>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid sy...
Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?
>>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value ...
[ "Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead:\nfor i in range(0,len(a),2):\n a[i] = 3\n\nApart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and comple...
[ 26, 9, 3, -1 ]
[]
[]
[ "list_comprehension", "python", "side_effects", "variable_assignment" ]
stackoverflow_0003362413_list_comprehension_python_side_effects_variable_assignment.txt
Q: Looking for online Judge Engine that support Python I am writing a website which intends to be a place for use to paste/answer coding questions. Especially Python. So, I am looking for an "online judge" engine that could support Python(c/c++/java/# could be a plus), so that the guy who paste the question could pro...
Looking for online Judge Engine that support Python
I am writing a website which intends to be a place for use to paste/answer coding questions. Especially Python. So, I am looking for an "online judge" engine that could support Python(c/c++/java/# could be a plus), so that the guy who paste the question could provide a simple test, then others could answer it with the ...
[ "The Sphere Online Judge supports Python.\nThe questions from the old Google Codejam, along with the problems at Project Euler are both language independent, and are helpful for practicing in any language.\n", "You can use Ideone API - free for non commercial apps.\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001253376_python.txt
Q: Clustering after minimum spanning tree cut What would be the optimal way of clustering nodes after cutting a MST with a maximum edge-length? My output from MST edge-length cut is a 2xN array where each element is an integer. The integers are the node identifiers that describe the edges. An example of the output wo...
Clustering after minimum spanning tree cut
What would be the optimal way of clustering nodes after cutting a MST with a maximum edge-length? My output from MST edge-length cut is a 2xN array where each element is an integer. The integers are the node identifiers that describe the edges. An example of the output would is given below: >>> print array[0:3] [[ 0 ...
[ "The problem has been solved. Go to the NetworkX google group link to see the solution. \nhttp://groups.google.com/group/networkx-discuss/browse_thread/thread/4ac4250d460a1b75\nCheers,\nEli\n" ]
[ 0 ]
[]
[]
[ "graph", "intersection", "python", "union" ]
stackoverflow_0003176963_graph_intersection_python_union.txt
Q: Is all I need the "identity url"? - OpenID I'm just wondering if all I need is the identity url in order to to theoretically attach an OpenID account to a user's account. I have identity urls that look like the following: https://www.google.com/accounts/o8/id?id=YGnyuGHMUmhUI98nuhUMhu98nuN. Is this different betwe...
Is all I need the "identity url"? - OpenID
I'm just wondering if all I need is the identity url in order to to theoretically attach an OpenID account to a user's account. I have identity urls that look like the following: https://www.google.com/accounts/o8/id?id=YGnyuGHMUmhUI98nuhUMhu98nuN. Is this different between OpenID 1.0 and 2.0? Just in case someone asks...
[ "All you need to bind to a user account is the \"Claimed Identifier\" which is what the sample URL you provided is called. OpenID 1.x and 2.0 have a handful of URLs it deals with, including \"openid.identity\" and \"openid.claimed_id\" values. It is very important that you're reading from the property that gives ...
[ 2 ]
[]
[]
[ "authentication", "django", "google_openid", "openid", "python" ]
stackoverflow_0003363781_authentication_django_google_openid_openid_python.txt
Q: Color in python? Possible Duplicate: Print in terminal with colors using python ? hello guys did i can do like C# in console? to make print 'hello' write hello with green color and print 'WOW am sexy' write it with red color? A: Previously: Print in terminal with colors using Python? http://pypi.python...
Color in python?
Possible Duplicate: Print in terminal with colors using python ? hello guys did i can do like C# in console? to make print 'hello' write hello with green color and print 'WOW am sexy' write it with red color?
[ "Previously: \n\nPrint in terminal with colors using Python?\nhttp://pypi.python.org/pypi/termcolor\nhttp://docs.python.org/library/curses.html#curses.can_change_color\nhttp://en.wikipedia.org/wiki/ANSI_escape_code\n\n", "colorama\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003363320_python.txt
Q: Best practices for doing accounting in Python I am writing a web2py application that requires summing dollar amounts without losing precision. I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with: Decimal(str(myval)) Before I go crazy add...
Best practices for doing accounting in Python
I am writing a web2py application that requires summing dollar amounts without losing precision. I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with: Decimal(str(myval)) Before I go crazy adding that to all of my code, is there a better way? ...
[ "First, keep all numbers in decimal form in the database -- you don't mention what DB engine you're using, but every engine supports such functionality, e.g., here is MySQL's DECIMAL type documentation. I hope you're already doing that, but, if you aren't, it's still worth the pain of a schema change.\nThen, you n...
[ 8, 0 ]
[]
[]
[ "accounting", "currency", "decimal", "freetds", "python" ]
stackoverflow_0003364699_accounting_currency_decimal_freetds_python.txt
Q: How do I create / access dynamic form fields in Django from within a View? I have a system which keeps lots of "records" and need to integrate a component which will produce reports of any selected records. To the user, it looks like this: Click "Create Report" Select the records to be included in the report. Hit...
How do I create / access dynamic form fields in Django from within a View?
I have a system which keeps lots of "records" and need to integrate a component which will produce reports of any selected records. To the user, it looks like this: Click "Create Report" Select the records to be included in the report. Hit "Submit" and the report is displayed. To me I think: Load all records. Create...
[ "If I understand your question correctly, your answer lies in using the proper Django form widgets. I will give you an example. Let's say you have a Django model: - \nclass Record(models.Model):\n name = models.CharField()\n\nLet's say you create a custom Form for your needs: - \nclass MyCustomForm(forms.Form):\...
[ 1 ]
[]
[]
[ "django", "dynamic", "forms", "python", "views" ]
stackoverflow_0003358935_django_dynamic_forms_python_views.txt
Q: python: if row[1].upper().find(brand)!=-1: are these two statements equivalent? if row[1].upper().find(brand)!=-1: and if row[1].upper().find(brand): A: No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -...
python: if row[1].upper().find(brand)!=-1:
are these two statements equivalent? if row[1].upper().find(brand)!=-1: and if row[1].upper().find(brand):
[ "No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -1, and false if the expression evaluates to 0 (when it should be true).\nUse the first statement.\n", "As others have said, no those statements are not eq...
[ 8, 5, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003364106_python.txt
Q: images API / Error I'm working on a project and I used the the Images Python API . For instance in the example given in http://code.google.com/appengine/docs/python/images/usingimages.html I get an error when ever I do not upload a photo, How can I modify the code so I don't get an error when I don't post anythi...
images API / Error
I'm working on a project and I used the the Images Python API . For instance in the example given in http://code.google.com/appengine/docs/python/images/usingimages.html I get an error when ever I do not upload a photo, How can I modify the code so I don't get an error when I don't post anything. thanks
[ "Try changing the line\navatar = images.resize(self.request.get(\"img\"), 32, 32)\n\nto check if self.request.get(\"img\") is empty:\nposted_avatar = self.request.get(\"img\")\nif posted_avatar:\n avatar = images.resize(posted_avatar, 32, 32)\n greeting.avatar = db.Blob(avatar)\n\ngreeting.put()\n\n", "You can ...
[ 2, 1 ]
[]
[]
[ "api", "google_app_engine", "image", "python" ]
stackoverflow_0003365430_api_google_app_engine_image_python.txt
Q: twisted web getPage, 2 clients in 2 classes, manage events between the two i'm trying to create a bridge program in twisted.web that receives data from a web server and sends it to another server, thus i'm using 2 getPage applications that i have wrapped in a class for convenience, the class contains all the callb...
twisted web getPage, 2 clients in 2 classes, manage events between the two
i'm trying to create a bridge program in twisted.web that receives data from a web server and sends it to another server, thus i'm using 2 getPage applications that i have wrapped in a class for convenience, the class contains all the callbacks and the client "routine".. 1)auth 2)receive data 3)send data, all this is d...
[ "\nHow can I make callbacks outside the class?\n\nThis sounds like a very common misunderstanding. As a result of the misunderstanding, the question, as asked, doesn't make a lot of sense. So let's forget about the question.\nYou already have some code that's using Deferreds. Let's start with mainmyServ:\ndef ma...
[ 2 ]
[]
[]
[ "client", "http", "python", "twisted", "twisted.web" ]
stackoverflow_0003360819_client_http_python_twisted_twisted.web.txt
Q: Doing an XSL transform of a branch of a Docbook element tree I'd like to use the docbook XSL stylesheets to render various parts of a document, without transforming the entire thing. The complication is that some of these parts have <footnoteref> elements whose linkend attributes are not located within the same ch...
Doing an XSL transform of a branch of a Docbook element tree
I'd like to use the docbook XSL stylesheets to render various parts of a document, without transforming the entire thing. The complication is that some of these parts have <footnoteref> elements whose linkend attributes are not located within the same chunk. In other words, I want to process a branch of the tree which...
[ "Instead of trying to apply the DocBook XSL stylesheet to a single element, you could apply it to the full document, but specify the part of the document you want to transform with the rootid parameter. \nFrom the reference documentation:\n\nThe entire document will be loaded and\n parsed, but formatting will begi...
[ 0 ]
[]
[]
[ "docbook", "lxml", "python", "xslt" ]
stackoverflow_0003359335_docbook_lxml_python_xslt.txt
Q: What's wrong with my Python installation? I downloaded and installed Python 3.1.2 on Windows 7 x64. But it seems that it's not working as expected. What's wrong here? A: Try this: >>> print "Today's stock price: %f" % 50.4625 File "<stdin>", line 1 print "Today's stock price: %f" % 50.4625 ...
What's wrong with my Python installation?
I downloaded and installed Python 3.1.2 on Windows 7 x64. But it seems that it's not working as expected. What's wrong here?
[ "Try this:\n>>> print \"Today's stock price: %f\" % 50.4625\n File \"<stdin>\", line 1\n print \"Today's stock price: %f\" % 50.4625\n ^\nSyntaxError: invalid syntax\n>>> print(\"Today's stock price: %f\" % 50.4625)\nToday's stock price: 50.462500\n\nPython 3.X changed how print...
[ 8, 4, 1, 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0003340775_installation_python.txt
Q: How to throw an error window in Python in Windows What's the easiest way to generate an error window for a Python script in Windows? Windows-specific answers are fine; please don't reply how to generate a custom Tk window. A: @Constantin is almost correct, but his example will produce garbage text. Make sure th...
How to throw an error window in Python in Windows
What's the easiest way to generate an error window for a Python script in Windows? Windows-specific answers are fine; please don't reply how to generate a custom Tk window.
[ "@Constantin is almost correct, but his example will produce garbage text. Make sure that the text is unicode. I.e., \nctypes.windll.user32.MessageBoxW(0, u\"Error\", u\"Error\", 0)\n\n...and it'll work fine.\n", "If you need a GUI error message, you could use EasyGui:\n>>> import easygui as e\n>>> e.msgbox(\"A...
[ 12, 3, 2, 1, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003365673_python_windows.txt
Q: Custom user authentication. How is it done, with the best practices? I'm using Google Engine App with Python. I want to add custom user authentication. How is it done, with the best practices? I want custom authentication because the app is built in Flex and I don't want to redirect to an HTML page. The user value...
Custom user authentication. How is it done, with the best practices?
I'm using Google Engine App with Python. I want to add custom user authentication. How is it done, with the best practices? I want custom authentication because the app is built in Flex and I don't want to redirect to an HTML page. The user value object is like this: class User(db.Model): email = db.EmailProperty(re...
[ "Passwords:\nThe best way to handle the password is store a random salt value for each user and the result of a hash of the password + salt. \nWhen the user wants to login, compute hash(password + salt) and see it if is the same as the hash value you stored when the password was originally set. The idea is never ...
[ 3, 1 ]
[]
[]
[ "apache_flex", "authentication", "google_app_engine", "python" ]
stackoverflow_0003346265_apache_flex_authentication_google_app_engine_python.txt
Q: Add elements in a list of dictionaries I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are...
Add elements in a list of dictionaries
I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to ...
[ "Here are some microbenchmarks which suggest f2 (see below) might be an improvement. f2 uses iteritems which allows you avoid an extra dict lookup in the inner loop:\nimport collections\nimport string\nimport random\n\ndef random_dict():\n n=random.randint(1,26)\n keys=list(string.letters)\n random.shuffle...
[ 9, 1, 1, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0003366170_dictionary_nested_python.txt
Q: Eclipse and PyDev I want to start using Eclipse with the PyDev plugin, as recommended by this poster. The PyDev download page says I need Eclipse (3.2 to 3.5) and that I can use the Platform Runtime Binary. Can I also use Eclipse 3.5.2 (or maybe even 3.6) instead of 3.5? Where can I find the Platform Runtime Bi...
Eclipse and PyDev
I want to start using Eclipse with the PyDev plugin, as recommended by this poster. The PyDev download page says I need Eclipse (3.2 to 3.5) and that I can use the Platform Runtime Binary. Can I also use Eclipse 3.5.2 (or maybe even 3.6) instead of 3.5? Where can I find the Platform Runtime Binary? I'm a little bit ...
[ "Yes I use eclipse 3.5.2 with pydev plugin and it works great. Install the pydev plugin by opening up Help / Install New Software and putting in \"Pydev - http://pydev.org/updates\" into the Work with field. Then follow on the installation procedure. After pydev is installed make sure that you put the python interp...
[ 1, 1, 0 ]
[]
[]
[ "eclipse", "installation", "pydev", "python", "versions" ]
stackoverflow_0003361468_eclipse_installation_pydev_python_versions.txt
Q: Unbuffered stdout in python (as in python -u) from within the program Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on Linux (Ubuntu 8.10 Server). A: The best I could come ...
Unbuffered stdout in python (as in python -u) from within the program
Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on Linux (Ubuntu 8.10 Server).
[ "The best I could come up with:\n>>> import os\n>>> import sys\n>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)\n>>> unbuffered.write('test')\ntest>>> \n>>> sys.stdout = unbuffered\n>>> print 'test'\ntest\n\nTested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it ...
[ 52, 37, 9, 8 ]
[]
[]
[ "python" ]
stackoverflow_0000881696_python.txt
Q: Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile? I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap. I need a library that let me add circles or circular arc to ...
Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile?
I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap. I need a library that let me add circles or circular arc to it. The library could be in for Python or in Java.
[ "If you look at OpenMap, it may be possible to write some code using that set of libraries in Java to do what you are asking.\nI don't know if its possible from a single call, but there is definitely code in OpenMap to generate circles and arcs and it also has code to read in a shapefile. The jump to exporting a s...
[ 1, 0 ]
[]
[]
[ "arcgis", "esri", "java", "python", "shapefile" ]
stackoverflow_0000853311_arcgis_esri_java_python_shapefile.txt
Q: escape characters in psycopg2 how do i escape special characters for to_tsquery in psycopg2 python? A: I suggest you build your own parser.
escape characters in psycopg2
how do i escape special characters for to_tsquery in psycopg2 python?
[ "I suggest you build your own parser.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0003364815_postgresql_psycopg2_python.txt
Q: arranging for python's sorted(set( )) I'm trying to eliminate duplicates of an array containing a few thousands of custom objects. For this I'm implementing the __hash__ and __cmp__ functions for these objects. Is it safe to delegate these functions to one of the objects' fields (a guaranteed unique string) ? I.e...
arranging for python's sorted(set( ))
I'm trying to eliminate duplicates of an array containing a few thousands of custom objects. For this I'm implementing the __hash__ and __cmp__ functions for these objects. Is it safe to delegate these functions to one of the objects' fields (a guaranteed unique string) ? I.e. class A: def __init__(self, key, etc...
[ "Yes. The only requirement of __hash__ is that it be unique. In fact, this is quite an elegant and Pythonic way of solving the problem!\nEDIT: It has been pointed out to me that __hash__ need not even be unique! Instead, one simply requires equal objects to have the same hash. Unequal ones may also have the same ha...
[ 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003366435_python.txt
Q: Django Pagination on a Changing Queryset On one of my pages I would like to display a subset of a sorted list of objects. The entire list of relevant objects is extremely long and has a good chance of changing while the user is viewing the page. I don't mind that the page is not up to date, but I do need to ensure...
Django Pagination on a Changing Queryset
On one of my pages I would like to display a subset of a sorted list of objects. The entire list of relevant objects is extremely long and has a good chance of changing while the user is viewing the page. I don't mind that the page is not up to date, but I do need to ensure that when the user goes to the next page, the...
[ "What might be a possibly solution is if you create your own pagination function that instead of the next link referring to a certain page it could pass a record that is the top record on the next page\nThe problem is that this would only work if the items being added/changed are only the first items in a list\n" ]
[ 3 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0003367371_django_pagination_python.txt
Q: Basic python arithmetic - division I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 : >>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> pri...
Basic python arithmetic - division
I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 : >>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> print per_page 2 >>> pages = math.ceil(coun...
[ "Python does integer division when both operands are integers, meaning that 1 / 2 is basically \"how many times does 2 go into 1\", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you ...
[ 15, 6, 1, 0, 0, 0 ]
[]
[]
[ "math", "python", "python_2.x" ]
stackoverflow_0003367315_math_python_python_2.x.txt
Q: Problem with 2D collision detection from beginner I've taken an introductory course in Computer Science, but a short while back I decided to try and make a game. I'm having a problem with collision detection. My idea was to move an object, and if there is a collision, move it back the way it came until there is no...
Problem with 2D collision detection from beginner
I've taken an introductory course in Computer Science, but a short while back I decided to try and make a game. I'm having a problem with collision detection. My idea was to move an object, and if there is a collision, move it back the way it came until there is no longer a collision. Here is my code: class Player(obje...
[ "Looks like you're setting the hitbox BEFORE updating the position. The Fix seems simple.\nFind:\n self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40)\n self.gPos += self.velocity \n\nReplace:\n self.gPos += self.velocity \n self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40)\n\nOther Suggestions: W...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0003367664_pygame_python.txt
Q: How to extract first items from a list of tuples I have a rather large list of tuples which contains: [('and', 44023), ('cx', 37711), ('is', 36777), ...] I just want to extract the first string, so the output for the above list would be: and cx is How do I code this (with extensibilty built in to some degree)? ...
How to extract first items from a list of tuples
I have a rather large list of tuples which contains: [('and', 44023), ('cx', 37711), ('is', 36777), ...] I just want to extract the first string, so the output for the above list would be: and cx is How do I code this (with extensibilty built in to some degree)?
[ "[tup[0] for tup in mylist]\n\nThis uses a list comprehension. You could also use parentheses instead of the outer brackets to make it a generator comprehension, so evaluation would be lazy.\n", "Just to provide an alternative way to the solution by Matthew.\ntuples = [('and', 44023), ('cx', 37711), ('is', 36777...
[ 15, 6, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0003367450_list_python_tuples.txt
Q: Ascending/descending ordering of Django QuerySet when one attribute is a model method I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the ...
Ascending/descending ordering of Django QuerySet when one attribute is a model method
I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the same winning percentage, I want them to be ordered alphabetically by school. How do I get s...
[ "Do it in two steps, not bad since sorts are stable:\nfrom operator import attrgetter\n\nsorted_team_list = sorted(team_list, key=attrgetter('school'))\nsorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sorting" ]
stackoverflow_0003367706_django_python_sorting.txt
Q: using python to add images to powerpoint files has anyone used python to add images to powerpoint 2007 files? can someone please help me get started with this A: You can do this with Office's COM/OLE automation API. For example, see this post: Automating PowerPoint with Python
using python to add images to powerpoint files
has anyone used python to add images to powerpoint 2007 files? can someone please help me get started with this
[ "You can do this with Office's COM/OLE automation API. For example, see this post:\n\nAutomating PowerPoint with Python\n\n" ]
[ 3 ]
[]
[]
[ "powerpoint", "python", "windows" ]
stackoverflow_0003367736_powerpoint_python_windows.txt
Q: is python the preferred language for mobile applications? a lot of my friends are using Python to build their mobile applications and games. is python the preferred language for mobile applications for developers? if so, why? A: No. Python is an excellent language, but there is nothing about it makes it especia...
is python the preferred language for mobile applications?
a lot of my friends are using Python to build their mobile applications and games. is python the preferred language for mobile applications for developers? if so, why?
[ "No. Python is an excellent language, but there is nothing about it makes it especially preferred for mobile development.\n", "No, there is no preferred language for mobile development. Each mobile platform has its own supported language or set of supported languages. Android is programmed primarily with Java (al...
[ 5, 3 ]
[]
[]
[ "mobile", "python" ]
stackoverflow_0003367808_mobile_python.txt
Q: Efficiently carry out multiple string replacements in Python If I would like to carry out multiple string replacements, what is the most efficient way to carry this out? An example of the kind of situation I have encountered in my travels is as follows: >>> strings = ['a', 'list', 'of', 'strings'] >>> [s.replace(...
Efficiently carry out multiple string replacements in Python
If I would like to carry out multiple string replacements, what is the most efficient way to carry this out? An example of the kind of situation I have encountered in my travels is as follows: >>> strings = ['a', 'list', 'of', 'strings'] >>> [s.replace('a', '')...replace('u', '') for s in strings if len(s) > 2] ['a',...
[ "The specific example you give (deleting single characters) is perfect for the translate method of strings, as is substitution of single characters with single characters. If the input string is a Unicode one, then, as well as the two above kinds of \"substitution\", substitution of single characters with multiple...
[ 12, 1 ]
[]
[]
[ "immutability", "python", "string" ]
stackoverflow_0003367809_immutability_python_string.txt
Q: How to replace a non-static substring case-insensitively This question is similar to this except that the substring to be replaced is only known at the runtime. I want to write the definition of ireplace, that behaves like this: >>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26') r'image\py...
How to replace a non-static substring case-insensitively
This question is similar to this except that the substring to be replaced is only known at the runtime. I want to write the definition of ireplace, that behaves like this: >>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26') r'image\python26\lib\site.py' >>>
[ "In this case, I think this is the simplest way\nr'c:\\Python26\\lib\\site.py'.lower().replace('python26', r'image\\python26')\n\nFor case insensitive, regexp is the simplest way\n>>> def ireplace(s, a, b):\n... return re.sub(\"(?i)\"+re.escape(a),b,s)\n...\n>>> print ireplace(r'c:\\Python26\\lib\\site.py', 'C:...
[ 1, 0 ]
[]
[]
[ "case_insensitive", "python", "string" ]
stackoverflow_0003367874_case_insensitive_python_string.txt
Q: converting structures in c to pywin32? i am trying to use TTM_GETTEXT via SendMessage using pywin32. the problem is, the structure of the lparam, which is where the text should be stored, has to be TOOLINFO, which is well documented in MSDN, but has no counterpart in pywin32. is there a way to create the same stru...
converting structures in c to pywin32?
i am trying to use TTM_GETTEXT via SendMessage using pywin32. the problem is, the structure of the lparam, which is where the text should be stored, has to be TOOLINFO, which is well documented in MSDN, but has no counterpart in pywin32. is there a way to create the same structure using python and pywin32? Edit: here's...
[ "It's not particularly pretty, but you can use the struct module to pack the fields into a string with the appropriate endianess, alignment, and padding. It's a little tricky since you must define the structure with a format string using only corresponding fundamental data types in the correct order.\nYou could al...
[ 1 ]
[]
[]
[ "python", "pywin32", "winapi" ]
stackoverflow_0003367721_python_pywin32_winapi.txt
Q: Where to host a periodically running Python or Java service? I'm going to build a little service which monitors an IMAP email account and acts on the read messages. For this it just has to run every say 10 min, no external trigger required, but I want to host this service externally (so that I don't need to worry ...
Where to host a periodically running Python or Java service?
I'm going to build a little service which monitors an IMAP email account and acts on the read messages. For this it just has to run every say 10 min, no external trigger required, but I want to host this service externally (so that I don't need to worry about up times.) To be machine independent I could write the servi...
[ "Depending on what actions you require, and your requirements for resources, Google App Engine might be quite suitable for both Python and Java services (GAE supports both languages quite decently). cron jobs can be set to run every 10 minutes (the URL I gave shows how to do that with Python) and you can queue mor...
[ 6, 3, 0 ]
[]
[]
[ "hosting", "java", "python", "service" ]
stackoverflow_0003368246_hosting_java_python_service.txt
Q: In a python script, how can I save the contents of a string to file, and the file is in current directory? In a python script, how can I save the contents of a string to file, and the file is in current directory? i.e the same directory as the test.py script file A: This will create/overwrite myfile.txt in the c...
In a python script, how can I save the contents of a string to file, and the file is in current directory?
In a python script, how can I save the contents of a string to file, and the file is in current directory? i.e the same directory as the test.py script file
[ "This will create/overwrite myfile.txt in the current working directory.\nThe Python 'current working directory' is inherited from the operating system. I.e., it's the directory you were 'in' when you ran the script. (Which isn't always the directory containing the script; e.g., scripts in distant directories can b...
[ 3, 3 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003368244_file_io_python.txt
Q: Best way to test for existence of a variable in Python I am reading a million plus files to scrape out some data. The files are generally pretty uniform but there are occasional problems where something that I expected to find is not present. For example, I expect some sgml code to identify a value I need for dat...
Best way to test for existence of a variable in Python
I am reading a million plus files to scrape out some data. The files are generally pretty uniform but there are occasional problems where something that I expected to find is not present. For example, I expect some sgml code to identify a value I need for data_line in temp #temp is a list of lines from a file if ...
[ "Just initialize your variable to its default value before the loop:\nVARIABLE_VAL = somethingELSE\nfor dataline in temp: ...\n\nthis way, VARIABLE_VAL will keep its initial, default value unless bound to something else within the loop, and you need no weird testing whatsoever to ensure that.\n", "Alex's solution...
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003368270_python.txt
Q: Which is better - PyInstaller or cx_Freeze? Could someone tell me which is better of the two for bundling Python applications — cx_Freeze or PyInstaller? I'm looking for a comparison based on factors such as: Popularity (i.e. larger user base) Footprint of the built binary Cross platform compatibility Ease of use...
Which is better - PyInstaller or cx_Freeze?
Could someone tell me which is better of the two for bundling Python applications — cx_Freeze or PyInstaller? I'm looking for a comparison based on factors such as: Popularity (i.e. larger user base) Footprint of the built binary Cross platform compatibility Ease of use
[ "I tried both for a current project and decided to use cx_freeze. I found it easier to get started. It has an option to bundle dependencies in a zip archive, which makes it easy to check that everything was properly included.\nI had trouble getting PyInstaller to include certain egg dependencies. It couldn't handle...
[ 26, 1 ]
[]
[]
[ "cx_freeze", "pyinstaller", "python" ]
stackoverflow_0003307966_cx_freeze_pyinstaller_python.txt
Q: How do I setup python to always include my directory of utility files I have been programming in Python for a while now, and have created some utilities that I use a lot. Whenever I start a new project, I start writing, and as I need these utilities I copy them from where ever I think the latest version of the pa...
How do I setup python to always include my directory of utility files
I have been programming in Python for a while now, and have created some utilities that I use a lot. Whenever I start a new project, I start writing, and as I need these utilities I copy them from where ever I think the latest version of the particular utility is. I have enough projects now that I am losing track of ...
[ "The site-packages directory within the Python lib directory should always be added to sys.path, so you shouldn't need to modify anything to take care of that. That's actually just what I'd recommend, that you make yourself a Python package within that directory and put your code in there.\nActually, something you ...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003368459_python.txt
Q: python function fails to return unless the last statement is slow I'm working on a subclass of threading.Thread which allows its methods to be called and run in the thread represented by the object that they are called on as opposed to the usual behavior. I do this by using decorators on the target method that pla...
python function fails to return unless the last statement is slow
I'm working on a subclass of threading.Thread which allows its methods to be called and run in the thread represented by the object that they are called on as opposed to the usual behavior. I do this by using decorators on the target method that place the call to the method in a collections.deque and using the run meth...
[ "\n__process_calls is modifying __enqueued_calls without owning the lock. This may be creating a race condition.\nEdit: deque may be \"threadsafe\" (ie not corrupted by thread accesses), but the checking of its state still should be locked.\nThe stop condition is also not safe.\n\nComments inline:\ndef run(self): ...
[ 1 ]
[]
[]
[ "debugging", "multithreading", "python", "python_multithreading" ]
stackoverflow_0003368475_debugging_multithreading_python_python_multithreading.txt
Q: Integrity check going from dev to testing Django app using Git I'm using Git to push my code from my development machine to my testing server. Dev: Mac, Python 2.6, sqllite and Test: Linux, Python 2.7, MySQL I took an early dev database and exported it to MySQL for initial testing. So now I'm regularly pushing...
Integrity check going from dev to testing Django app using Git
I'm using Git to push my code from my development machine to my testing server. Dev: Mac, Python 2.6, sqllite and Test: Linux, Python 2.7, MySQL I took an early dev database and exported it to MySQL for initial testing. So now I'm regularly pushing new code to the testing server. In general it seems to be working ...
[ "I'm not able to answer this question directly. \nDepending on the reasons why you have used a different Python environment for your testing server, there are a few options:\nFirst, if you want to test to see whether your code functions in multiple environments, I recommend you look into py.test. It has support for...
[ 1 ]
[]
[]
[ "configuration", "django", "git", "python" ]
stackoverflow_0003367004_configuration_django_git_python.txt
Q: Compile Error IcePy (Ice 3.3.1) : relocation against local symbol I have a problem when I try to build IcePy (from Ice 3.3.1) (for python 2.4.4). Compilation, testing and install of Ice itself (cpp version) is OK but when I tried to build the python interface ("py" directory) I get the following error (sorry for t...
Compile Error IcePy (Ice 3.3.1) : relocation against local symbol
I have a problem when I try to build IcePy (from Ice 3.3.1) (for python 2.4.4). Compilation, testing and install of Ice itself (cpp version) is OK but when I tried to build the python interface ("py" directory) I get the following error (sorry for the truncated paths) : .../lib/python2.4/config/libpython2.4.a(abstract....
[ "The abstract.o was very likely not compiled with -fPIC, so the advice linker gave you is correct.\nGo back to your build log, and verify that -fPIC is not there when libpython2.4.a was built. Note that -fPIC is needed for libpython2.4.a itself, not just for the IcePy.\nIf it is there, you have found a bug in GCC (...
[ 1 ]
[]
[]
[ "compilation", "linker", "python" ]
stackoverflow_0003364168_compilation_linker_python.txt
Q: How to make float values in Python display .00 instead of .0? Simple question, sorry I can;t figure this out. I have some numbers that are made by float(STRING) and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this? Thanks! EDIT: Python saiys that fl...
How to make float values in Python display .00 instead of .0?
Simple question, sorry I can;t figure this out. I have some numbers that are made by float(STRING) and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this? Thanks! EDIT: Python saiys that float doesn't have a cal 'format()'
[ ">>> '%.2f' % 2.0\n'2.00'\n\n", "Also:\n>>> \"{0:.2f}\".format(2.0)\n'2.00'\n\n", "If you do not like the numbers to be rounded, you need to do little more:\n>>> \"%.2f\" % 1.99999\n'2.00'\n>>> \"%.2f\" % (int(1.99999*100)/100.0)\n'1.99'\n\n", ">>> \"{0:.2f}\".format(2)\n'2.00'\n\nFor more information about...
[ 11, 2, 1, 1 ]
[]
[]
[ "double", "floating_point", "integer", "python" ]
stackoverflow_0003368514_double_floating_point_integer_python.txt
Q: Zooming With Python Image Library I'm writing a simple application in Python which displays images.I need to implement Zoom In and Zoom Out by scaling the image. I think the Image.transform method will be able to do this, but I'm not sure how to use it, since it's asking for an affine matrix or something like that...
Zooming With Python Image Library
I'm writing a simple application in Python which displays images.I need to implement Zoom In and Zoom Out by scaling the image. I think the Image.transform method will be able to do this, but I'm not sure how to use it, since it's asking for an affine matrix or something like that :P Here's the quote from the docs: im...
[ "You would be much better off using the EXTENT rather than the AFFINE method. You only need to calculate two things: what part of the input you want to see, and how large it should be. For example, if you want to see the whole image scaled down to half size (i.e. zooming out by 2), you'd pass the data (0, 0, im.siz...
[ 6, 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0003368740_image_processing_python_python_imaging_library.txt
Q: Using beautifulsoup, how to I reference table rows in html page I have a html page that looks like: <html> .. <form post="/products.hmlt" ..> .. <table ...> <tr>...</tr> <tr> <td>part info</td> .. </tr> </table> .. </form> .. </html> I tried: form = soup....
Using beautifulsoup, how to I reference table rows in html page
I have a html page that looks like: <html> .. <form post="/products.hmlt" ..> .. <table ...> <tr>...</tr> <tr> <td>part info</td> .. </tr> </table> .. </form> .. </html> I tried: form = soup.findAll('form') table = form.findAll('table') # table inside form ...
[ "findAll returns a list, so extract the element first:\nform = soup.findAll('form')[0]\ntable = form.findAll('table')[0] # table inside form\n\nOf course, you should do some error checking (i.e. make sure it's not empty) before indexing into the list.\n", "I like ars's answer, and certainly agree w/ the need for...
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003368730_beautifulsoup_python.txt
Q: form -> table -> tr using successive findAll calls Ok so I can reference my table correctly in a html page like this: form = soup.findAll('form')[1] table = form.findAll('table', width="79%") # returns 1 table, doing a print shows table with rows tr = table.findAll('tr') I get an error: ResultSet object has no...
form -> table -> tr using successive findAll calls
Ok so I can reference my table correctly in a html page like this: form = soup.findAll('form')[1] table = form.findAll('table', width="79%") # returns 1 table, doing a print shows table with rows tr = table.findAll('tr') I get an error: ResultSet object has no attribute findAll. Why doesn't this work? I used the o...
[ "As in the previous question, findAll returns a list.\nSo,\ntable = form.findAll('table', width='79%')[0]\ntr = table.findAll(...)\n\nwill extract the first one. As before, check that your list isn't empty first.\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003368854_beautifulsoup_python.txt
Q: Dynamic Django Application Creation Based On a SQL / CSV file Is there any django application that can create other apps merely based on a sql / csv file provided that a default template is found for the new applications. A: You can use database introspection to create models from pre-existing tables. You can di...
Dynamic Django Application Creation Based On a SQL / CSV file
Is there any django application that can create other apps merely based on a sql / csv file provided that a default template is found for the new applications.
[ "You can use database introspection to create models from pre-existing tables. You can divide the models up into apps and fix the odd error it seems to produce now an again. It saves a heap of time when integrating with legacy databases.\npython manage.py inspectdb > models.py\n\nMore details:\nhttp://docs.djangopr...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_apps", "django_models", "python" ]
stackoverflow_0003368304_django_django_admin_django_apps_django_models_python.txt
Q: how to see the content of a particular file in .tar.gz archive without unzipping the contents? for ex abc.tar.gz has abc/file1.txt abc/file2.txt abc/abc1/file3.txt abc/abc2/file4.txt i need to read/display the contents of file3.txt without extracting the file. Thanks for any input. A: import tarfile spam =...
how to see the content of a particular file in .tar.gz archive without unzipping the contents?
for ex abc.tar.gz has abc/file1.txt abc/file2.txt abc/abc1/file3.txt abc/abc2/file4.txt i need to read/display the contents of file3.txt without extracting the file. Thanks for any input.
[ "import tarfile\nspam = tarfile.open( \"abc.tar.gz\" )\nif \"abc/abc1/file3.txt\" in spam.getnames():\n with spam.extractfile( \"abc/abc1/file3.txt\" ) as ham:\n print ham.read()\n\nSee tarfile.\n", "tar -xzf mytar.tar.gz --to-command=cat filename.in.archive\n\n" ]
[ 11, 5 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0003369732_bash_python.txt
Q: Why python list slice assignment eats memory? I'm fighting a memory leak in a Python project and spent much time on it already. I have deduced the problem to a small example. Now seems like I know the solution, but I can't understand why. import random def main(): d = {} used_keys = [] n = 0 while...
Why python list slice assignment eats memory?
I'm fighting a memory leak in a Python project and spent much time on it already. I have deduced the problem to a small example. Now seems like I know the solution, but I can't understand why. import random def main(): d = {} used_keys = [] n = 0 while True: # choose a key unique enough among u...
[ "Here's the reason - the current method does not delete the keys from the dict (only one, actually). This is because you clear the used_keys list during the loop, and the loop exits prematurely.\nThe 2nd (commented) method, however, does work as you assign a new value to used_keys so the loop finishes successfully....
[ 5, 0 ]
[]
[]
[ "memory", "memory_leaks", "memory_management", "python" ]
stackoverflow_0003369771_memory_memory_leaks_memory_management_python.txt
Q: When is using __call__ a good idea? What are peoples' opinions on using the __call__. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour. A: I think your intuition is about right. Historically, callable objects (...
When is using __call__ a good idea?
What are peoples' opinions on using the __call__. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour.
[ "I think your intuition is about right.\nHistorically, callable objects (or what I've sometimes heard called \"functors\") have been used in the OO world to simulate closures. In C++ they're frequently indispensable.\nHowever, __call__ has quite a bit of competition in the Python world:\n\nA regular named method, w...
[ 37, 3, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003369640_oop_python.txt
Q: Why < is slower than >= I am using the following code to do the test and it seems like < is slower that >=., does anyone know why? import timeit s = """ x=5 if x<0: pass """ t = timeit.Timer(stmt=s) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) #0.21 usec/pass z = """ x=5 if x>=0:...
Why < is slower than >=
I am using the following code to do the test and it seems like < is slower that >=., does anyone know why? import timeit s = """ x=5 if x<0: pass """ t = timeit.Timer(stmt=s) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) #0.21 usec/pass z = """ x=5 if x>=0: pass """ t2 = timeit.Timer(s...
[ "In Python 3.1.2, sometime < is faster than >=. I try to read it in disassembler,\nimport dis\ndef f1():\n x=5\n if x < 0: pass\n\ndef f2():\n x = 5\n if x >=0: pass\n\n>>> dis.dis(f1)\n 2 0 LOAD_CONST 1 (5) \n 3 STORE_FAST 0 (x) \n\n 3 6 LO...
[ 32, 5, 5, 2, 2, 1, 1 ]
[]
[]
[ "optimization", "performance", "python" ]
stackoverflow_0003369304_optimization_performance_python.txt
Q: Annotate a django query via a reverse relationship I have two models Property and Image, related by foreign key such that each Property has multiple instances of Image. I'm trying to retrieve a queryset of all the properties - listing all fields - and the number of images that each property has. I am aware that I ...
Annotate a django query via a reverse relationship
I have two models Property and Image, related by foreign key such that each Property has multiple instances of Image. I'm trying to retrieve a queryset of all the properties - listing all fields - and the number of images that each property has. I am aware that I could do this as two distinct queries, but I don't feel ...
[ "The code you've posted should work - in any case, it should not return an empty queryset as annotate doesn't affect the filtering of the main query.\nSilly question, but are you sure there are Property elements in the database?\n" ]
[ 6 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0003369904_django_django_queryset_python.txt
Q: "post" method to communicate directly with a server Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it rai...
"post" method to communicate directly with a server
Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it raises HTTP Error 404 which means page not found. Here's my ...
[ "why is there a 'url' in your values ? did you try without it ?\nthen, try replacing localhost with 127.0.0.1 (if localhost is not in your hosts file). \nAre you on windows or linux ?\n", "I recommend you to use Mechanize. It will simplify your life.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "urllib", "urllib2", "wordpress" ]
stackoverflow_0003362399_python_urllib_urllib2_wordpress.txt
Q: basic questions about "import" I have some questions about Python's import statement: What is the difference between import <module> and from <module> import *? How can I import a module that is not in the same directory? (and not in PythonHome) Please consider I am a Python newbie A: import imports the mo...
basic questions about "import"
I have some questions about Python's import statement: What is the difference between import <module> and from <module> import *? How can I import a module that is not in the same directory? (and not in PythonHome) Please consider I am a Python newbie
[ "import imports the module into the global namespace. from import imports the named items into the namespace.\nSo with a plain import you always have to reference the module:\n>>> import datetime\n>>> day = datetime.date.today()\n\nBut with an from import you can reference the items directly:\n>>> from datetime im...
[ 6, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003370726_import_python.txt
Q: python error when I use different systems! When I use my system, there is no error in my python codes. When I use another system I get this error:(both systems have same version of python) /usr/lib/pymodules/python2.6/matplotlib/numerix/__init__.py:18: DeprecationWarning: *****************************************...
python error when I use different systems!
When I use my system, there is no error in my python codes. When I use another system I get this error:(both systems have same version of python) /usr/lib/pymodules/python2.6/matplotlib/numerix/__init__.py:18: DeprecationWarning: ********************************************************** matplotlib.numerix and all its...
[ "There's a hint.\nmatplotlib.numerix and all its subpackages are deprecated.\nThey will be removed soon. Please use numpy instead.\n\nThe system that gets this error has old packages installed.\nWhile the \"version of python\" may be the same, the set of installed packages is different.\n" ]
[ 4 ]
[]
[]
[ "deprecated", "python", "version" ]
stackoverflow_0003370908_deprecated_python_version.txt
Q: How to store Python 2.6 value in regedit What information about Python 2.6 stored in the Windows registry, under HKEY_LOCAL_MACHINE/SOFTWARE? Where is it stored? Somehow I lost it in my regedit and can't install a module. I googled it, but I can't find any answer, and I don't have an extra computer to try and man...
How to store Python 2.6 value in regedit
What information about Python 2.6 stored in the Windows registry, under HKEY_LOCAL_MACHINE/SOFTWARE? Where is it stored? Somehow I lost it in my regedit and can't install a module. I googled it, but I can't find any answer, and I don't have an extra computer to try and many modules that I need for my school project is...
[ "Ohh, I found the solution by repairing the Python 2.6 installation.\n" ]
[ 1 ]
[]
[]
[ "python", "window" ]
stackoverflow_0003371008_python_window.txt
Q: how to send variable to javascript? I am sending a tuple as my variable to javascript. But i could not find a way. I am using bottle framework. A: Encode it into JSON. It'll convert to a javascript array. A: A related tip to add to @Oil's point, Bottle returns JSON by default of you return a dict: @route('/res...
how to send variable to javascript?
I am sending a tuple as my variable to javascript. But i could not find a way. I am using bottle framework.
[ "Encode it into JSON. It'll convert to a javascript array.\n", "A related tip to add to @Oil's point, Bottle returns JSON by default of you return a dict:\n@route('/resource.json')\ndef resource_json():\n response = dict(\n data=('tuple', 'of', 'things'))\nreturn response\n\nSee http://bottle.paws.de/pa...
[ 2, 2 ]
[]
[]
[ "bottle", "javascript", "python" ]
stackoverflow_0003370996_bottle_javascript_python.txt
Q: Assign multiple tags to one entry I have this simple model: class Tag(models.Model): title = models.SlugField() created = models.datetime def __unicode__(self): return self.title class Entry(models.Model): title = models.CharField(max_length=30) created = models.datetime tags = mod...
Assign multiple tags to one entry
I have this simple model: class Tag(models.Model): title = models.SlugField() created = models.datetime def __unicode__(self): return self.title class Entry(models.Model): title = models.CharField(max_length=30) created = models.datetime tags = models.ForeignKey(Tag) categories = mo...
[ "As one tag can have many entries and vice versa, you will want to add a ManyToMany field.\n", "I would create another class in the Model to support this. \nclass tagEntryJoins(models.Model): \n tag = models.ForeignKey('Tag')\n entry = models.ForeignKey('entry') \n\n" ]
[ 4, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003371164_django_django_models_python.txt
Q: How to add audio to video? I record a video with no sound. I save a snapshots and then I compile them to .avi with 25FPS. Now I want to record audio (instead time.sleep(0.04) between following snapshots I will record audio in this time) and compile it wits video. Now I have avi file, and wave file, and I find a so...
How to add audio to video?
I record a video with no sound. I save a snapshots and then I compile them to .avi with 25FPS. Now I want to record audio (instead time.sleep(0.04) between following snapshots I will record audio in this time) and compile it wits video. Now I have avi file, and wave file, and I find a solution to mix them. Python, Win3...
[ "I think the best bet would be to use an external program to mux them. ffmpeg is a perennial favorite -- quality Windows builds are available at http://ffmpeg.arrozcru.org/autobuilds/ . With ffmpeg, just do ffmpeg -i your_video_file.avi -i your_audio_file.wav -vcodec copy -acodec copy muxed_file.avi and you're done...
[ 3 ]
[]
[]
[ "audio", "python", "video" ]
stackoverflow_0003371407_audio_python_video.txt