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: Is it possible to install an msi using python? Is it possible to write a script in python that installs an msi? Or is it possible to make it through any other script? A: You can use the antiquated os.system('msiexec /i whatever.msi'), or, better, the subprocess equivalent subprocess.call -- in either case, you ...
Is it possible to install an msi using python?
Is it possible to write a script in python that installs an msi? Or is it possible to make it through any other script?
[ "You can use the antiquated os.system('msiexec /i whatever.msi'), or, better, the subprocess equivalent subprocess.call -- in either case, you can also add whatever further msiexec flags or arguments you desire (documentation in abundance here).\n", "AFAIK, it's possible to use WMI in Python, so you should be abl...
[ 7, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0003130252_python_scripting.txt
Q: How do I create a unique property in python on google app engine? In some database technologies, for a attribute in a record, you can guarantee uniqueness of that attribute within the entire database. An example of this might be a email_address attribute in a User record. By setting email_address to unique, you gu...
How do I create a unique property in python on google app engine?
In some database technologies, for a attribute in a record, you can guarantee uniqueness of that attribute within the entire database. An example of this might be a email_address attribute in a User record. By setting email_address to unique, you guarantee that a particular email address can only appear in one record i...
[ "The only help you get from GAE's datastore regarding \"uniqueness\" is via entities' keys -- but then, I see the URL you quote also noticed that and shows one way to exploit this fact. To get anywhere beyond keys, you need to perform your checks at application level (before you put an entity, or a change to a uniq...
[ 4, 2, 2 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0001809754_database_google_app_engine_python.txt
Q: Switch python distributions I have a MacBook Pro with Snow Leopard, and the Python 2.6 distribution that comes standard. Numpy does not work properly on it. Loadtxt gives errors of the filename being too long, and getfromtxt does not work at all (no object in module error). So then I tried downloading the py26-...
Switch python distributions
I have a MacBook Pro with Snow Leopard, and the Python 2.6 distribution that comes standard. Numpy does not work properly on it. Loadtxt gives errors of the filename being too long, and getfromtxt does not work at all (no object in module error). So then I tried downloading the py26-numpy port on MacPorts. Of cours...
[ "First of all, add the MacPorts path (/opt/local/bin) to your $PATH. In .bashrc (or whatever shell config file you use):\nexport PATH=\"/opt/local/bin:${PATH}\"\n\nIf you have multiple versions of Python installed via MacPorts, and/or want to easily switch between the MacPorts and Apple distributions, you can insta...
[ 4, 1, 0 ]
[]
[]
[ "macports", "numpy", "osx_snow_leopard", "python" ]
stackoverflow_0003134332_macports_numpy_osx_snow_leopard_python.txt
Q: Good real-world uses of metaclasses (e.g. in Python) I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclas...
Good real-world uses of metaclasses (e.g. in Python)
I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out th...
[ "In Python 2.6 and 3.1, the Python standard library provides an abc.ABCMeta, a meta-class for Abstract Base Classes (\"ABCs\"). Classes that use the meta-class can use @abstractmethod and @abstractproperty to define abstract methods and properties. The meta-class will ensure that derived classes override the abst...
[ 3, 3, 2, 0, 0 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0002907498_metaprogramming_python.txt
Q: 401 and 403 Errors with google base API I built a wiki using Google App engine and the Data APIs. The wiki pages are stored as Google Base 'Reference Articles.' I want users to be able to view, edit, and delete the items, so when a request is made to the server, client login uses my username and password, and re...
401 and 403 Errors with google base API
I built a wiki using Google App engine and the Data APIs. The wiki pages are stored as Google Base 'Reference Articles.' I want users to be able to view, edit, and delete the items, so when a request is made to the server, client login uses my username and password, and retrieves or edits the data on the user's behal...
[ "It sounds like logging out in your client is invalidating all sessions for your account. Your best bet is probably to create a role account specifically for your app to use.\n" ]
[ 1 ]
[]
[]
[ "authentication", "gdata_api", "google_app_engine", "google_base", "python" ]
stackoverflow_0003134412_authentication_gdata_api_google_app_engine_google_base_python.txt
Q: How do I tell django to not escape % and _ in a query I want to be able to use wildcards in my django queries used for searching. However as the documentation says: Entry.objects.filter(headline__contains='%') Will result in SQL that looks something like this: SELECT ... WHERE headline LIKE '%\%%'; How do I te...
How do I tell django to not escape % and _ in a query
I want to be able to use wildcards in my django queries used for searching. However as the documentation says: Entry.objects.filter(headline__contains='%') Will result in SQL that looks something like this: SELECT ... WHERE headline LIKE '%\%%'; How do I tell django to not escape % and _ in a query. Or is there ano...
[ "headline__contains='%' would mean headline is anything, no? In which case why include it in the query?\n", "You can use the extra() method to insert a custom where clause:\nEntry.objects.extra(where=\"headline LIKE '%'\")\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003134850_django_python.txt
Q: Can I have two init functions in a python class? I'm porting some geolocation java code from http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#Java (shown below) to python. It can be initialized using two functions (fromDegrees or fromRadians). I thought I could do something like class geoLocation: ...
Can I have two init functions in a python class?
I'm porting some geolocation java code from http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#Java (shown below) to python. It can be initialized using two functions (fromDegrees or fromRadians). I thought I could do something like class geoLocation: _radLat = 0 _radLong = 0 _degLat = 0 _degL...
[ "Chose one default ( radians or degrees ) and stick with it. You can write a classmethod to automatically convert to the other:\nclass geoLocation:\n def __init__(self, lat, long):\n \"\"\"init class from lat,long as radians\"\"\"\n\n @classmethod\n def fromDegrees(cls, dlat, dlong):\n \"\"\"...
[ 30, 7, 5, 1 ]
[]
[]
[ "init", "python" ]
stackoverflow_0003134829_init_python.txt
Q: How can I break this multithreaded python script into "chunks"? I'm processing 100k domain names into a CSV based on results taken from Siteadvisor using urllib (not the best method, I know). However, my current script creates too many threads and Python runs into errors. Is there a way I can "chunk" this script t...
How can I break this multithreaded python script into "chunks"?
I'm processing 100k domain names into a CSV based on results taken from Siteadvisor using urllib (not the best method, I know). However, my current script creates too many threads and Python runs into errors. Is there a way I can "chunk" this script to do X number of domains at a time (say, 10-20) to prevent these erro...
[ "Your existing code will work beautifully - just modify your __init__ method inside Resolver to take in an additional list of addresses instead of one at a time, so instead of having one thread for each address, you have one thread for every 10 (for example). That way you won't overload the threading.\nYou'll obvio...
[ 2, 2 ]
[]
[]
[ "python", "python_multithreading" ]
stackoverflow_0003135015_python_python_multithreading.txt
Q: Serious overhead in Python cProfile? Hi expert Pythonists out there, I am starting to use cProfile so as to have a more detailed timing information on my program. However, it's quite disturbing to me that there's a significant overhead. Any idea why cProfile reported 7 seconds while time module only reported 2 sec...
Serious overhead in Python cProfile?
Hi expert Pythonists out there, I am starting to use cProfile so as to have a more detailed timing information on my program. However, it's quite disturbing to me that there's a significant overhead. Any idea why cProfile reported 7 seconds while time module only reported 2 seconds in the code below? # a simple functio...
[ "Because it's doing a lot more work? time just times the whole operation, while cProfile runs it under instrumentation so it can get a detailed breakdown. Obviously, profiling is not meant to be used in production, so a 2.5x overhead seems like a small price to pay.\n", "The function f returns very quickly. Whe...
[ 5, 1 ]
[]
[]
[ "cprofile", "performance", "profile", "python", "time" ]
stackoverflow_0003134843_cprofile_performance_profile_python_time.txt
Q: How to Close an Image? I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on filename. I need this content to be saved back to the same file...
How to Close an Image?
I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on filename. I need this content to be saved back to the same file because external processes ...
[ "You can provide a file-like object instead of a filename to the Image.open function. So try this:\ndef do_post_processing(filename):\n with open(str(filename), 'rb') as f:\n image = Image.open(f)\n ...\n del new_image, image\n os.remove(str(filename))\n os.rename(...)\n\n" ]
[ 16 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0003135328_python_python_imaging_library.txt
Q: Is Python (Django) experience professionaly comparable to Ruby on Rails? I ask this because there seems to be a few more jobs available (at least by telecommute) in RoR. If an employer sees significant Python/Django experience on a resume, would it be plausible to believe that the developer would be able quickly l...
Is Python (Django) experience professionaly comparable to Ruby on Rails?
I ask this because there seems to be a few more jobs available (at least by telecommute) in RoR. If an employer sees significant Python/Django experience on a resume, would it be plausible to believe that the developer would be able quickly learn Rails?
[ "My experience is, that the more languages and/or frameworks you know, the easier it is to learn a new language. So if you have pretty good experience in programming it shouldn't be a big problem. \nPython and Ruby are both dynamic and completely object oriented Languages. Just the syntax is a little bit different....
[ 2, 0, 0 ]
[]
[]
[ "django", "python", "ruby_on_rails" ]
stackoverflow_0003136131_django_python_ruby_on_rails.txt
Q: Deleting already printed in Python For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace chara...
Deleting already printed in Python
For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something l...
[ "\\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.\n", "I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're ...
[ 4, 2, 2, 1 ]
[]
[]
[ "printing", "python", "python_3.x" ]
stackoverflow_0003136202_printing_python_python_3.x.txt
Q: Find MacOSX version from Python Currently I am using this: def _get_mac_ver(): import subprocess p = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.strip() Is there a better version (eg: by using built-in Python API)? >>> pri...
Find MacOSX version from Python
Currently I am using this: def _get_mac_ver(): import subprocess p = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.strip() Is there a better version (eg: by using built-in Python API)? >>> print _get_mac_ver() 10.6.3 Note: I tri...
[ "True to the philosophy that python comes with batteries included, there is a module in the standard library to do this: platform. \nSee in particular the `mac_ver()' function:\n>>> import platform\n>>> platform.mac_ver()\n('10.6.3', ('', '', ''), 'i386')\n>>> print platform.mac_ver()[0]\n10.6.3\n\n" ]
[ 8 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003136818_macos_python.txt
Q: Find root of implicit function in Python I have an implicit function, for example: f(x,y) = x**y + y**y - 3*x I want to solve the root on a meshgrid. So f(x,y) = 0 Drawing the solution is easy: x = linspace(-2,2,11) y = linspace(-2,2,11) (X,Y) = meshgrid(x,y) A = X**Y + Y**Y - 3*X contour(X,Y,A,0) This works gr...
Find root of implicit function in Python
I have an implicit function, for example: f(x,y) = x**y + y**y - 3*x I want to solve the root on a meshgrid. So f(x,y) = 0 Drawing the solution is easy: x = linspace(-2,2,11) y = linspace(-2,2,11) (X,Y) = meshgrid(x,y) A = X**Y + Y**Y - 3*X contour(X,Y,A,0) This works great, I have a drawing of the curve I need, how...
[ "You can get \"the data that is in the [matplotlib] plot\" using:\ncs = contour(X,Y,A,0)\ndata = cs.collections[0].get_paths()[1]\n\nThere are a variety of algorithms for calculating the contours directly, though I don't know of any numpy/scipy versions. Marching squares is the one I always here about, although th...
[ 3 ]
[]
[]
[ "implicit", "numpy", "python", "root" ]
stackoverflow_0003136432_implicit_numpy_python_root.txt
Q: EDI X12 Templates in Python (Most likely django or jinja) (w/ sqlalchemy) My Case: I'm working on a system that will need to create various X12 files for health care (insurance) transactions and inquiries (Specifically 270 Eligibility and 837 Claim). I know there are good tools out there (pyx12 specifically) for ...
EDI X12 Templates in Python (Most likely django or jinja) (w/ sqlalchemy)
My Case: I'm working on a system that will need to create various X12 files for health care (insurance) transactions and inquiries (Specifically 270 Eligibility and 837 Claim). I know there are good tools out there (pyx12 specifically) for converting between XML and X12, and actually I've gone as far as importing some...
[ "I haven't worked on x12 specifically, but I've often generated all kinds of textual formats by templating, and I can confirm it works like a charm. I would recommend mako (because it basically gives you all the power of Python for your templating), but if you're keen on staying with django-like templates, then ji...
[ 1 ]
[]
[]
[ "python", "sqlalchemy", "templates", "x12" ]
stackoverflow_0003137023_python_sqlalchemy_templates_x12.txt
Q: python sql interval With PostgreSQL, one of my tables has an 'interval' column, values of which I would like to extract as something I can manipulate (datetime.timedelta?); however I am using PyGreSQL which seems to be returning intervals as strings, which is less than helpful. Where should I be looking to either ...
python sql interval
With PostgreSQL, one of my tables has an 'interval' column, values of which I would like to extract as something I can manipulate (datetime.timedelta?); however I am using PyGreSQL which seems to be returning intervals as strings, which is less than helpful. Where should I be looking to either parse the interval or mak...
[ "Use Psycopg 2. It correctly converts between Postgres's interval data type and Python's timedelta.\n" ]
[ 3 ]
[]
[]
[ "postgresql", "pygresql", "python", "sql" ]
stackoverflow_0003134699_postgresql_pygresql_python_sql.txt
Q: How to write python web service server WSDL? All the stuff I am seeing points me towards writing clients. A: I believe the popular approach is to hand-write WSDL first (typically with an XML-oriented editor, of course, such as oxygen), then generate a Python server skeleton from it with wsdl2py. Unfortunately I...
How to write python web service server WSDL?
All the stuff I am seeing points me towards writing clients.
[ "I believe the popular approach is to hand-write WSDL first (typically with an XML-oriented editor, of course, such as oxygen), then generate a Python server skeleton from it with wsdl2py. Unfortunately I have no first-hand experience with this so I'm not sure if it works as well as it's advertised to.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "web_services" ]
stackoverflow_0003136778_python_python_3.x_web_services.txt
Q: Using an StringIO object for holding uu.encode/uu.decode data I would like to do the following: import StringIO, uu my_data = StringIO.StringIO() # this is a file-like object uu.encode(in_file, my_data) # do stuff with my data (send over network) uu.decode(my_data, out_file) # here I finally write to disk The abo...
Using an StringIO object for holding uu.encode/uu.decode data
I would like to do the following: import StringIO, uu my_data = StringIO.StringIO() # this is a file-like object uu.encode(in_file, my_data) # do stuff with my data (send over network) uu.decode(my_data, out_file) # here I finally write to disk The above code works. However, if I implement the previous step as a prope...
[ "self._content is left with the \"current point\" at its end after the content.setter method has written to it. You probably want to add self._content.seek(0) at the end of that method so you can next read that pseudo-file from the beginning (reading while starting from the end will return \"nothing more\", quite ...
[ 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003136697_encoding_python.txt
Q: Is it possible copy the contents of multiple widgets simultaneous in Tkinter? I'm trying to add a feature in python that copies the entire contents of two text widgets. How would one go about that? Pseudo Code: text1.SelectAll() C1 = text1.get(Copy) text2.SelectAll() C2 = text2.get(Copy) Pas...
Is it possible copy the contents of multiple widgets simultaneous in Tkinter?
I'm trying to add a feature in python that copies the entire contents of two text widgets. How would one go about that? Pseudo Code: text1.SelectAll() C1 = text1.get(Copy) text2.SelectAll() C2 = text2.get(Copy) Paste('Widget 1:\n\n' + C1 + 'Widget 2:\n\n' + C2 )
[ "Just do (if you have a from Tkinter import * -- I don't like it but many use it):\nC1 = text1.get(1.0, END)\nC2 = text2.get(1.0, END)\n\nNow you have the two strings. I'm not sure where that Paste is supposed to put the text into -- if you mean to replace the previous contents of text2, for example, just do\ntext...
[ 3 ]
[]
[]
[ "copy", "python", "tkinter", "widget" ]
stackoverflow_0003135646_copy_python_tkinter_widget.txt
Q: Highlight selected Tab - Python webpage I am trying to develop my first python web project. It have multiple tabs (like apple.com have Store, iPhone, iPad etc tabs) and when user click on any tab, the page is served from server. I want to make sure that the selected tab will have different background color when pa...
Highlight selected Tab - Python webpage
I am trying to develop my first python web project. It have multiple tabs (like apple.com have Store, iPhone, iPad etc tabs) and when user click on any tab, the page is served from server. I want to make sure that the selected tab will have different background color when page is loaded. Which is a best way to do it? J...
[ "I think the best way would be through CSS. You can handle it by adding the pseudoclass :active to the CSS.\nOther way is serving the page with a new class added to the tab, which will change the background color, but I would not recommend that.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003137167_python.txt
Q: How do I undo/redo something in a Tkinter text widget? I need to make both a Control-Z and Shift-Control-Z function in Python. Anyone have any Idea? Also I need to select the contents of an entire text widget, anyone know how to go about that? A: For the undo mechanism, check the UndoDelegator.py of Idle in co...
How do I undo/redo something in a Tkinter text widget?
I need to make both a Control-Z and Shift-Control-Z function in Python. Anyone have any Idea? Also I need to select the contents of an entire text widget, anyone know how to go about that?
[ "For the undo mechanism, check the UndoDelegator.py of Idle in combination with EditorWindow.py.\nTo select the entire contents of a Text widget, you can do:\n# remove previous selection, if any\ntext_widget.tag_remove(Tkinter.SEL, \"1.0\", Tkinter.END)\n# select all\ntext_widget.tag_add(Tkinter.SEL, \"1.0\", Tkint...
[ 2 ]
[]
[]
[ "python", "tkinter", "undo_redo" ]
stackoverflow_0003135924_python_tkinter_undo_redo.txt
Q: How to reference object properties in another module I am relatively new to Python having used C# for many years and I'm hoping someone can help me with this question. I have a module called actuators.py that contains a number of classes for defining properties and methods for the servos I use in a robot project....
How to reference object properties in another module
I am relatively new to Python having used C# for many years and I'm hoping someone can help me with this question. I have a module called actuators.py that contains a number of classes for defining properties and methods for the servos I use in a robot project. In another module called robot.py, I instantiate my actu...
[ "\nAnd I can't use\nfrom robot.py import myActuators\n\nbecause myActuators is not a module.\n\nBut myActuators doesn't need to be a module. You can do exactly that. (Though you'll want to use just robot rather than robot.py)\nhttp://docs.python.org/reference/simple_stmts.html#import\nAs well:\nhttp://docs.python.o...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003134549_python.txt
Q: How to layout all children of a wxPanel? I have a wxPython application which allows the users to select items from menus that then change what is visible on the screen. This often requires a recalculation of the layout of panels. I'd like to be able to call the layout of all the children of a panel (and the chil...
How to layout all children of a wxPanel?
I have a wxPython application which allows the users to select items from menus that then change what is visible on the screen. This often requires a recalculation of the layout of panels. I'd like to be able to call the layout of all the children of a panel (and the children of those children) in reverse order. Tha...
[ "Have a look at wxSizers and some examples for a fluid way to layout forms.\nYou can specify heights, poportions etc. etc. and then let the layout code do the rest for you :)\n", "More in response to your comment to Jon Cage's answer, than to your\noriginal question (which was perfectly answered by Jon):\nThe use...
[ 0, 0 ]
[]
[]
[ "dry", "model_view_controller", "python", "wxpython", "wxwidgets" ]
stackoverflow_0003136997_dry_model_view_controller_python_wxpython_wxwidgets.txt
Q: Test assertions for tuples with floats I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple ind...
Test assertions for tuples with floats
I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a list...
[ "Well how about pimping up your function with couple of zips:\ndef testF(self):\n for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]):\n for val1, val2 in zip(tuple1, tuple2):\n if type(val2) is float:\n self.assertAlmostEquals(val1, val2, 5)\n else:\n ...
[ 8, 3, 2 ]
[]
[]
[ "assert", "floating_point", "python", "tuples", "unit_testing" ]
stackoverflow_0003022952_assert_floating_point_python_tuples_unit_testing.txt
Q: How do you debug (trace execution) of a pylons web application? How do you debug (trace execution) of a pylons web application? (using a mac with textmate) A: It's really easy To sum it up, import the python logging module and send debug messages to the terminal on your Mac where you have the paste server runnin...
How do you debug (trace execution) of a pylons web application?
How do you debug (trace execution) of a pylons web application? (using a mac with textmate)
[ "It's really easy\nTo sum it up, import the python logging module and send debug messages to the terminal on your Mac where you have the paste server running.\nimport logging\nlog = logging.getLogger(__name__)\nlog.debug('Your trace message')\n\nThis will show up in whatever terminal your paste server is running in...
[ 1 ]
[]
[]
[ "debugging", "pylons", "python", "trace" ]
stackoverflow_0003133206_debugging_pylons_python_trace.txt
Q: Python: If an iterator is an expression, is it calculated every time? Take the following example: >>> for item in [i * 2 for i in range(1, 10)]: print item 2 4 6 8 10 12 14 16 18 Is [i * 2 for i in range(1, 10)] computed every time through the loop, or just once and stored? (Also, what is the proper name for...
Python: If an iterator is an expression, is it calculated every time?
Take the following example: >>> for item in [i * 2 for i in range(1, 10)]: print item 2 4 6 8 10 12 14 16 18 Is [i * 2 for i in range(1, 10)] computed every time through the loop, or just once and stored? (Also, what is the proper name for that part of the expression?) One reason I would want to do this is that ...
[ "A good translation of for i in <whatever>: <loopbody>, showing exactly what it does for any <whatever> and any <loopbody>:\n_aux = iter(<whatever>)\nwhile True:\n try: i = next(_aux)\n except StopIteration: break\n <loopbody>\n\nexcept that the pseudo-variable I have here named _aux actually remains unnamed.\nS...
[ 7, 4, 3 ]
[]
[]
[ "iterator", "loops", "python" ]
stackoverflow_0003137443_iterator_loops_python.txt
Q: Python question relating to dated values in a csv file I am loading a data file with dated data into a csv.DictReader The data looks like this: date, weight, blood_pressure, sugar_level 1/1/01, 120.1, 100.1, 25.2 2/1/01, 130.1, 102.1, 26.2 3/1/01, 110.1, 120.1, 24.2 4/1/01, 130.1, ...
Python question relating to dated values in a csv file
I am loading a data file with dated data into a csv.DictReader The data looks like this: date, weight, blood_pressure, sugar_level 1/1/01, 120.1, 100.1, 25.2 2/1/01, 130.1, 102.1, 26.2 3/1/01, 110.1, 120.1, 24.2 4/1/01, 130.1, 130.1, 28.2 5/1/01, 160.1, 104.1, 27.0 6/...
[ "First of all, please don't use ; after commands in python.\nimport datetime\nimport csv\n\nWEEK = datetime.timedelta(weeks=1)\nDAY = datetime.timedelta(days=1)\nMONTH = datetime.timedelta(days=30)\n\n# read the entire file to memory in a dict keyed by date\ndata = {}\nwith open('file.csv') as csvfile:\n for row...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003137505_python.txt
Q: Python: Can a class forbid clients setting new attributes? I just spent too long on a bug like the following: >>> class Odp(): def __init__(self): self.foo = "bar" >>> o = Odp() >>> o.raw_foo = 3 # oops - meant o.foo I have a class with an attribute. I was trying to set it, and wondering why it had n...
Python: Can a class forbid clients setting new attributes?
I just spent too long on a bug like the following: >>> class Odp(): def __init__(self): self.foo = "bar" >>> o = Odp() >>> o.raw_foo = 3 # oops - meant o.foo I have a class with an attribute. I was trying to set it, and wondering why it had no effect. Then, I went back to the original class definition, a...
[ "You can implement a __setattr__ method for the purpose -- that's much more robust than the __slots__ which is often misused for the purpose (for example, __slots__ is automatically \"lost\" when the class is inherited from, while __setattr__ survives unless explicitly overridden).\ndef __setattr__(self, name, valu...
[ 22 ]
[]
[]
[ "oop", "python", "typing" ]
stackoverflow_0003137558_oop_python_typing.txt
Q: Using enum properties in PyGTK/GObject This tutorial on using GObject in Python only covers using a property of type gobject.TYPE_FLOAT. I've adapted it to use an enumerated type: import pygtk pygtk.require('2.0') import gobject FUEL_NONE = 0 FUEL_SOME = 1 FUEL_FULL = 2 class Car(gobject.GObject): __gpropertie...
Using enum properties in PyGTK/GObject
This tutorial on using GObject in Python only covers using a property of type gobject.TYPE_FLOAT. I've adapted it to use an enumerated type: import pygtk pygtk.require('2.0') import gobject FUEL_NONE = 0 FUEL_SOME = 1 FUEL_FULL = 2 class Car(gobject.GObject): __gproperties__ = { 'fuel' : (gobject.TYPE_ENUM, ...
[ "It's not enough enough to tell __gproperties__ that it's an enumerated type; you need to register the enumeration with the GObject type system, and then use the GType value you get from that instead of gobject.TYPE_ENUM. At least, that's how it's done in C. I'm not sure what the proper way to do this is PyGTK is...
[ 2 ]
[]
[]
[ "gobject", "pygtk", "python" ]
stackoverflow_0003137262_gobject_pygtk_python.txt
Q: Using @property decorator on dicts I'm trying to use Python's @property decorator on a dict in a class. The idea is that I want a certain value (call it 'message') to be cleared after it is accessed. But I also want another value (call it 'last_message') to contain the last set message, and keep it until another m...
Using @property decorator on dicts
I'm trying to use Python's @property decorator on a dict in a class. The idea is that I want a certain value (call it 'message') to be cleared after it is accessed. But I also want another value (call it 'last_message') to contain the last set message, and keep it until another message is set. In my mind, this code wou...
[ "class MyDict(dict):\n def __setitem__(self, key, value):\n if key == 'message':\n super().__setitem__('message', '')\n super().__setitem__('last_message', value) \n else:\n super().__setitem__(key, value)\n\nclass A(object):\n def __init__(self):\n self._...
[ 21, 3 ]
[]
[]
[ "dictionary", "getter", "properties", "python", "setter" ]
stackoverflow_0003137685_dictionary_getter_properties_python_setter.txt
Q: How do I build a flexible counter with 1000+ rows but few reads in Google App Engine? I have a list of users that only administrators can see (= few reads). This list also displays a count of the number of users in the datastore. Because the list could grow larger than 1000 my first thought was to avoid a normal c...
How do I build a flexible counter with 1000+ rows but few reads in Google App Engine?
I have a list of users that only administrators can see (= few reads). This list also displays a count of the number of users in the datastore. Because the list could grow larger than 1000 my first thought was to avoid a normal count() and instead use a sharded counter. However, the problem is that the admins also have...
[ "\"Loop of counts\" is slow, but these days you can make it a bit better with cursors. Normally I would recommend denormalizing into all the \"filtered\" counters you need, but that slows down user addition and deletion (and probably demographic changes as well), so, given your particular use case with a very low ...
[ 2, 2 ]
[]
[]
[ "count", "counter", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003137070_count_counter_google_app_engine_google_cloud_datastore_python.txt
Q: SocketServer.ThreadingTCPServer - Cannot bind to address after program restart As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted: socket.error: [Errno 98] Address already in use In this particular case, instead of using a socket direc...
SocketServer.ThreadingTCPServer - Cannot bind to address after program restart
As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted: socket.error: [Errno 98] Address already in use In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server: httpd = SocketServer.Threa...
[ "The above solution didn't work for me but this one did:\n SocketServer.ThreadingTCPServer.allow_reuse_address = True\n server = SocketServer.ThreadingTCPServer((\"localhost\", port), CustomHandler)\n server.serve_forever()\n\n", "In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) may be call...
[ 19, 16 ]
[]
[]
[ "linux", "python", "sockets", "tcpserver" ]
stackoverflow_0002274320_linux_python_sockets_tcpserver.txt
Q: Is this correct way to import python scripts residing in arbitrary folders? This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directorie...
Is this correct way to import python scripts residing in arbitrary folders?
This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directories, and I would like to be able to import them into new projects without having to...
[ "The \"official\" and fully safe approach is the imp module of the standard Python library.\nUse imp.find_module to find the module on your precisely-specified list of acceptable directories -- it returns a 3-tuple (file, pathname, description) -- if unsuccessful, file is actually None (but it can also raise Import...
[ 8, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003137731_python.txt
Q: Cross-platform Python GUI suitable for taskbar (Win) and menubar (mac) functionality? I am fairly new to Python programming, and completely new to cross-platform GUI building (only previous GUI experience is through visual basic and Java). I've written some python code to screen-scrape data from a website, and now...
Cross-platform Python GUI suitable for taskbar (Win) and menubar (mac) functionality?
I am fairly new to Python programming, and completely new to cross-platform GUI building (only previous GUI experience is through visual basic and Java). I've written some python code to screen-scrape data from a website, and now I want to build a GUI that will reside in the Mac OS X menubar, and in Window's task bar (...
[ "Here's an example for PyQt. This works for me on MacOS X; I haven't tried it on other platforms. Note that the QSystemTrayIcon class will raise exceptions if it doesn't have an icon – I grabbed the RSS feed svg from Wiki commons for my icon.svg (but you can give QIcon a PNG directly and not mess around with QtSvg)...
[ 10, 2 ]
[]
[]
[ "cross_platform", "menubar", "python", "taskbar", "user_interface" ]
stackoverflow_0003104818_cross_platform_menubar_python_taskbar_user_interface.txt
Q: Implementing a special type of multiprocessing queue in Python Imagine an inverted binary tree with nodes A, B, C, D, E, F on level 0. nodes G,H,I on level 1, node J on level 2, and node K on level 3. Level 1: G = func(A,B), H = func(C,D), I = func(E,F) Level 2: J = func(G,H) Level 3: K = func(J,I). Each pair of...
Implementing a special type of multiprocessing queue in Python
Imagine an inverted binary tree with nodes A, B, C, D, E, F on level 0. nodes G,H,I on level 1, node J on level 2, and node K on level 3. Level 1: G = func(A,B), H = func(C,D), I = func(E,F) Level 2: J = func(G,H) Level 3: K = func(J,I). Each pair of nodes on Level 0 must be processed in order, Each pair of nodes on ...
[ "I couldn't come up with a smart design for a queue, but you can easily replace the queue with one more process, which in my example I called WorkerManager. This process gathers results from all Worker processes and starts new workers only if there are two adjacent data packs waiting to be processed. This way, you'...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0003098785_multiprocessing_python_queue.txt
Q: Including HTML variable in Django template without escaping I have html encoded text which reads like this: RT <a href="http://twitter.com/freuter">@freuter</a>... I want this displayed as html but I am not sure if there is a filter which i can apply to this text to convert the html-encoded text back to html ......
Including HTML variable in Django template without escaping
I have html encoded text which reads like this: RT <a href="http://twitter.com/freuter">@freuter</a>... I want this displayed as html but I am not sure if there is a filter which i can apply to this text to convert the html-encoded text back to html ... can someone help?
[ "As Daniel says, use the {{ tweet|safe }} filter in the html, or mark it safe from the views.\nUse django.template.mark_safe()\n", "Try the |safe filter if you want to render all HTML.\n", "See: How do I perform HTML decoding/encoding using Python/Django?\nI think this answers your querstion.\n" ]
[ 27, 4, 2 ]
[]
[]
[ "django", "encoding", "html", "python" ]
stackoverflow_0003138588_django_encoding_html_python.txt
Q: OSError on uploading files in Django While trying to send form with image field in it I'm getting : Exception Type: OSError at /user/register/ Exception Value: (13, 'Permission denied') Of course first thing I've checked were the permissions to my folders, and just in case set them to 777 on the whole path from '/...
OSError on uploading files in Django
While trying to send form with image field in it I'm getting : Exception Type: OSError at /user/register/ Exception Value: (13, 'Permission denied') Of course first thing I've checked were the permissions to my folders, and just in case set them to 777 on the whole path from '/'. Still nothing. So I've tried adding par...
[ "The apache use that runs your django application does not have the permission to create the folder/file in your media directory.\nA quick temporary fix would be to \nGo to your media folder:\n/home/fandrive/www/fandrive/site_media\nand type:\nsudo chmod -R a+w\n\nwhich makes your folder writeable by all users.\nT...
[ 2 ]
[]
[]
[ "django", "file_permissions", "file_upload", "permissions", "python" ]
stackoverflow_0003137111_django_file_permissions_file_upload_permissions_python.txt
Q: Trying to install Django via Macports on Leopard I have Python 2.6 & 3.1 installed on Leopard via mac ports with no problems. I want to install Django 1.2 via mac ports for Python 2.6, but a google search of how to do it seems to point me in the wrong direction. Can anyone point me in the right direction? Thanks a...
Trying to install Django via Macports on Leopard
I have Python 2.6 & 3.1 installed on Leopard via mac ports with no problems. I want to install Django 1.2 via mac ports for Python 2.6, but a google search of how to do it seems to point me in the wrong direction. Can anyone point me in the right direction? Thanks again.....
[ "Just don't do that. Install it directly from source.\nOr better, use easy_install:\neasy_install django\n\nOr even better, use pip (and add virtualenv as a bonus (and virtualenvwrapper for more fun!)):\npip install django\n\n", "What is wrong with this package?\n$ port info py26-django\npy26-django @1.2.1 (pytho...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003136423_django_python.txt
Q: Python - passing object references? I learning Python (coming from a dotnet background) and developing an app which interacts with a webservice. The web service is flat, in that it has numerous calls some of which are related to sessions e.g. logging on etc, whereas other calls are related to retrieving/setting b...
Python - passing object references?
I learning Python (coming from a dotnet background) and developing an app which interacts with a webservice. The web service is flat, in that it has numerous calls some of which are related to sessions e.g. logging on etc, whereas other calls are related to retrieving/setting business data. To accompany the webservice...
[ "If WebserviceAPI is an object just remove the parentheses like that:\nreturn self._api \n\nYou already created an instance of the object in the constructor.\nMaybe add the definition of WebserviceAPI to the question, I can only guess at the moment.\n", "I don't see anything that is wrong or un-Pythonic here. Pyt...
[ 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003139042_oop_python.txt
Q: Installing django with python 2.5 and not with the default version of python I have to install Django on my linux server where python 2.4 is available as the default installation. I have installed python 2.5 as a separate version. Now I have to install Django which I have to use with python 2.5. Is there any speci...
Installing django with python 2.5 and not with the default version of python
I have to install Django on my linux server where python 2.4 is available as the default installation. I have installed python 2.5 as a separate version. Now I have to install Django which I have to use with python 2.5. Is there any specific requirement, so that it is installed with the python 2.5 and not with the defa...
[ "after downloading the django source, instead of doing\npython setup.py install\n\ndo\n/path/to/python2.5 setup.py install\n\n", "Django is 100% compatible with Python 2.4. However if you really want to use 2.5 you would probably be best off using a virtualenv and installing Django and your project inside that.\n...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003139372_django_python.txt
Q: timeit module hangs with bigger values of pow() I am trying to calculate the time taken by pow function to calculate exponential modulo. With the values of g,x,p hardcoded the code gives error and with the values placed in the pow function, the code hangs. The same piece of code is working efficiently when i am us...
timeit module hangs with bigger values of pow()
I am trying to calculate the time taken by pow function to calculate exponential modulo. With the values of g,x,p hardcoded the code gives error and with the values placed in the pow function, the code hangs. The same piece of code is working efficiently when i am using time() and clock() to calculate the time taken by...
[ "There are two issues here:\n\nYou can't directly access globals from timeit: See this question. You can use this to fix the error:\nt = Timer('pow(g,x,p)', 'from __main__ import g,x,p')\n\nOr just put the numerical values directly in the string.\nBy default, the timeit module runs 1000000 iterations, which will ta...
[ 4 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0003139586_python_timeit.txt
Q: Django: Update order attribute for objects in a queryset I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after th...
Django: Update order attribute for objects in a queryset
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same ...
[ "This cannot be done in one single queryset operation. As far as I know it can't even be done in one query with raw SQL. So you will always need the update call for each object that has to be updated. So both your and Collin Anderson's solutions seem quite optimal for your description.\nHowever, what's your use cas...
[ 6, 2 ]
[]
[]
[ "django", "django_queryset", "list", "performance", "python" ]
stackoverflow_0003048171_django_django_queryset_list_performance_python.txt
Q: Has anyone here tried using the iSeries Python port? I found http://www.iseriespython.com/, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are: Does the port work wel...
Has anyone here tried using the iSeries Python port?
I found http://www.iseriespython.com/, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are: Does the port work well, or are there limits to what the interpreter can handle ...
[ "From what I have seen so far, it works pretty well. Note that I'm using iSeries Python 2.3.3. The fact that strings are natively EBCDIC can be a problem; it's definitely one of the reasons many third-party packages won't work as-is, even if they are pure Python. (In some cases they can be tweaked and massaged i...
[ 7, 5, 4, 3, 0 ]
[]
[]
[ "ibm_midrange", "python" ]
stackoverflow_0000752349_ibm_midrange_python.txt
Q: heapq.nlargest index of returned result in original sequence How do I return the index in the original list of the nth largest items of an iterable heapq.nlargest(2, [100, 2, 400, 500, 400]) output = [(3,500), (2, 400)] This already cost me a couple hours. I can't figure it out. A: >>> seq = [100, 2, 400, 500,...
heapq.nlargest index of returned result in original sequence
How do I return the index in the original list of the nth largest items of an iterable heapq.nlargest(2, [100, 2, 400, 500, 400]) output = [(3,500), (2, 400)] This already cost me a couple hours. I can't figure it out.
[ ">>> seq = [100, 2, 400, 500, 400]\n>>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])\n[(3, 500), (2, 400)]\n\n", "You can use list.index in combination with map, which is fast for small n (beware the list.index returns the index in the list of the first item whose value is x):\n>>> iterable = [100, 2, 40...
[ 29, 6 ]
[]
[]
[ "heap", "python", "sorting" ]
stackoverflow_0003139869_heap_python_sorting.txt
Q: Python limited multithreading As you surely know, I can do multithreading to download files from the Internet faster. But if I send lots of requests to the same website, I could be black listed. So could you help me to implement something like "I've got a list of urls. I want you to download all of these files bu...
Python limited multithreading
As you surely know, I can do multithreading to download files from the Internet faster. But if I send lots of requests to the same website, I could be black listed. So could you help me to implement something like "I've got a list of urls. I want you to download all of these files but if 10 downloads are already runni...
[ "Using threads doesn't \"download files from the Internet faster\". You have only one network card and one internet connection so that's just not true.\nThe threads are being used to wait, and you can't wait faster.\nYou can use a single thread and be as fast, or even faster -- Just don't wait for the response of o...
[ 4, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003139513_multithreading_python.txt
Q: Converting from utf-16 to utf-8 in Python 3 I'm programming in Python 3 and I'm having a small problem which I can't find any reference to it on the net. As far as I understand the default string in is utf-16, but I must work with utf-8, I can't find the command that will convert from the default one to utf-8. I'd...
Converting from utf-16 to utf-8 in Python 3
I'm programming in Python 3 and I'm having a small problem which I can't find any reference to it on the net. As far as I understand the default string in is utf-16, but I must work with utf-8, I can't find the command that will convert from the default one to utf-8. I'd appreciate your help very much.
[ "In Python 3 there are two different datatypes important when you are working with string manipulation. First there is the string class, an object that represents unicode code points. Important to get is that this string is not some bytes, but really a sequence of characters. Secondly, there is the bytes class, whi...
[ 7 ]
[]
[]
[ "character_encoding", "python", "python_3.x", "utf_16", "utf_8" ]
stackoverflow_0003140010_character_encoding_python_python_3.x_utf_16_utf_8.txt
Q: appcfg.py: error: no such option: --dump on google-app-engine Possible Duplicate: How can I use the Google App engine bulkloader to back up all my data? i follow this article :http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html and want to download all data from my app , but when i use ...
appcfg.py: error: no such option: --dump on google-app-engine
Possible Duplicate: How can I use the Google App engine bulkloader to back up all my data? i follow this article :http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html and want to download all data from my app , but when i use the next code,it show error: D:\zjm_demo\app>appcfg.py --dump --ap...
[ "The documentation appears to be incorrect:\nI found that I had to use download_data instead of --dump and --application instead of --app_id, for example:\nappcfg.py download_data --application=app_id --url=http://etc --filename=file \n\nThis is a duplicate of How can I use the Google App engine bulkloader to back ...
[ 1, 0, 0 ]
[]
[]
[ "dump", "google_app_engine", "python" ]
stackoverflow_0003066934_dump_google_app_engine_python.txt
Q: News sources for python django I find myself continually sifting through the net to keep up with Python/Django/web development trends and news. Does anyone recommend any good news sites that focus on web development or they Python community? For example, what new Django modules are popular or interesting new jQu...
News sources for python django
I find myself continually sifting through the net to keep up with Python/Django/web development trends and news. Does anyone recommend any good news sites that focus on web development or they Python community? For example, what new Django modules are popular or interesting new jQuery plugins, etc. Just curious to ...
[ "The Django community aggregator is a great source of news and information about what people are doing with Django.\n", "Coder.io lists Django news too but Django's own community page is my primary source. \nhttp://coder.io/tag/django\n", "Django Dose is great. They have a bit or erratic updates (but they're ba...
[ 4, 2, 1, 1 ]
[]
[]
[ "django", "feed", "python" ]
stackoverflow_0003130494_django_feed_python.txt
Q: Templating and form processing toolkits to use with twisted.web As the title states, I am looking for something, that will help me automate form processing (validation/rendering/etc) in twisted.web. I am also looking for a suitable templating toolkit to use with it. As for templating, it is not so much of an issue...
Templating and form processing toolkits to use with twisted.web
As the title states, I am looking for something, that will help me automate form processing (validation/rendering/etc) in twisted.web. I am also looking for a suitable templating toolkit to use with it. As for templating, it is not so much of an issue as there are a lot of libraries in python, that do it. I was conside...
[ "I really like Jinja2. It's an improved form of the django templating system. I use it pretty extensively in my projects.\nFor form processing, you may want to check out formosa.\n", "My experience of Nevow is that examples and documentation are hard to find on the web. There are some basic ones linked from the N...
[ 1, 1 ]
[]
[]
[ "forms", "python", "templates", "twisted", "twisted.web" ]
stackoverflow_0003128548_forms_python_templates_twisted_twisted.web.txt
Q: Do dictionaries in Python offer the best way to formulate switch-like statements? I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way: errstr = {404: "404 Not Found", 405: "405 Method Not Allowed"} if code in errstr: ...
Do dictionaries in Python offer the best way to formulate switch-like statements?
I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way: errstr = {404: "404 Not Found", 405: "405 Method Not Allowed"} if code in errstr: print errstr[code];
[ "Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-larg...
[ 4 ]
[]
[]
[ "conditional", "dictionary", "python", "switch_statement" ]
stackoverflow_0003140928_conditional_dictionary_python_switch_statement.txt
Q: SSH Dynamic Port Forwarding ('ssh -D') in Python I'm looking for a way to implement SSH Dynamic Port Forwarding ('ssh -D') under Python. The problem is that it has to work under Windows, i.e., running SSH with popen/pexec/etc. won't work. Any ideas? cheers, Bruno Nery. A: Have you tried Paramiko? A: There are ...
SSH Dynamic Port Forwarding ('ssh -D') in Python
I'm looking for a way to implement SSH Dynamic Port Forwarding ('ssh -D') under Python. The problem is that it has to work under Windows, i.e., running SSH with popen/pexec/etc. won't work. Any ideas? cheers, Bruno Nery.
[ "Have you tried Paramiko?\n", "There are ssh executables for Windows, so you can uses the subprocess.Popen approach. This is not exactly elegant, a pure Python approach would be better.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "ssh", "ssh_tunnel", "tunneling", "windows" ]
stackoverflow_0003141063_python_ssh_ssh_tunnel_tunneling_windows.txt
Q: Python DataError coming from stored procedure, but no error when run manually I am getting this error: DataError: (DataError) invalid input syntax for integer: "1.50" CONTEXT: PL/pgSQL function "sp_aggregate_cart" line 82 at FOR over EXECUTE statement 'SELECT total_items, subtotal, is_shipping_required, discount_...
Python DataError coming from stored procedure, but no error when run manually
I am getting this error: DataError: (DataError) invalid input syntax for integer: "1.50" CONTEXT: PL/pgSQL function "sp_aggregate_cart" line 82 at FOR over EXECUTE statement 'SELECT total_items, subtotal, is_shipping_required, discount_other, is_shipping_discount FROM sp_aggregate_cart(8135)' {} When running my appli...
[ "the buy_object_query was selecting things in the wrong order. It selects into the type I created at the beginning of that code buy_object_info. I was selecting the decimal into the integer\n" ]
[ 1 ]
[]
[]
[ "plpgsql", "postgresql", "python", "stored_procedures" ]
stackoverflow_0003132893_plpgsql_postgresql_python_stored_procedures.txt
Q: Keyword argument in unpacking argument list/dict cases in Python For python, I could use unpacking arguments as follows. def hello(x, *y, **z): print 'x', x print 'y', y print 'z', z hello(1, *[1,2,3], a=1,b=2,c=3) hello(1, *(1,2,3), **{'a':1,'b':2,'c':3}) x = 1 y = (1, 2, 3) z = {'a': 1, 'c': 3, ...
Keyword argument in unpacking argument list/dict cases in Python
For python, I could use unpacking arguments as follows. def hello(x, *y, **z): print 'x', x print 'y', y print 'z', z hello(1, *[1,2,3], a=1,b=2,c=3) hello(1, *(1,2,3), **{'a':1,'b':2,'c':3}) x = 1 y = (1, 2, 3) z = {'a': 1, 'c': 3, 'b': 2} But, I got an error if I use keyword argument as follows. he...
[ "Regardless of the order in which they are specified, positional arguments get assigned prior to keyword arguments. In your case, the positional arguments are (1, 2, 3) and the keyword arguments are x=1, a=1, b=2, c=3. Because positional arguments get assigned first, the parameter x receives 1 and is not eligible f...
[ 9 ]
[]
[]
[ "argument_passing", "python" ]
stackoverflow_0003141152_argument_passing_python.txt
Q: Checking when shutil.copyfile is done I have a such code: for file in file_list: shutil.copyfile(file,newpath) #do further actions And here is the question, at #do further actions I use the copied f iles thus I need to make sure the shutil.copyfile functions finish their task. How can I make sure of this ? ...
Checking when shutil.copyfile is done
I have a such code: for file in file_list: shutil.copyfile(file,newpath) #do further actions And here is the question, at #do further actions I use the copied f iles thus I need to make sure the shutil.copyfile functions finish their task. How can I make sure of this ?
[ "The shutil functions should return only after the operation is finished. If nothing funny is going on on the OS level it should be safe this way.\nIf you know the size of the file you could check if that is correct.\n", "copyfile is a blocking function. By the time you get to #do further actions it should alway...
[ 5, 3 ]
[]
[]
[ "file_copying", "python", "shutil" ]
stackoverflow_0003141296_file_copying_python_shutil.txt
Q: In Eclipse PyDev is there a way to exclude arbitrary file-types from the Pydev Package explorer? If you click on the icon resembling a downard-pointing triangle in the PyDev Package Explorer and then select "Customize View", The "Available Customizations" pop-down allows the user to select which of a standard set ...
In Eclipse PyDev is there a way to exclude arbitrary file-types from the Pydev Package explorer?
If you click on the icon resembling a downard-pointing triangle in the PyDev Package Explorer and then select "Customize View", The "Available Customizations" pop-down allows the user to select which of a standard set of files are visible in the package explorer. That's great if you wish to exlude or include certain s...
[ "To the left of the down arrow is the \"Setup custom filters\" button. You can enter custom filters delimited by commas. If that file name indeed has a comma in it, then you will have to enter the filter as *cover since *,cover is treated as two separate filters.\n" ]
[ 7 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003138677_eclipse_pydev_python.txt
Q: associative list python i am parsing some html form with Beautiful soup. Basically i´ve around 60 input fields mostly radio buttons and checkboxes. So far this works with the following code: from BeautifulSoup import BeautifulSoup x = open('myfile.html','r').read() out = open('outfile.csv','w') soup = BeautifulSou...
associative list python
i am parsing some html form with Beautiful soup. Basically i´ve around 60 input fields mostly radio buttons and checkboxes. So far this works with the following code: from BeautifulSoup import BeautifulSoup x = open('myfile.html','r').read() out = open('outfile.csv','w') soup = BeautifulSoup(x) values = soup.findAll('i...
[ "I'm fairly sure you can use the attribute name like a key for a hash:\nprint cell['name']\n\n", "My suggestion is to make values a dict. If soup.findAll returns a list of tuples as you seem to imply, then it's as simple as:\nvalues = dict(soup.findAll('input',checked=\"checked\"))\n\nAfter that you can simply re...
[ 2, 2 ]
[]
[]
[ "associative", "beautifulsoup", "list", "python" ]
stackoverflow_0003141530_associative_beautifulsoup_list_python.txt
Q: Django one database for each application in the same project I have a Django project that contains two applications App1 and App2 I have configured two databases DB1 and DB2 when I use python manage.py syncdb the tables corresponding to model of the two application are created in the first database How ca...
Django one database for each application in the same project
I have a Django project that contains two applications App1 and App2 I have configured two databases DB1 and DB2 when I use python manage.py syncdb the tables corresponding to model of the two application are created in the first database How can I configure Django to make the model of the first application go...
[ "You need to implement Automatic database routing.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003141785_django_python.txt
Q: Increment a Version Number using Regular Expression I am trying to increment a version number using regex but I can't seem to get the hang of regex at all. I'm having trouple with the symbols in the string I am trying to read and change. The code I have so far is: version_file = "AssemblyInfo.cs" read_file = open...
Increment a Version Number using Regular Expression
I am trying to increment a version number using regex but I can't seem to get the hang of regex at all. I'm having trouple with the symbols in the string I am trying to read and change. The code I have so far is: version_file = "AssemblyInfo.cs" read_file = open(version_file).readlines() write_file = open(version_fil...
[ "If you specify the version as \"1.0.0.*\" then AFAIK it gets updated on each build automagically, at least if you're using Visual Studio.NET.\nI'm not sure regex is your best bet, but one way of doing it would be this:\nimport re\n\n# Don't bother matching everything, just the bits that matter.\npat = re.compile(r...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003141642_python_regex.txt
Q: In Django, how do I set the default so that every model is created with INNODB? Right now, Django defaults to MYISAM...but I want to change it so that everytime I create a new table it is innodb. A: Put that in settings.py: DATABASE_ENGINE = 'mysql' DATABASE_OPTIONS = {"init_command": "SET storage_engine=INNODB"...
In Django, how do I set the default so that every model is created with INNODB?
Right now, Django defaults to MYISAM...but I want to change it so that everytime I create a new table it is innodb.
[ "Put that in settings.py:\nDATABASE_ENGINE = 'mysql'\nDATABASE_OPTIONS = {\"init_command\": \"SET storage_engine=INNODB\"}\n\nUPDATE\nFor Django >= 1.2 this should be write like this:\nDATABASES = {\n 'default': {\n 'ENGINE': 'mysql',\n 'OPTIONS': {'init_c...
[ 2 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0003136417_database_django_mysql_python.txt
Q: Can python share info like .net remoting? I known python can use pipe to communicate between two process of py. But, data and functions of this method are not clear. I like .net remoting better. So, can python realize that approach? A: Yes, you can do this using (for example) PYRO (Python Remote Objects). A: ...
Can python share info like .net remoting?
I known python can use pipe to communicate between two process of py. But, data and functions of this method are not clear. I like .net remoting better. So, can python realize that approach?
[ "Yes, you can do this using (for example) PYRO (Python Remote Objects).\n", "The ability to share \"data and functions\" is better known as a web service or remote procedure call (RPC). This has the benefit of working between nearly any computer language on any operating system, whereas \".net remoting\" will mai...
[ 1, 0 ]
[]
[]
[ "communication", "process", "python", "remoting" ]
stackoverflow_0003141844_communication_process_python_remoting.txt
Q: Project Euler - Problem 160 For any N, let f(N) be the last five digits before the trailing zeroes in N!. For example, 9! = 362880 so f(9)=36288 10! = 3628800 so f(10)=36288 20! = 2432902008176640000 so f(20)=17664 Find f(1,000,000,000,000) I've successfully tackled this question for the given examples, m...
Project Euler - Problem 160
For any N, let f(N) be the last five digits before the trailing zeroes in N!. For example, 9! = 362880 so f(9)=36288 10! = 3628800 so f(10)=36288 20! = 2432902008176640000 so f(20)=17664 Find f(1,000,000,000,000) I've successfully tackled this question for the given examples, my function can correctly find f(...
[ "mul can get very big. Is that necessary? If I asked you to compute the last 5 non-zero digits of 1278348572934847283948561278387487189900038 * 38758\nby hand, exactly how many digits of the first number do you actually need to know?\n", "Building strings frequently is expensive. I'd rather use the modulo operato...
[ 7, 2, 1 ]
[]
[]
[ "math", "optimization", "python" ]
stackoverflow_0003140533_math_optimization_python.txt
Q: Passing variables/functions between imported modules I'm going to throw out some pseudocode. Then explain what I want, because I am not sure how to otherwise. File_A class Panel_A(wx.Panel) def __init__(self): button_a = wx.Button(parent=self) def onButton(self, event): pass to list view ...
Passing variables/functions between imported modules
I'm going to throw out some pseudocode. Then explain what I want, because I am not sure how to otherwise. File_A class Panel_A(wx.Panel) def __init__(self): button_a = wx.Button(parent=self) def onButton(self, event): pass to list view File_B class Panel_B(wx.panel): def __init__(self): ...
[ "Use the delegate design pattern:\n(Pass in panel_b as an argument when instantiating Panel_A objects):\n# File_A\nclass Panel_A(wx.Panel)\n def __init__(self,panel_b):\n self.panel_b=panel_b\n button_a = wx.Button(parent=self)\n\n def onButton(self, event):\n pass to self.panel_b.listvie...
[ 1, 0 ]
[]
[]
[ "import", "module", "python", "wxpython" ]
stackoverflow_0003142031_import_module_python_wxpython.txt
Q: Optimising memory usage in numpy The following program loads two images with PyGame, converts them to Numpy arrays, and then performs some other Numpy operations (such as FFT) to emit a final result (of a few numbers). The inputs can be large, but at any moment only one or two large objects should be live. A test...
Optimising memory usage in numpy
The following program loads two images with PyGame, converts them to Numpy arrays, and then performs some other Numpy operations (such as FFT) to emit a final result (of a few numbers). The inputs can be large, but at any moment only one or two large objects should be live. A test image is about 10M pixels, which tran...
[ "if I understand correctly, you are calculating a convolution between two images. The Scipy package contains a dedicated module for that (ndimage), which might be more memory efficient than the \"manual\" approach via Fourier transforms. It would be good to try using it instead of going through Numpy.\n", "This...
[ 1, 1 ]
[]
[]
[ "memory_management", "numpy", "pygame", "python" ]
stackoverflow_0003138669_memory_management_numpy_pygame_python.txt
Q: Python base64.decode does not seem to work on windows I am consuming a webservice (written in java) - that basically returns a byte[] array (the SOAP equivalent is base64 encoded binary data). I am using the python suds library and the following code works for me on my mac (and on cygwin under windows), but the d...
Python base64.decode does not seem to work on windows
I am consuming a webservice (written in java) - that basically returns a byte[] array (the SOAP equivalent is base64 encoded binary data). I am using the python suds library and the following code works for me on my mac (and on cygwin under windows), but the decoding does not work on vanilla windows (python 2.6.5). I ...
[ "Try\nf = open(\"tools.tar.gz\", \"wb\")\n\nIt's crucial to tell Python that it's a binary file (in Py3, it also becomes crucial on Unixy systems, but in Py2 it's not strictly needed on them, which is why your code works on MacOSX): the default is text, which, on Windows, translates each \\n written into \\r\\n on ...
[ 7 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003142107_encoding_python.txt
Q: Python Syntax Problem I'm just getting back into Project Euler and have lost my account and solutions, so I'm back on problem 7. However, my code doesn't work. It seems fairly elementary to me, can someone help me debug my (short) script? Should find the 10001st Prime. #!/usr/bin/env python #encoding: utf-8 """ P7...
Python Syntax Problem
I'm just getting back into Project Euler and have lost my account and solutions, so I'm back on problem 7. However, my code doesn't work. It seems fairly elementary to me, can someone help me debug my (short) script? Should find the 10001st Prime. #!/usr/bin/env python #encoding: utf-8 """ P7.py Created by Andrew Leve...
[ "The syntax is fine (in Python 2). The semantics has some avoidable complications, and this off-by-one bug:\nfor x in range(2,int(sqrt(num))):\n if( num % x == 0 ):\n flag = False\n\nrange(2, Y) goes from 2 included to Y excluded -- so you're often not checking the last possible divisor and thereby deemi...
[ 5, 1 ]
[]
[]
[ "primes", "python" ]
stackoverflow_0003142318_primes_python.txt
Q: ZeroConf Chat with Python I am trying to set up a Bonjour (or Ahavi) chatbot for our helpdesk system that would answer basic questions based on a menu system. The basis of my question is how do I get python to create the bot so that it connects to the network as a chat client. Basically, anyone on my network with ...
ZeroConf Chat with Python
I am trying to set up a Bonjour (or Ahavi) chatbot for our helpdesk system that would answer basic questions based on a menu system. The basis of my question is how do I get python to create the bot so that it connects to the network as a chat client. Basically, anyone on my network with iChat or Empathy (or any chat p...
[ "What you have here is a disconnect between what you want to do and how to do it. Zeroconf/Avahi are about service discovery. What you describe is a chat bot. Chat bots connect to an existing chat server. Apple with iChat has slightly blurred these lines.\niChat (and presumably other chat clients that implement the...
[ 1, 0 ]
[]
[]
[ "bonjour", "chatbot", "linux", "python", "zeroconf" ]
stackoverflow_0003072934_bonjour_chatbot_linux_python_zeroconf.txt
Q: Lookahead assertions seem to short-circuit ordering of alternates in regular expressions I'm working with a (Python-flavored) regular expression to recognize common and idiosyncratic forms and abbreviations of scripture references. Given the following verbose snippet: >>> cp = re.compile(ur""" (?:( # N...
Lookahead assertions seem to short-circuit ordering of alternates in regular expressions
I'm working with a (Python-flavored) regular expression to recognize common and idiosyncratic forms and abbreviations of scripture references. Given the following verbose snippet: >>> cp = re.compile(ur""" (?:( # Numbered books (?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ? (?:John|Joh|Jhn|Jo|Jn|...
[ "I've given up after a little try to follow what _sre.so is doing in this case (too complicated!) but a \"blind fix\" I tried seemed to work -- switch to a negative lookahead assertion for the complementary character set...:\ncp = re.compile(ur\"\"\"\n(?:(\n # Numbered books\n (?:(?:Third|Thir|Thi|III|3rd|Th|...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003142148_python_regex.txt
Q: os.path.getmtime of shared files in Dropbox I want to run a script to check whether certain files in my Dropbox folder have changed. I am currently using os.path.getmtime() to check that the modified time is in some window of time.time(). The problem is that if I modify a file in my Dropbox folder from a different...
os.path.getmtime of shared files in Dropbox
I want to run a script to check whether certain files in my Dropbox folder have changed. I am currently using os.path.getmtime() to check that the modified time is in some window of time.time(). The problem is that if I modify a file in my Dropbox folder from a different computer than where the script is set to run, th...
[ "It looks that Dropbox preserves mtime when synchronizing files. Try to detect changed file by changed file size and/or checksum (MD5, SHA1 or so) instead of modification time. Or just ask Dropbox :) (I don't know if it has any API for this).\n" ]
[ 1 ]
[]
[]
[ "dropbox", "python" ]
stackoverflow_0003142770_dropbox_python.txt
Q: What is the best way to do a list[0] with a default value in python? I am looking for a list functionnality in Python. I am doing this : abcd = [1, 2, 3, 4] try: item = list[5] except: item = 0 How can I make it looks like : item = abcd.get(5, 0) Thanks for your help A: You cannot add a get method to t...
What is the best way to do a list[0] with a default value in python?
I am looking for a list functionnality in Python. I am doing this : abcd = [1, 2, 3, 4] try: item = list[5] except: item = 0 How can I make it looks like : item = abcd.get(5, 0) Thanks for your help
[ "You cannot add a get method to the list class, but you can use either a function:\ndef get(alist, index, default):\n try: return alist[index]\n except IndexError: return default\n\nwhich gives you the usage example:\nabcd = [1, 2, 3, 4]\nitem = get(abcd, 5, 0)\n\nor a subclass of list:\nclass mylist(list):\n de...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003142533_python.txt
Q: I want to rank document and store them in a list in python I am just a beginner in python. I have document score= {1:0.98876, 8:0.12245, 13:0.57689} which is stored in dictionary. The keys are corresponding to a series of document id and the values are corresponding to the score for each document id. How do I rank...
I want to rank document and store them in a list in python
I am just a beginner in python. I have document score= {1:0.98876, 8:0.12245, 13:0.57689} which is stored in dictionary. The keys are corresponding to a series of document id and the values are corresponding to the score for each document id. How do I rank the document based on the scores? inverse=[(value, key) for key...
[ "sorted(score.items(), key=lambda x:-x[1])\n\nshould do the trick\nThe order of the elements in a dictionary is not defined, so the result of the sorting has to be stored in a list (or an OrderedDict).\nYou should convert it to a list of tuples using items(). With sorted() you can sort them, the key parameter tells...
[ 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003142987_python_sorting.txt
Q: PyGTK/GIO: monitor directory for changes recursively Take the following demo code (from the GIO answer to this question), which uses a GIO FileMonitor to monitor a directory for changes: import gio def directory_changed(monitor, file1, file2, evt_type): print "Changed:", file1, file2, evt_type gfile = gio.Fi...
PyGTK/GIO: monitor directory for changes recursively
Take the following demo code (from the GIO answer to this question), which uses a GIO FileMonitor to monitor a directory for changes: import gio def directory_changed(monitor, file1, file2, evt_type): print "Changed:", file1, file2, evt_type gfile = gio.File(".") monitor = gfile.monitor_directory(gio.FILE_MONITOR...
[ "\n\"Is there an easy way to make it\n recursive?\"\n\nI'm not aware of any \"easy way\" to achieve this. The underlying systems, such as inotify on Linux or kqueue on BSDs don't provide facilities to automatically add recursive watches. I'm also not aware of any library layering what you want atop GIO.\nSo you'll...
[ 2, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003068839_pygtk_python.txt
Q: How to send file to serial port using kermit protocol in python I have device connected through serial port to PC. Using c-kermit I can send commands to device and read output. I can also send files using kermit protocol. In python we have pretty nice library - pySerial. I can use it to send/receive data from devi...
How to send file to serial port using kermit protocol in python
I have device connected through serial port to PC. Using c-kermit I can send commands to device and read output. I can also send files using kermit protocol. In python we have pretty nice library - pySerial. I can use it to send/receive data from device. But is there some nice solution to send files using kermit protoc...
[ "You should be able to do it via the subprocess module. The following assumes that you can send commands to your remote machine and parse out the results already. :-)\nI don't have anything to test this on at the moment, so I'm going to be pretty general.\nRoughly:\n\nuse pyserial to connect to the remote system th...
[ 1 ]
[]
[]
[ "kermit", "pyserial", "python", "serial_port" ]
stackoverflow_0002237483_kermit_pyserial_python_serial_port.txt
Q: "/1/2/3/".split("/") It's too hot & I'm probably being retarded. >>> "/1/2/3/".split("/") ['', '1', '2', '3',''] Whats with the empty elements at the start and end? Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/...
"/1/2/3/".split("/")
It's too hot & I'm probably being retarded. >>> "/1/2/3/".split("/") ['', '1', '2', '3',''] Whats with the empty elements at the start and end? Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/stdtypes.html "Return a li...
[ "Compare with:\n\"1/2/3\".split(\"/\")\n\nEmpty elements are still elements.\nYou could use strip('/') to trim the delimiter from the beginning/end of your string.\n", "As JLWarlow says, you have an extra '/' in the string. Here's another example:\n>>> \"//2//3\".split('/')\n['', '', '2', '', '3']\n\n", "Slashe...
[ 18, 4, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003142428_python_string.txt
Q: python import depth I've noticed that importing a module will import its functions and methods, and the functions and methods of those as well. Is there a set rule for how many levels down python will import when you import an upper-level module? edit sorry, I think I've been misunderstood by the answers so far r...
python import depth
I've noticed that importing a module will import its functions and methods, and the functions and methods of those as well. Is there a set rule for how many levels down python will import when you import an upper-level module? edit sorry, I think I've been misunderstood by the answers so far responding about multiple ...
[ "No, python will import what it needs to import. However, each module is only imported once. For example, if one module does import sys and another module does import sys, it will not physically do it twice.\n", "Not really. A module imports stuff from other modules because it needs to use them in that module, ot...
[ 3, 1, 1 ]
[]
[]
[ "depth", "import", "python" ]
stackoverflow_0003143106_depth_import_python.txt
Q: How to get Field names from a SQL database into a list in python Here is a the code I have so far: from ConfigParser import * import MySQLdb configuration = ConfigParser() configuration.read('someconfigfile.conf') db = MySQLdb.connect( host = configuration.get('DATABASE', 'MYSQL_HOST'), user = configu...
How to get Field names from a SQL database into a list in python
Here is a the code I have so far: from ConfigParser import * import MySQLdb configuration = ConfigParser() configuration.read('someconfigfile.conf') db = MySQLdb.connect( host = configuration.get('DATABASE', 'MYSQL_HOST'), user = configuration.get('DATABASE', 'MYSQL_USER'), passwd = configuration.get('...
[ "Don't shadow built-ins (list), change to \nalist = cursor.fetchall()\nThis generator expression will get you the column names in a tuple:\ntuple(i[0] for i in alist)\n" ]
[ 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003143150_mysql_python.txt
Q: What's an elegant way to create a dictionary from another dictionary's keys and an array of values? How can I create another dictionary using the keys of another dictionary, and an array of values? I thought about doing this: zipped = zip(theExistingDict.keys(), arrayOfValues) myNewDict = dict(zipped) However, th...
What's an elegant way to create a dictionary from another dictionary's keys and an array of values?
How can I create another dictionary using the keys of another dictionary, and an array of values? I thought about doing this: zipped = zip(theExistingDict.keys(), arrayOfValues) myNewDict = dict(zipped) However, this doesn't quite work, each value from arrayOfValues are paired with an arbitrary key in the resulting di...
[ "As others have mentioned, a Dictionary doesn't have any order defined in it. The python docs say, \"Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.\"\nIf you're looking to use the origi...
[ 4, 4, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003142012_dictionary_python.txt
Q: implementing chop() using iterators Current version: def chop(ar,size): p=len(ar)/size for i in xrange(p): yield ar[(i*size):((i+1)*size)] ar is type of list(). What i want is that chop() takes iterator and return iterator. for i in chop(xrange(9),3): for j in i: print j, print ...
implementing chop() using iterators
Current version: def chop(ar,size): p=len(ar)/size for i in xrange(p): yield ar[(i*size):((i+1)*size)] ar is type of list(). What i want is that chop() takes iterator and return iterator. for i in chop(xrange(9),3): for j in i: print j, print prints 0 1 2 3 4 5 6 7 8
[ "There's an implementation in the itertools documentation:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\n" ]
[ 2 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0003143371_iterator_python.txt
Q: retrieving uploaded images with django's ImageField this is the code in my models file: from django.db import models class Studio(models.Model): ..... ..... metroimage = models.ImageField(upload_to='images', blank=True) this is the code on the template file: {% for place in studio %} ......
retrieving uploaded images with django's ImageField
this is the code in my models file: from django.db import models class Studio(models.Model): ..... ..... metroimage = models.ImageField(upload_to='images', blank=True) this is the code on the template file: {% for place in studio %} ..... ..... <img class="metr...
[ "I'd guess your MEDIA_URL settings (in settings.py) is to blame for the extra slash. \n" ]
[ 1 ]
[]
[]
[ "django", "imagefield", "python" ]
stackoverflow_0003142883_django_imagefield_python.txt
Q: py-amqp/flopsy: Waiting for a single AMQP message in Python I have a similar question to this one: It's very easy in py-amqp/flopsy to say "I'm going to wait forever, and I want this callback to be called whenever a message comes in," but I can't find any way of saying "OK, I got the message I want now stop waitin...
py-amqp/flopsy: Waiting for a single AMQP message in Python
I have a similar question to this one: It's very easy in py-amqp/flopsy to say "I'm going to wait forever, and I want this callback to be called whenever a message comes in," but I can't find any way of saying "OK, I got the message I want now stop waiting." (Maybe a GOTO? Just kidding...) Is there an elegant way of do...
[ "OK, maybe this should have been obvious to me: If you register a callback in flopsy (which is a thin wrapper around amqplib) with\nconsumer.register('kind', callback_func)\nconsumer.wait()\n# more code goes here...\n\nthen you can raise an Exception in callback_func to get to the rest of the code.\nBonus question:...
[ 1 ]
[]
[]
[ "amqp", "flopsy", "py_amqplib", "python" ]
stackoverflow_0003135629_amqp_flopsy_py_amqplib_python.txt
Q: How can I use google app engine? I've begun planning a kind of web store interface that I want to work on soon. I'm starting to import products from China and want to have a completely unique feel for my site. Now I'm kinda a google fanboy and have heard alot about google app engine. Mostly I like the hosting avai...
How can I use google app engine?
I've begun planning a kind of web store interface that I want to work on soon. I'm starting to import products from China and want to have a completely unique feel for my site. Now I'm kinda a google fanboy and have heard alot about google app engine. Mostly I like the hosting available with google more then anything t...
[ "It is hard to say if App Engine is suited to your particular needs without more details about what functionality you want your web store to present. It also depends a little bit on your background and experience.\nHowever, the \"app like feel\" and crafting a \"completely unique feel\" for your site is something ...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications", "webstore" ]
stackoverflow_0003143703_google_app_engine_python_web_applications_webstore.txt
Q: Python profiler usage with objects I have a specific question regarding the usage of profiler. I am new to python programming I am trying to profile a function which I want to invoke as a class method, something like this import profile class Class: def doSomething(): do here .. def callMethod():...
Python profiler usage with objects
I have a specific question regarding the usage of profiler. I am new to python programming I am trying to profile a function which I want to invoke as a class method, something like this import profile class Class: def doSomething(): do here .. def callMethod(): self.doSomething() instead of ...
[ "Fixed!!!\nInstead of profile, I used cProfile module that as per the python docs has much lesser overhead\nRef : http://docs.python.org/library/profile.html#introduction-to-the-profilers\nwith cProfiler, one can actually pass the local and global params using the runctx module\nso for the same problem, I did the f...
[ 13, 3 ]
[]
[]
[ "profiler", "python" ]
stackoverflow_0003142901_profiler_python.txt
Q: Python code refactoring question. Simplification I have code that looks something like this: self.ui.foo = False self.ui.bar = False self.ui.item = False self.ui.item2 = False self.ui.item3 = False And I would like to turn it into something like this: items = [foo,bar,item,item2,item3] for elm in items: self...
Python code refactoring question. Simplification
I have code that looks something like this: self.ui.foo = False self.ui.bar = False self.ui.item = False self.ui.item2 = False self.ui.item3 = False And I would like to turn it into something like this: items = [foo,bar,item,item2,item3] for elm in items: self.ui.elm = False But obviously just having the variabl...
[ "Here's how you do that:\nitems = ['foo','bar','item','item2','item3']\nfor elm in items:\n setattr(self.ui, elm, False)\n\n", "items needs to be a list of strings.\nitems = ['foo', 'bar', 'item', 'item2', 'item3']\nfor elm in items:\n setattr(self.ui, elm, False)\n\n" ]
[ 6, 4 ]
[]
[]
[ "list", "python", "refactoring" ]
stackoverflow_0003143844_list_python_refactoring.txt
Q: Is there a way to view the source code of a function, class, or module from the python interpreter? Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods) A: If you plan to use python ...
Is there a way to view the source code of a function, class, or module from the python interpreter?
Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods)
[ "If you plan to use python interactively it is hard to beat ipython. To print the source of any known function you can then use %psource.\nIn [1]: import ctypes\nIn [2]: %psource ctypes.c_bool\nclass c_bool(_SimpleCData):\n_type_ = \"?\"\n\nThe output is even colorized. You can also directly invoke your $EDITOR on ...
[ 19, 11 ]
[]
[]
[ "python" ]
stackoverflow_0003143888_python.txt
Q: Parent/Child(ren) Hierarchy / "Nested Sets", in Python/Django I'm using Django/Python, but pseudo-code is definitely acceptable here. Working with some models that already exist, I have Employees that each have a Supervisor, which is essentially a Foreign Key type relationship to another Employee. Where the Empl...
Parent/Child(ren) Hierarchy / "Nested Sets", in Python/Django
I'm using Django/Python, but pseudo-code is definitely acceptable here. Working with some models that already exist, I have Employees that each have a Supervisor, which is essentially a Foreign Key type relationship to another Employee. Where the Employee/Supervisor hierarchy is something like this: Any given Employ...
[ "You don't have to touch your models to be able to use django-mptt; you just have to create a parent field on your model, django-mptt creates all the other attributes for mptt automaitcally, when you register your model: mptt.register(MyModel). \nThough if you just need the 'upline' hierarchy you wouldn't need nes...
[ 2, 0 ]
[]
[]
[ "django", "hierarchy", "parent_child", "python" ]
stackoverflow_0003143898_django_hierarchy_parent_child_python.txt
Q: using Blobstore Python API with ajax there is any sample showing how to use the blobstore api with ajax? when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error: blob_info = upload_files[0] IndexError: list index out of range I have this code in javascript f...
using Blobstore Python API with ajax
there is any sample showing how to use the blobstore api with ajax? when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error: blob_info = upload_files[0] IndexError: list index out of range I have this code in javascript function TestAjax() { var nombre="Some ran...
[ "I wrote a series of posts about exactly this.\n", "Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype=\"multipart/form-data\", right?\nWhen you're just sending a \"POST\" via ajax, you're losin...
[ 4, 2 ]
[]
[]
[ "blobstore", "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0003143337_blobstore_google_app_engine_javascript_jquery_python.txt
Q: Machine Learning Algorithm for Predicting Order of Events? Simple machine learning question. Probably numerous ways to solve this: There is an infinite stream of 4 possible events: 'event_1', 'event_2', 'event_4', 'event_4' The events do not come in in completely random order. We will assume that there are some c...
Machine Learning Algorithm for Predicting Order of Events?
Simple machine learning question. Probably numerous ways to solve this: There is an infinite stream of 4 possible events: 'event_1', 'event_2', 'event_4', 'event_4' The events do not come in in completely random order. We will assume that there are some complex patterns to the order that most events come in, and the r...
[ "This is essentially a sequence prediction problem, so you want Recurrent neural networks or hidden Markov models.\nIf you only have a fixed time to look back, time window approaches might suffice. You take the sequence data and split it into overlapping windows of length n. (eg. you split a sequence ABCDEFG into A...
[ 23, 13, 0, 0, 0 ]
[]
[]
[ "compression", "evolutionary_algorithm", "machine_learning", "neural_network", "python" ]
stackoverflow_0002524608_compression_evolutionary_algorithm_machine_learning_neural_network_python.txt
Q: simple fetch is really slow I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, I debugged and all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a ...
simple fetch is really slow
I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, I debugged and all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a few items out of a 100 item table...
[ "Have you tried using appstats? That will give you a breakdown on what parts of your page are specifically taking the most time, based on RPC information.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003143969_google_app_engine_python.txt
Q: Ruby version of to String method This question is about formatting ruby's strings. In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example: >>>$ python Python 2.6.4 (r264:7...
Ruby version of to String method
This question is about formatting ruby's strings. In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example: >>>$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4....
[ "[1,23,4].inspect #=> \"[1, 23, 4]\"\np [1,23,4] # Same as puts [1,23,4].inspect\n\n", "In Ruby, there are four methods that are typically available for getting a string representation of an object.\n\n#to_str: this is part of Ruby's standard type conversion protocols (similar to to_int, to_ary, to_float, …). It...
[ 9, 9, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0003144265_python_ruby.txt
Q: Accepting only numbers as input in Python Is there a way to accept only numbers in Python, say like using raw_input()? I know I can always get the input and catch a ValueError exception, but I was interested in knowing whether there was someway I could force the prompt to accept only numbers and freeze on any oth...
Accepting only numbers as input in Python
Is there a way to accept only numbers in Python, say like using raw_input()? I know I can always get the input and catch a ValueError exception, but I was interested in knowing whether there was someway I could force the prompt to accept only numbers and freeze on any other input.
[ "From the docs:\n\nHow do I get a single keypress at a time?\nFor Unix variants: There are several\n solutions. It’s straightforward to do\n this using curses, but curses is a\n fairly large module to learn. Here’s a\n solution without curses:\n\nimport termios, fcntl, sys, os\nfd = sys.stdin.fileno()\n\noldter...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003144529_python.txt
Q: a indexing question of ndarray for example, there is a matrix: import numpy as np A = np.array([[ 8. , -6. , 2. ], [-0.5, 8. , -6. ], [ 0.5, -0.5, 2. ]]) It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U]) I want to get L and U from A. U should be: U = np.array...
a indexing question of ndarray
for example, there is a matrix: import numpy as np A = np.array([[ 8. , -6. , 2. ], [-0.5, 8. , -6. ], [ 0.5, -0.5, 2. ]]) It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U]) I want to get L and U from A. U should be: U = np.array([[ 8., -6., 2.], [ 0...
[ "You don't need any index manipulation. Just use tril, triu and identity functions:\nimport numpy as np\nA = np.array([[ 8. , -6. , 2. ], \n [-0.5, 8. , -6. ], \n [ 0.5, -0.5, 2. ]])\n\nU = np.triu(A)\n\n#[[ 8. -6. 2.]\n# [-0. 8. -6.]\n# [ 0. -0. 2.]]\n\nL = np.tril(A, k=-1) + np.identi...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003107991_numpy_python.txt
Q: QSvgRenderer segmentation fault I realize specific questions like this aren't great, but I've spent several days trying to puzzle this out. Hopefully someone here can help. This python code using PyQt4 causes a segmentation fault: data = """<?xml version="1.0" ?> <svg height="1000" width="2000"> ...
QSvgRenderer segmentation fault
I realize specific questions like this aren't great, but I've spent several days trying to puzzle this out. Hopefully someone here can help. This python code using PyQt4 causes a segmentation fault: data = """<?xml version="1.0" ?> <svg height="1000" width="2000"> <text>blah</text> </s...
[ "Try making it draw on a QPixmap instead of a QImage.\nQt does cause segfaults once in a while, I usually just code around them.\nMaybe you could rasterize this SVG in Gimp and just load that.\n", "With only a minor change to make that run (defining width and height), it works for me. Note that I don't see any te...
[ 0, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "segmentation_fault" ]
stackoverflow_0003144361_pyqt_pyqt4_python_qt_segmentation_fault.txt
Q: Python question about time spent I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it? Thank you A: The best way would be to run some benchmark tests (to test individual functions) or Profiling (to te...
Python question about time spent
I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it? Thank you
[ "The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). Python comes with built-in Profilers.\nAlternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the p...
[ 15, 4 ]
[]
[]
[ "python", "timedelta" ]
stackoverflow_0003144898_python_timedelta.txt
Q: Using named arguments with variable length un-named arguments in Python I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions... I'd like to create a python function that takes two mandatory arguments, one named argument...
Using named arguments with variable length un-named arguments in Python
I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions... I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so: def my_functio...
[ "That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional argu...
[ 1 ]
[]
[]
[ "keyword_argument", "named_parameters", "python", "variadic_functions" ]
stackoverflow_0003145241_keyword_argument_named_parameters_python_variadic_functions.txt
Q: Another Python Scope Question - losing information going into if statement Not sure if I'm missing something obvious, but here's what is happening: I have a python 2.4.3 script that contains several RegEx objects. Below one of the regex objects is searching for all matches in a string (tMatchList). Even if tMatchL...
Another Python Scope Question - losing information going into if statement
Not sure if I'm missing something obvious, but here's what is happening: I have a python 2.4.3 script that contains several RegEx objects. Below one of the regex objects is searching for all matches in a string (tMatchList). Even if tMatchList is not null, it is printing an empty set after the 'if p:' step. This behavi...
[ "The findall may not create a list object. If it is some kind of generator function, then it has a value which is \"consumed\" by traversing the results once.\nAfter consuming the results yielded by this function, there are no more results.\ntMatchList = self._testReplacePDFTag.findall(lines)\n\np = self._pdfPathR...
[ 0, 0 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0003141534_python_scope.txt
Q: making a python object unsable after a finalize-type call I have a python object which wraps a sensitive and important resource on the system. I have a cleanup() function which safely releases various locks used by the object. I want to make sure that after a call to cleanup() the object becomes unusable. Ideally...
making a python object unsable after a finalize-type call
I have a python object which wraps a sensitive and important resource on the system. I have a cleanup() function which safely releases various locks used by the object. I want to make sure that after a call to cleanup() the object becomes unusable. Ideally, any call to any member function of the object would raises an...
[ "One way is to simply set all the instance variables to None. Then, doing pretty much anything will cause AttributeError or TypeError. A more sophisticated approach is to wrap instance methods with a decorator. The decorator can check if the close has been disposed. If so, it throws an exception:\nclass Unusabl...
[ 1 ]
[]
[]
[ "destructor", "object", "python", "resources" ]
stackoverflow_0003145353_destructor_object_python_resources.txt
Q: Executing a python script using subprocess.Popen() in a django view I've looked around a bit but I can't seem to solve this problem I have. I'd like to execute a python script within a view of my django app. I've placed the code I'd like to execute inside a django management command so it can be accessed via com...
Executing a python script using subprocess.Popen() in a django view
I've looked around a bit but I can't seem to solve this problem I have. I'd like to execute a python script within a view of my django app. I've placed the code I'd like to execute inside a django management command so it can be accessed via command line python manage.py command-name. I then tried to run this comman...
[ "Maybe you should use celery\n\nCelery is a task queue/job queue based\n on distributed message passing. It is\n focused on real-time operation\n\n", "I wasted a lot of time trying to implement something similar, but had the same problems as you. Eventually, I gave up and implemented a beanstalk queue to handle...
[ 3, 2 ]
[]
[]
[ "django", "multithreading", "python", "subprocess" ]
stackoverflow_0003144162_django_multithreading_python_subprocess.txt
Q: How can I group objects by their date in Django? I'm trying to select all objects in the articles table, and have them grouped by their date. I'm thinking it would look similar to this: articles = Article.objects.filter(pub_date__lte=datetime.date.today()).group_by(pub_date.day) articles = {'2010-01-01': (articleA...
How can I group objects by their date in Django?
I'm trying to select all objects in the articles table, and have them grouped by their date. I'm thinking it would look similar to this: articles = Article.objects.filter(pub_date__lte=datetime.date.today()).group_by(pub_date.day) articles = {'2010-01-01': (articleA, articleB, articleC...), '2010-01-02': (a...
[ "Here's a working example of ignacio's suggestion to use itertools.groupby. \nclass Article(object):\n def __init__(self, pub_date):\n self.pub_date = pub_date\n\n\nif __name__ == '__main__':\n from datetime import date\n import itertools\n import operator\n\n # You'll use your Article query ...
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003145246_django_python.txt
Q: Python: get number of items in generator without storing the items I have a generator for a large set of items. I want to iterate through them once, outputting them to a file. However, with the file format I currently have, I first have to output the number of items I have. I don't want to build a list of the item...
Python: get number of items in generator without storing the items
I have a generator for a large set of items. I want to iterate through them once, outputting them to a file. However, with the file format I currently have, I first have to output the number of items I have. I don't want to build a list of the items in memory, as there are too many of them and that would take a lot of ...
[ "If you can figure out how to just write a formula to calculate the size based on the parameters that control the generator, do that. Otherwise, I don't think you would save much time.\nInclude the generator here, and we'll try to do it for you!\n", "This cannot be done. Once a generator is exhausted it needs to ...
[ 5, 5, 5 ]
[]
[]
[ "generator", "memory", "performance", "python", "yield" ]
stackoverflow_0003145483_generator_memory_performance_python_yield.txt
Q: printing lines that contain 60 characters I'm having trouble printing a string in lines chat contains 60 characters. my code is below: s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz' for i in range(0, len(s), 60): for k in s[i:i+60]: print k A: s[i:i+60] will sli...
printing lines that contain 60 characters
I'm having trouble printing a string in lines chat contains 60 characters. my code is below: s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz' for i in range(0, len(s), 60): for k in s[i:i+60]: print k
[ "s[i:i+60] will slice the 60 characters you want into a string. By adding a second for loop, you're looping over each character in that string and outputting it separately. Just output s[i:i+60] instead\n", "Print the slice itself, not each character in the slice. \ns = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmno...
[ 4, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003145046_python.txt
Q: PyS60 vs Symbian C++ I'm planning some Symbian related development on S60 3.1 platform. It seems like generally available language options are Python and C++. However Nokia's official forum seems very much tilted towards C++. I want to know what are the advantages and disadvantages of using Python for S60 over Sym...
PyS60 vs Symbian C++
I'm planning some Symbian related development on S60 3.1 platform. It seems like generally available language options are Python and C++. However Nokia's official forum seems very much tilted towards C++. I want to know what are the advantages and disadvantages of using Python for S60 over Symbian C++? And is it even p...
[ "PyS60 is good when you need to prototype something simple fast. If you try to develop a full application with it though, you'll most likely find yourself sooner or later wanting to use features that are available in Symbian C++ but not in PyS60 without writing bindings (in C++) for it. Also you'll need to deal wit...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "c++", "pys60", "python", "symbian" ]
stackoverflow_0003123340_c++_pys60_python_symbian.txt