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: Reading from a file, storing values, and math operations I am trying to read in from a file that contains city names, an odometer reading, and how much fuel is left. The contents of the text file are: Kennewick 97840.4 40.0<br> Benton_City 97861.3 37.6<br> Prosser 97878.2 35.9<br> Grandview 97886.5 35.0<br> Sunnys...
Reading from a file, storing values, and math operations
I am trying to read in from a file that contains city names, an odometer reading, and how much fuel is left. The contents of the text file are: Kennewick 97840.4 40.0<br> Benton_City 97861.3 37.6<br> Prosser 97878.2 35.9<br> Grandview 97886.5 35.0<br> Sunnyside 97894.6 34.1<br> Granger 97904.6 33.1<br> Toppenish 97913....
[ "You have \nprevmiles = miles\n\nmilest = miles - prevmiles\n\nwhich guarantees that milest will be 0. Try just switching the order of those two lines.\n", "Two things going on here:\n\nyou need to initialize stopname, prevmiles, and fuel with the first line of the file, and\nyou need to swap the two lines where ...
[ 2, 1, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007797174_file_io_python.txt
Q: Sum elements in a list of lists and find maximum in Python I don't know how to do this: I have a list of lists defined like this: list=[[day,type,expense],[...]]; day and expense are int, type is string I need to find the max expense by day. An example: list=[[1,'food',15],[4,'rent', 50],[1,'other',60],[8,'bills...
Sum elements in a list of lists and find maximum in Python
I don't know how to do this: I have a list of lists defined like this: list=[[day,type,expense],[...]]; day and expense are int, type is string I need to find the max expense by day. An example: list=[[1,'food',15],[4,'rent', 50],[1,'other',60],[8,'bills',40]] I need to sum the elements that have the same day and fi...
[ "Isn't a defaultdict just as easy?\nimport pprint\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nl = [[1, 'food', 15], [4, 'rent', 50], [1, 'other', 60], [8, 'bills', 40]]\nd = defaultdict(int)\nfor item in l:\n d[item[0]] += item[2]\npprint.pprint(dict(d))\nprint max(d.iteritems(), key...
[ 5, 2, 0 ]
[]
[]
[ "list", "max", "python", "sum" ]
stackoverflow_0007797686_list_max_python_sum.txt
Q: wxPython: wx.SpinCtrl border management I'm trying to create a basic date-selector/calendar in wxPython. So far I've managed to add all the necessary widgets to my grid, but I'm struggling to get them positioned properly. Although there are numerous things I don't fully understand, I'm getting particularly frust...
wxPython: wx.SpinCtrl border management
I'm trying to create a basic date-selector/calendar in wxPython. So far I've managed to add all the necessary widgets to my grid, but I'm struggling to get them positioned properly. Although there are numerous things I don't fully understand, I'm getting particularly frustrated with the wx.SpinCtrl widget, which seem...
[ "It looks like you don't quite have the sizer's Add signature correct. It should be sizer.Add(widget, proportion, flags, border)\nYou keep skipping the proportion and are not specifying a border at all. If you did this instead:\nyearNavigationBox.Add(sc, 0, wx.EXPAND|wx.TOP, 5)\n\nIt will put the spinner 5 pixels b...
[ 1 ]
[]
[]
[ "layout", "python", "wxpython" ]
stackoverflow_0007797592_layout_python_wxpython.txt
Q: calling row data from successive months in successive yrs and writing it into columns? I have spread sheets of climate data for which, essentially, I need to transpose parts of rows into columns and vice versa. Unfortunately, the format is somewhat awkward. The data came to me with columns for year, month, number ...
calling row data from successive months in successive yrs and writing it into columns?
I have spread sheets of climate data for which, essentially, I need to transpose parts of rows into columns and vice versa. Unfortunately, the format is somewhat awkward. The data came to me with columns for year, month, number of days in the month, the type of climate data in the row, and then a successive 93 columns,...
[ "Each for makes a loop; your code has two loops for years inside each other – it processes all the years with the first line of the file, then all the years for the second, etc. This is the error you're running into, but if you just go and fix it somehow, another one will pop up soon enough.\n\nNow, please do borro...
[ 1 ]
[]
[]
[ "csv", "iterable_unpacking", "python", "row", "transpose" ]
stackoverflow_0007797268_csv_iterable_unpacking_python_row_transpose.txt
Q: jpype and java.util.Properties I'm attempting to instantiate a Properties object in JPype, and am encountering some difficulty. The commands below... props = JClass('java.util.Properties') props.setProperty('foo','bar') ...return the following: RuntimeError: No matching overloads found. at src/native/common/jp_me...
jpype and java.util.Properties
I'm attempting to instantiate a Properties object in JPype, and am encountering some difficulty. The commands below... props = JClass('java.util.Properties') props.setProperty('foo','bar') ...return the following: RuntimeError: No matching overloads found. at src/native/common/jp_method.cpp:121 I've attempted various...
[ "Try this:\nProperties = JClass('java.util.Properties')\nprops = Properties()\nprops.setProperty('foo','bar')\n\n" ]
[ 3 ]
[]
[]
[ "java", "properties", "python" ]
stackoverflow_0007797406_java_properties_python.txt
Q: How to raise custom dictionary KeyError message I'm writing some scripts that will be used by non-python users. I have a Config class that has dictionaries and I'd like to be able to raise a custom exception for KeyError. Is there an elegant way to do this other than writing a method that raises an exception whe...
How to raise custom dictionary KeyError message
I'm writing some scripts that will be used by non-python users. I have a Config class that has dictionaries and I'd like to be able to raise a custom exception for KeyError. Is there an elegant way to do this other than writing a method that raises an exception when checking for the value in the dictionary? Here's ...
[ "Consider doing this.\nclass MyConfigDict( dict ):\n def __getitem__( self, key ):\n try:\n return super( MyConfigDict, self ).__getitem__( key )\n except KeyError as e:\n raise MyConfigError( e.message )\n\nSomething like that may allow you to wrap every access in your own ex...
[ 5 ]
[]
[]
[ "dictionary", "exception_handling", "python", "python_2.4" ]
stackoverflow_0007797930_dictionary_exception_handling_python_python_2.4.txt
Q: Why does the pygtk callback on a clicked ToolButton executed twice when clicked once I've got a simple callback function which switches the label of a PyGTK button: def langSelectHandler(self, widget, callback_data=None): if self.lang == "fr": self.lang = "de" print "changed to de" widg...
Why does the pygtk callback on a clicked ToolButton executed twice when clicked once
I've got a simple callback function which switches the label of a PyGTK button: def langSelectHandler(self, widget, callback_data=None): if self.lang == "fr": self.lang = "de" print "changed to de" widget.set_label("Deutsch") else: self.lang = "fr" print "changed to fr" ...
[ "as pointed out in my comment (see the 2nd entry below the post), I made a connect via the code as well as via glade which lead to the 2 calls. If you ran into a similar or same problem just check that.\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0006644065_gtk_pygtk_python.txt
Q: How can I get the addition object for integers? Is there any way in Python to get the addition object (operator +) for integers in Python and store it somewhere? A: >>> int_add = int.__add__ >>> int_add(1, 2) 3 You can also use operator.add to obtain a generic function for adding in Python: >>> from operator i...
How can I get the addition object for integers?
Is there any way in Python to get the addition object (operator +) for integers in Python and store it somewhere?
[ ">>> int_add = int.__add__\n>>> int_add(1, 2)\n3\n\nYou can also use operator.add to obtain a generic function for adding in Python:\n>>> from operator import add\n>>> add(1, 2)\n3\n>>> add('a', 'b')\n'ab'\n\nIf you want to get the addition method of a specific integer, instead of the int type, see gnibbler's comme...
[ 7, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007798281_python.txt
Q: How do I ensure that a Python thread dies after its target function completes? I have a service that spawns threads. The threads are started by providing a target function. It would appear that the thread doesn't "die" when the function ends. I know this because the thread makes some SSH connections with Parami...
How do I ensure that a Python thread dies after its target function completes?
I have a service that spawns threads. The threads are started by providing a target function. It would appear that the thread doesn't "die" when the function ends. I know this because the thread makes some SSH connections with Paramiko (via Fabric), and if I do an lsof I see the SSH connections are still active afte...
[ "Are you sure your fabric module is doing the ssh only for the duration of the ls command. That is, it should be doing the equivalent of \nssh host ls -lht /tmp \nThis commandline will open a remote shell to run the ls -lht command and then shutdown.\nBut I suspect the Fabric library might be doing the equivalent o...
[ 2 ]
[]
[]
[ "fabric", "paramiko", "python", "python_multithreading" ]
stackoverflow_0007798330_fabric_paramiko_python_python_multithreading.txt
Q: How do you pass an argument variable while to an imported script? I have two scripts. Script A has a bunch of functions with variables in them, that need to be defined in Script B. For example, this is basically what I need to do in script A and B A.py: health = {p1:"100", p2:"100"} The rest of the script require...
How do you pass an argument variable while to an imported script?
I have two scripts. Script A has a bunch of functions with variables in them, that need to be defined in Script B. For example, this is basically what I need to do in script A and B A.py: health = {p1:"100", p2:"100"} The rest of the script requires that dictionary to be defined. B.py: p1 = raw_input() p2 = raw_input(...
[ "You could just make a function in A.py to pass the values into:\ndef DoStuff(p1, p2):\n #work with dict here\n\nSide note: Don't use strings for clearly numerical values like player health.\n" ]
[ 0 ]
[]
[]
[ "argv", "python", "variables" ]
stackoverflow_0007787298_argv_python_variables.txt
Q: python environment case senstivity - os.environ[...] I need to access the process' environment block in a platform-independent manner. The python os module docs don't specify anything about case-sensitivity of the os.environ / os.getenv. Experimenting on my ubuntu and win7 dev box's, I see that os.environ is case...
python environment case senstivity - os.environ[...]
I need to access the process' environment block in a platform-independent manner. The python os module docs don't specify anything about case-sensitivity of the os.environ / os.getenv. Experimenting on my ubuntu and win7 dev box's, I see that os.environ is case sensitive on linux but not on windows (This mirrors the b...
[ "When the documentation doesn't specify the behaviour and you want to discover the answer yourself, you can look in the source code. In this case you can get the source code for os.py online at http://svn.python.org/:\n\nos.py (Python trunk).\nos.py (Python 2.7).\n\nThe comments in the code say:\nelif name in ('os2...
[ 14, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007797269_python.txt
Q: Put a letter to the front of a string in python is there a quick way to place a string in the front of another string in python? if so how? as an example let's say that string = 'pple'. How would I put the string_2 = 'a' at the start of string? A: concatenate it: string=char+string A: >>> strg = 'pple' >>> cha...
Put a letter to the front of a string in python
is there a quick way to place a string in the front of another string in python? if so how? as an example let's say that string = 'pple'. How would I put the string_2 = 'a' at the start of string?
[ "concatenate it:\nstring=char+string\n", ">>> strg = 'pple'\n>>> char = 'a'\n>>> char + strg\n'apple'\n>>> strg = char + strg\n>>> strg\n'apple'\n>>>\n\n", "Here's a quick example:\n string='a'+string\n", "Lots of correct answers. You could also use \"string interpolation\" (or just \"string formatting\",...
[ 4, 4, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007798985_python_string.txt
Q: AppEngine mapper API import error EDIT: I just gave it a go on appengine itself and it seems like it actually works there, so the problem is just with the dev server. I would still be interested in understanding why this is happening... I am using the AppEngine mapper API (mapreduce) and am having a problem with i...
AppEngine mapper API import error
EDIT: I just gave it a go on appengine itself and it seems like it actually works there, so the problem is just with the dev server. I would still be interested in understanding why this is happening... I am using the AppEngine mapper API (mapreduce) and am having a problem with imports. Here is my file structure: ├── ...
[ "This may be the same problem I was having -- I was using the 2.7 version of the Python Interpreter in my local environment. When I switched to 2.5, it works fine.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "import", "importerror", "python" ]
stackoverflow_0007587675_google_app_engine_import_importerror_python.txt
Q: Twitter Oauth Callback Override Failing So I have setup a twitter application so that people can reply to tweets inside my own app. I have a callback URL and when I do not try and override it everything seems to go fine. However Now I am having a problem getting the override of the callback to work the app runs on...
Twitter Oauth Callback Override Failing
So I have setup a twitter application so that people can reply to tweets inside my own app. I have a callback URL and when I do not try and override it everything seems to go fine. However Now I am having a problem getting the override of the callback to work the app runs on multiple sub domains and servers based on wh...
[ "Few quick things...\nYour URLs are old and outdated and don't function as well as the proper URLs. Use SSL and the api subdomain:\n\nhttps://api.twitter.com/oauth/request_token\nhttps://api.twitter.com/oauth/authorize\nhttps://api.twitter.com/oauth/access_token\n\nIt's unclear to me looking at this code whether yo...
[ 4 ]
[]
[]
[ "oauth", "python", "twitter", "twitter_oauth" ]
stackoverflow_0007797765_oauth_python_twitter_twitter_oauth.txt
Q: Implementing restful servers with Django for Dojo's JsonRestStore - Which tools for the job? I'm writing some restful serverside resources which talk with dojo's JsonRestStore (JRS) on the client-side: http://dojotoolkit.org/reference-guide/dojox/data/JsonRestStore.html I notice that there are a couple of projec...
Implementing restful servers with Django for Dojo's JsonRestStore - Which tools for the job?
I'm writing some restful serverside resources which talk with dojo's JsonRestStore (JRS) on the client-side: http://dojotoolkit.org/reference-guide/dojox/data/JsonRestStore.html I notice that there are a couple of projects that I may be able to leverage to help create restful resources (i.e. to expose simple CRUD ope...
[ "I'd take a look at piston, tastypie and django-rest-framework, honestly they're mostly pretty similar, I'd just take a run through the docs and see which you think fits the bill.\nI don't think any of those will natively support the Range pagination you mention it's probably something you'd need to deal with yours...
[ 4, 3, 1 ]
[]
[]
[ "django", "dojo", "python", "rest" ]
stackoverflow_0005752748_django_dojo_python_rest.txt
Q: Why my error of blobstore_handlers.py, line 348, in get_uploads? I patched appengine_config to enable foreign characters with blobstoreuploadhandler: webapp_django_version = '1.2' import base64 import quopri from webob import multidict def from_fieldstorage(cls, fs): obj = cls() if fs.list: # fs...
Why my error of blobstore_handlers.py, line 348, in get_uploads?
I patched appengine_config to enable foreign characters with blobstoreuploadhandler: webapp_django_version = '1.2' import base64 import quopri from webob import multidict def from_fieldstorage(cls, fs): obj = cls() if fs.list: # fs.list can be None when there's nothing to parse for field in ...
[ "Indent \"obj.add(field.name, field_value)\" so that it is part of your else statement. \n" ]
[ 2 ]
[]
[]
[ "blobstore", "file", "google_app_engine", "python" ]
stackoverflow_0007797995_blobstore_file_google_app_engine_python.txt
Q: How to split a Python module into multiple files? I have a single Python module which contains 3 classes: A, A1 and A2. A1 and A2 derive from A. A contains functions which operate on A1 and A2. This all works fine when it's in one .py file. But that file has grown quite long and I would like to split A1 and A2 off...
How to split a Python module into multiple files?
I have a single Python module which contains 3 classes: A, A1 and A2. A1 and A2 derive from A. A contains functions which operate on A1 and A2. This all works fine when it's in one .py file. But that file has grown quite long and I would like to split A1 and A2 off into their own files. How can I split this file despit...
[ "modA.py:\nclass A(...):\n ...\n\nmodA1.py:\nimport modA\nclass A1(modA.A):\n ...\n\nmodA2.py:\nimport modA\nclass A2(modA.A):\n ...\n\nmodfull:\nfrom modA import A\nfrom modA1 import A1\nfrom modA2 import A2\n\nEven if A \"processes\" A1s and A2s you should be fine because thanks to duck typing you don't nee...
[ 12, 2, 0 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0007799286_python_python_module.txt
Q: Find a replace string in xml file with python I'm trying to replace a string in an xml file with python. For example: I want to change enabled to disbabled in: <s:global-method-security secured-annotations="enabled"/> Is it best to search and replace the whole line? Or is there a way to just replaced the enabled ...
Find a replace string in xml file with python
I'm trying to replace a string in an xml file with python. For example: I want to change enabled to disbabled in: <s:global-method-security secured-annotations="enabled"/> Is it best to search and replace the whole line? Or is there a way to just replaced the enabled on the line if I find a line that matches?
[ "A simple way could be:\nfor line in fileh:\n line = line.replace(\"enabled\", \"disabled\")\n ouf.write(line)\n\nYou do not need to explicitly find \"enabled\" in the string before replacing it.\nHowever, since its an xml file, I would suggest using the xml parser to modify it.\n", "Just use string.replace...
[ 3, 1 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0007799382_python_replace.txt
Q: PyQT vs PyObjc / Cocoa-Python I'm thinking about developing an app for OS X using Python. I don't know Objective C and don't want to learn it right now. I know and like Python. I'm trying to determine what GUI toolkit to use. I already have a bit of experience with PyQT, but not much. I've also seen that PyObjc or...
PyQT vs PyObjc / Cocoa-Python
I'm thinking about developing an app for OS X using Python. I don't know Objective C and don't want to learn it right now. I know and like Python. I'm trying to determine what GUI toolkit to use. I already have a bit of experience with PyQT, but not much. I've also seen that PyObjc or Cocoa-Python seem to allow use of ...
[ "If the only thing stopping you using PyQt is passing strings in signals, then the latest syntax should make your choice much easier. The old syntax (which can still be used) looks like this:\nself.connect(self.action, SIGNAL('triggered()'), self.handler)\n\nBut the new style signals are much more pythonic:\nself.a...
[ 4 ]
[]
[]
[ "pyobjc", "pyqt", "python", "signals_slots", "user_interface" ]
stackoverflow_0007799135_pyobjc_pyqt_python_signals_slots_user_interface.txt
Q: How to access Bluetooth low level functions in pybluez? Are there pybluez wrapper functions for lower level bt functionality? I couldn't find anything in the docs. What I need to use is equivalent functionality to: l2ping (single ping) hcitool cc hcitool rssi hcitool lq hcitool tpl hcitool dc Is there a way to ac...
How to access Bluetooth low level functions in pybluez?
Are there pybluez wrapper functions for lower level bt functionality? I couldn't find anything in the docs. What I need to use is equivalent functionality to: l2ping (single ping) hcitool cc hcitool rssi hcitool lq hcitool tpl hcitool dc Is there a way to access that from pybluez (or actually any other wrapper and/or ...
[ "The simple way to get the exact same functionality would be to just have python scripts invoke hcitool from the command line. \nBut for the custom solution, you can use pybluez to send the same HCI command packets that those other commands generate. For example, hcitool rssi just causes an HCI Read RSSI command t...
[ 2 ]
[]
[]
[ "bluetooth", "linux", "python" ]
stackoverflow_0007784854_bluetooth_linux_python.txt
Q: Why am I not getting the result of sorted function in expected order? print activities activities = sorted(activities,key = lambda item:item[1]) print activities Activities in this case is a list of tuples like (start_number,finish_number) the output of the above code according to me should be the list of values...
Why am I not getting the result of sorted function in expected order?
print activities activities = sorted(activities,key = lambda item:item[1]) print activities Activities in this case is a list of tuples like (start_number,finish_number) the output of the above code according to me should be the list of values sorted according the the increasing order of finish_number. When I tried t...
[ "You are sorting strings instead of integers: in that case, 10 is \"smaller\" than 4. To sort on integers, convert it to this:\nactivites = sorted(activities,key = lambda item:int(item[1]))\nprint activities\n\nResults in:\n[('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9'), ('6', '10'), ('8', ...
[ 6, 6, 2, 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0007798185_python_sorting.txt
Q: web2py Autofilling/autocomplete returns id i've a from and i want to fill it automatically based on information from a database and filled fields : in db_wizard.py db.define_table('receiver', Field('name'), # e.g. Daniel Field('email'),# e.g. daniel@daniel.com Field('opening'), # e.g. Dear Daniel ...) ...
web2py Autofilling/autocomplete returns id
i've a from and i want to fill it automatically based on information from a database and filled fields : in db_wizard.py db.define_table('receiver', Field('name'), # e.g. Daniel Field('email'),# e.g. daniel@daniel.com Field('opening'), # e.g. Dear Daniel ...) db.define_table('sender', Field('name...
[ "I don't think you want to use the suggest_widget (or the built-in autocomplete widget). Instead, you want the 'opening' field dynamically filled in as soon as the user selects a receiver. For that, you probably need a modified version of the lazy_options_widget (not used in conjunction with the suggest_widget).\nA...
[ 0, 0 ]
[]
[]
[ "ajax", "autocomplete", "autofill", "python", "web2py" ]
stackoverflow_0007703353_ajax_autocomplete_autofill_python_web2py.txt
Q: trying to automate translation on babelfish with python I have modified a python babelizer to help me to translate english to chinese. ## {{{ http://code.activestate.com/recipes/64937/ (r4) # babelizer.py - API for simple access to babelfish.altavista.com. # Requires python 2.0 or better. # # See it...
trying to automate translation on babelfish with python
I have modified a python babelizer to help me to translate english to chinese. ## {{{ http://code.activestate.com/recipes/64937/ (r4) # babelizer.py - API for simple access to babelfish.altavista.com. # Requires python 2.0 or better. # # See it in use at http://babel.MrFeinberg.com/ """API for simple ac...
[ "I think you need to use:\nimport codecs\ncodecs.open\n\ninstead of plain open, in your:\nsaveHTML\n\nmethod, to handle utf-8 docs. See the Python Unicode Howto for a complete explanation.\n" ]
[ 1 ]
[]
[]
[ "http", "python", "utf_8" ]
stackoverflow_0007799366_http_python_utf_8.txt
Q: Django: speech to text application first do you know what language google used to create the speech to text search? then can you create a speech to text django or google apps engine using python? i'm not a vb.net programmer and yes i know that such applications are usually created in java, couldn't they be created...
Django: speech to text application
first do you know what language google used to create the speech to text search? then can you create a speech to text django or google apps engine using python? i'm not a vb.net programmer and yes i know that such applications are usually created in java, couldn't they be created in jython? i have a django app i would ...
[ "Unlikely. \nAs you cannot install binaries in the Google App Engine environment, you would need build an entire speech recognition engine from scratch. This would be ..non-trival.\nIf you are not limited to Google App Engine however, there are Python bindings to existing packages, such as Sphinx\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "jython", "python" ]
stackoverflow_0007800094_django_google_app_engine_jython_python.txt
Q: How do you delete a node in networkx? I have a dataset that I'm uploading as a graph for various timeframes and trying to figure relationships between them. I want to delete all the nodes that do not have edges but I'm not sure the command to remove or delete nodes. Any idea how to do this? A: import networkx as...
How do you delete a node in networkx?
I have a dataset that I'm uploading as a graph for various timeframes and trying to figure relationships between them. I want to delete all the nodes that do not have edges but I'm not sure the command to remove or delete nodes. Any idea how to do this?
[ "import networkx as nx\nimport matplotlib.pyplot as plt\n\nG=nx.Graph()\nG.add_edges_from([('A','B'),('A','C'),('B','D'),('C','D')])\nnx.draw(G)\nplt.show()\n\n\nG.remove_node('B')\nnx.draw(G)\nplt.show()\n\n\nTo remove multiple nodes, there is also the Graph.remove_nodes_from() method.\n", "Documentation covers ...
[ 14, 4 ]
[]
[]
[ "graph_theory", "networkx", "python" ]
stackoverflow_0007800133_graph_theory_networkx_python.txt
Q: Can I use Python's CSV reader with Google Fusion Tables? I'm trying to read data from Google Fusion Tables API into Python using the csv library. It seems like querying the API returns CSV data, but when I try and use it with csv.reader, it seems to mangle the data and split it up on every character rather than ju...
Can I use Python's CSV reader with Google Fusion Tables?
I'm trying to read data from Google Fusion Tables API into Python using the csv library. It seems like querying the API returns CSV data, but when I try and use it with csv.reader, it seems to mangle the data and split it up on every character rather than just on the commas and newlines. Am I missing a step? Here's a s...
[ "csv.reader() takes in a file-like object.\nChange \nreader = csv.reader(serv_resp.read()) \n\nto\nreader = csv.reader(serv_resp)\n\nAlternatively, you could do:\nreader = csv.DictReader(serv_resp)\n\n", "It's not the CSV module that's causing the problem. Take a look at the output from serv_resp.read(). Try usin...
[ 2, 1 ]
[]
[]
[ "csv", "google_fusion_tables", "python" ]
stackoverflow_0007800213_csv_google_fusion_tables_python.txt
Q: python receive file from html form I have a form with an input tag and a submit button: <input type="file" name="filename" size="25"> I have a python file that handles the post: def post(self): The file that I'm receiving in the form is an .xml file, in the python post function I want to send that 'foo.xml' to a...
python receive file from html form
I have a form with an input tag and a submit button: <input type="file" name="filename" size="25"> I have a python file that handles the post: def post(self): The file that I'm receiving in the form is an .xml file, in the python post function I want to send that 'foo.xml' to another function that is going to validat...
[ "Oftentimes, there's also a function to extract XML from a string. For example, minidom has parseString, and lxml etree.XML.\nIf you have the content, you can make a file-like object with StringIO:\nfrom StringIO import StringIO\ncontent = form.getvalue('filename')\nfileh = StringIO(content)\n# You can now call fil...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007800283_python_python_3.x.txt
Q: Dropping a letter if it repeats Is there a way to drop a letter in a string if it repeats? For example lets say that I have the string aaardvark and I wanted to drop one of the beginning a, how would I do this? A: If I understood your question correctly, you can do this using regular expressions: import re re.s...
Dropping a letter if it repeats
Is there a way to drop a letter in a string if it repeats? For example lets say that I have the string aaardvark and I wanted to drop one of the beginning a, how would I do this?
[ "If I understood your question correctly, you can do this using regular expressions:\nimport re\nre.sub(r'(.)\\1+', r'\\1', 'aardvarrk')\n\nThis collapses all sequences of identical characters into one, giving you 'ardvark'.\nAs for the implementation of your spell checker, I suggest \"collapsing\" all words that h...
[ 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007800053_python_string.txt
Q: Table using nested loop, calculations not coming out correctly / completely This has stumped me for several hours, and I am so close to the end, and I've tried several different variations, and it comes out in weird ways. I have also found different times this problem has been asked, but none of them seem to be ha...
Table using nested loop, calculations not coming out correctly / completely
This has stumped me for several hours, and I am so close to the end, and I've tried several different variations, and it comes out in weird ways. I have also found different times this problem has been asked, but none of them seem to be having the problem I seem to be having. The question / problem: I am having can be ...
[ "You have calculated wchill at the very beginning of your program, when row = 0 and col = 0. That number is evaluated to 35.7 at the beginning, and will not change.\nIf you want wchill to change based on what row/column you are printing on currently, then you need to call the line \nwchill = round((35.74 + 0.6215*(...
[ 2, 0 ]
[]
[]
[ "loops", "python", "tabular" ]
stackoverflow_0007800198_loops_python_tabular.txt
Q: python library for file upload and persistent connections? I tried urllib{2}, pycurl and I'm looking at twisted's new http client. But: I found urllib2 difficult to perform a file upload pycurl multi looks right but unpythonic twisted's http client does not support persistent connection (didn't check the file upl...
python library for file upload and persistent connections?
I tried urllib{2}, pycurl and I'm looking at twisted's new http client. But: I found urllib2 difficult to perform a file upload pycurl multi looks right but unpythonic twisted's http client does not support persistent connection (didn't check the file upload capability) Is there any other alternative?
[ "PiCloud's library uses urllib2_file which easily does upload via multipart data. I forget where we got the module (we later modified it). the urllib2_file is covered under a BSD license.\n", "I rolled my own on top of httplib before discovering urllib3, which does both of these things. \n" ]
[ 2, 1 ]
[]
[]
[ "httpwebrequest", "pycurl", "python", "twisted" ]
stackoverflow_0002384496_httpwebrequest_pycurl_python_twisted.txt
Q: gcc error from easy_install of setproctitle I'm trying to install setproctitle. I've tried just downloading the package and using setup.py to install and I've tried easy_install. Neither method works, both come up with something that looks like: :~$ sudo easy_install setproctitle Searching for setproctitle Reading...
gcc error from easy_install of setproctitle
I'm trying to install setproctitle. I've tried just downloading the package and using setup.py to install and I've tried easy_install. Neither method works, both come up with something that looks like: :~$ sudo easy_install setproctitle Searching for setproctitle Reading http://pypi.python.org/simple/setproctitle/ Read...
[ "Install the python-dev package.\n" ]
[ 9 ]
[]
[]
[ "easy_install", "python", "setup.py" ]
stackoverflow_0007800574_easy_install_python_setup.py.txt
Q: Arbitrary number of positional arguments in django inclusion tag? I'm trying to write a django inclusion tag that takes an arbitrary number of arguments: @register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } However, when I call...
Arbitrary number of positional arguments in django inclusion tag?
I'm trying to write a django inclusion tag that takes an arbitrary number of arguments: @register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } However, when I call this from django's template engine: {% table_field form.hr form.bp for...
[ "As of 1.2.1 you can pass arguments to inclusion tags.\nHere is an example from my mods to django voting templatetags\n@register.inclusion_tag(\"voting/vote_form.html\", takes_context=True)\ndef vote_form(context, vote_object, vote_dict, score_dict):\n if isinstance(vote_dict, dict):\n\nand the template looks li...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001316968_django_python.txt
Q: Shell scripting in Python: calling programs that use curses, etc Here's a very specific question, but I'm looking for a slightly more general solution: I'm writing a shell script in Python to assist in various config tasks, including performing a git clone of various repositories. When I call git clone, is there ...
Shell scripting in Python: calling programs that use curses, etc
Here's a very specific question, but I'm looking for a slightly more general solution: I'm writing a shell script in Python to assist in various config tasks, including performing a git clone of various repositories. When I call git clone, is there a good way for me to supply git display output directly to the termina...
[ "Try:\nimport os\nos.system(mycommand)\n\nThis works for wget, the progress-bar that rewrites itself on one line on the screen works correctly this way. I suppose it would work for git and others as well.\n" ]
[ 2 ]
[]
[]
[ "python", "scripting", "shell", "stdout", "subprocess" ]
stackoverflow_0007800864_python_scripting_shell_stdout_subprocess.txt
Q: Get django-registration and django-profile working together I am in process to setting up a new django project and I want to use the provided apps django-registration and django-profile. I installed both of them with easy-install and managed to get the django-registration working fine. My next step would be to con...
Get django-registration and django-profile working together
I am in process to setting up a new django project and I want to use the provided apps django-registration and django-profile. I installed both of them with easy-install and managed to get the django-registration working fine. My next step would be to connect the django-profile app to the working branch. The django-reg...
[ "django-registration is hard to use thanks to the type of documentation and lack of templates. Many Django developers now use django-social-auth instead: \nhttps://github.com/omab/django-social-auth\nhttp://django-social-auth.readthedocs.org/en/latest/index.html\nYou can see how Kenneth Love integrated it into the ...
[ 3 ]
[]
[]
[ "authentication", "django", "django_registration", "python" ]
stackoverflow_0007800616_authentication_django_django_registration_python.txt
Q: phone number lookup program I am having a problem with my array homework, I need to enter a name then the program has to return the number, but all I can get it to do is return all of them def main(): people = ['todd','david','angela','steve','bob','josh','ben'] phoneNumbers = ['234-7654','567-1234','888-8...
phone number lookup program
I am having a problem with my array homework, I need to enter a name then the program has to return the number, but all I can get it to do is return all of them def main(): people = ['todd','david','angela','steve','bob','josh','ben'] phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6...
[ "Use index to print the phone number you want, rather than all of them:\nif found:\n print 'the phone number is: ', phoneNumbers[index]\n\n", "Others have explicitly given you the answer, but based on the way the question has been written, I'm concerned about comprehension. So I'll go into a little more detail...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007800944_python.txt
Q: Set http response Content-Type to "xml" in python How do I display on an html page an xml? how can I set in python text/html? I'm writing in the html as: response.out.write A: Assuming your using mod_python: response.content_type = "text/xml" Or: response.content_type = "text/html" http://www.modpython.org/liv...
Set http response Content-Type to "xml" in python
How do I display on an html page an xml? how can I set in python text/html? I'm writing in the html as: response.out.write
[ "Assuming your using mod_python:\nresponse.content_type = \"text/xml\"\n\nOr:\nresponse.content_type = \"text/html\"\n\nhttp://www.modpython.org/live/current/doc-html/pyapi-mprequest-mem.html\n\ncontent_type\nString. The content type. Mod_python maintains an\n internal flag (req._content_type_set) to keep track of...
[ 2 ]
[]
[]
[ "mod_python", "python", "xml" ]
stackoverflow_0007801280_mod_python_python_xml.txt
Q: Print a float number in normal form, not exponential form / scientific notation I have a number that prints out in exponential form: >>> >>> a = 1/1221759 >>> print(a) 8.184920266599223e-07 >>> How can i make it print in normal form? A: You can format it as a fixed-point number. >>> a = 1/1221759 >>> '{0:.10f}'...
Print a float number in normal form, not exponential form / scientific notation
I have a number that prints out in exponential form: >>> >>> a = 1/1221759 >>> print(a) 8.184920266599223e-07 >>> How can i make it print in normal form?
[ "You can format it as a fixed-point number.\n>>> a = 1/1221759\n>>> '{0:.10f}'.format(a)\n'0.0000008185'\n\n", "You can use print formatting:\nprint \"%.16f\" % a\n\nwhere 16 is the number of digits you want after the decimal point.\n" ]
[ 62, 9 ]
[]
[]
[ "floating_point", "python", "python_3.x" ]
stackoverflow_0007801586_floating_point_python_python_3.x.txt
Q: Django Model with dynamic attributes I'm totally, completely new to programming, so please forgive what is probably a stupid question, but I've been beating my head on this for the past couple of days. I have two models, Photos and Thumbnails. I'm trying to come up with an easy, dynamic way to get the thumbnail l...
Django Model with dynamic attributes
I'm totally, completely new to programming, so please forgive what is probably a stupid question, but I've been beating my head on this for the past couple of days. I have two models, Photos and Thumbnails. I'm trying to come up with an easy, dynamic way to get the thumbnail links for each Photo. I've come up a functi...
[ "You want to override the __init__ method like you did with the save method, and call self.get_thumbs() before you call super(Photo, self).init(*args, **kwargs)\nAlternately, you could look at other peoples solution to this problem sorl.thumbnail, django-imagekit, or easy-thumbnails (which is sort of like a combina...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007801729_django_django_models_python.txt
Q: Python: how can I catch a exception and continue? Why do you have a list of both numbers and some other kind of object? It seems like you're trying to compensate for a design flaw. As a matter of fact, I want it work this way because I want to keep data that is already encoded in JsonedData(), then I want json mo...
Python: how can I catch a exception and continue?
Why do you have a list of both numbers and some other kind of object? It seems like you're trying to compensate for a design flaw. As a matter of fact, I want it work this way because I want to keep data that is already encoded in JsonedData(), then I want json module to give me some way to insert a 'raw' item data r...
[ "put the try/except inside the loop around the json.JSONEncoder().encode(item):\nprint \"[\",\nlst = [1, 2, 3, JsonedData(u'4'), 5]\nfor i, item in enumerate(lst):\n    try:\n        chunk = json.JSONEncoder().encode(item)\n    except TypeError: \n pass\n else:\n print chunk\n finally:\n ...
[ 4, 3 ]
[]
[]
[ "exception", "json", "python" ]
stackoverflow_0007801903_exception_json_python.txt
Q: python can read image file to binary i need to upload a image file, and i use MultipartPostHandler.py as people suggest. but still doesn't work. here is my code: params = {"upload", open("12345.jpg", "rb")} // in 'rb' opener = urllib2.build_opener(MultipartPostHandler) res = opener.open(url, params) and here is t...
python can read image file to binary
i need to upload a image file, and i use MultipartPostHandler.py as people suggest. but still doesn't work. here is my code: params = {"upload", open("12345.jpg", "rb")} // in 'rb' opener = urllib2.build_opener(MultipartPostHandler) res = opener.open(url, params) and here is the code in MultipartPostHander: def multip...
[ "I have used Doug Hellman's MultiPartForm class from his blog to upload files to our mail server sucessfully: http://pymotw.com/2/urllib2/index.html#module-urllib2\nHopefully you can use that as well.\n", "i think this can save me. aha.\n# convert every byte of data to the corresponding 2-digit hexadecimal\nenter...
[ 1, 0 ]
[]
[]
[ "binary", "image", "python" ]
stackoverflow_0007794985_binary_image_python.txt
Q: Issues using python's string formatting libraries cur.execute('INSERT INTO company VALUES (%(cname), %(symbol), %(start_date), %(end_date))' %{'cname' : company, 'symbol' : company, 'start_date' : startdate, 'end_date' : enddate}) Trying to run this line on my computer results in a string formatting error: Va...
Issues using python's string formatting libraries
cur.execute('INSERT INTO company VALUES (%(cname), %(symbol), %(start_date), %(end_date))' %{'cname' : company, 'symbol' : company, 'start_date' : startdate, 'end_date' : enddate}) Trying to run this line on my computer results in a string formatting error: ValueError: unsupported format character ',' (0x2c) at in...
[ "You need an \"s\" after each of those positional arguments.\n(%(cname)s, %(symbol)s, ....\n\n", "What @imm said. Also, you may want to use the built in query formatting that is part of MySQLdb.\ncur.execute(\"INSERT INTO company VALUES (%s, %s, %s, %s)\", (company, company, startdate, enddate))\n\n" ]
[ 17, 3 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0007802265_formatting_python_string.txt
Q: Best practice for decoupling a database from a message queue I am building a web application that allows a user to upload an image. When the image is uploaded, it needs to be resized to one or more sizes, each of which needs to be sent to Amazon s3 for storage. Metadata and urls for each size of the image are stor...
Best practice for decoupling a database from a message queue
I am building a web application that allows a user to upload an image. When the image is uploaded, it needs to be resized to one or more sizes, each of which needs to be sent to Amazon s3 for storage. Metadata and urls for each size of the image are stored in a single database record on the web server. I'm using a mess...
[ "It seems that your goal is not to decouple the database from the MQ, but rather from the workers. As such, you can create another queue that receives completion notifications, and have another single worker that picks up the notifications and updates the database appropriately.\n" ]
[ 2 ]
[]
[]
[ "celery", "database", "message_queue", "pylons", "python" ]
stackoverflow_0007802504_celery_database_message_queue_pylons_python.txt
Q: In Python how to construct a str for help(object) I need a str object created out of the text displayed in help(some_object). simply typecasting to str doesn't work. >>> s = str(help(object)) >>> print s None Whats the correct way to do this ? A: >>> print pydoc.text.document(object) class object | The most b...
In Python how to construct a str for help(object)
I need a str object created out of the text displayed in help(some_object). simply typecasting to str doesn't work. >>> s = str(help(object)) >>> print s None Whats the correct way to do this ?
[ ">>> print pydoc.text.document(object)\nclass object\n | The most base type\n\n", "You actually want:\nimport pydoc\nstrhelp = pydoc.render_doc(str, \"Help on %s\")\n\nThat'll get you the exact text produced by help(str).\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007802789_python.txt
Q: Python: SpatiaLite table to numpy recarray with datetime format? I posted this question at the QGIS-user forum but it might be too technical, thus I take a chance and try here as well. My plan is to have a QGIS plugin that reads and plots time series data corresponding to selected points in a vector layer(the poi...
Python: SpatiaLite table to numpy recarray with datetime format?
I posted this question at the QGIS-user forum but it might be too technical, thus I take a chance and try here as well. My plan is to have a QGIS plugin that reads and plots time series data corresponding to selected points in a vector layer(the points represents different measuring stations and I need to quickly view...
[ "Basically, you're trying to pass in a string.\nMatplotlib has several convenience functions for converting date strings to it's (internal) datetime representation.\nTry something more like:\n...\nfrom matplotlib.dates import datestr2num\n...\n\n...\ntime = datestr2num(table2.date_time)\nax.plot_date(time, table2.v...
[ 2, 1 ]
[]
[]
[ "numpy", "python", "qgis", "spatialite" ]
stackoverflow_0007757461_numpy_python_qgis_spatialite.txt
Q: Python module location I have been trying to find the location of a module but can't I have searched the python folder but still can't find it but I know it's there >>> import math >>> math.__path__ Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> math.__path__ AttributeError: 'mod...
Python module location
I have been trying to find the location of a module but can't I have searched the python folder but still can't find it but I know it's there >>> import math >>> math.__path__ Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> math.__path__ AttributeError: 'module' object has no attribute...
[ "If it has no __file__ attribute then that means that it's probably built into the Python library itself (or some other executable), and does not exist independently on disk.\n" ]
[ 5 ]
[]
[]
[ "location", "math", "module", "python" ]
stackoverflow_0007803235_location_math_module_python.txt
Q: How do Python modules work I was wondering how do Python modules work? Say I want to make my Python program some custom modules to package with it, where would I put them in relation to the main .py file?(and how would I load them if not using the usual way) A: If the module is specific to your program, you can ...
How do Python modules work
I was wondering how do Python modules work? Say I want to make my Python program some custom modules to package with it, where would I put them in relation to the main .py file?(and how would I load them if not using the usual way)
[ "If the module is specific to your program, you can put into the same directory as the main script. From the documentation:\n\nWhen a module named spam is imported, the interpreter searches for a file named spam.py in the directory containing the input script and then in the list of directories specified by the env...
[ 8 ]
[]
[]
[ "customization", "load", "location", "module", "python" ]
stackoverflow_0007803493_customization_load_location_module_python.txt
Q: What differences does `__init__` make to a directory? In python, a directory containing one or more modules sometimes has __init__.py, so that the directory can be treated as a python package, is this correct? What differences the __init__ makes? (also another Q, is a python module just a python code-file with rel...
What differences does `__init__` make to a directory?
In python, a directory containing one or more modules sometimes has __init__.py, so that the directory can be treated as a python package, is this correct? What differences the __init__ makes? (also another Q, is a python module just a python code-file with related and possibly independent (to other files) set of class...
[ "Here's an explanation for why __init__.py is needed:\n\nThe __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In th...
[ 4, 2 ]
[]
[]
[ "init", "package", "python" ]
stackoverflow_0007803523_init_package_python.txt
Q: PIL image conversion not using file system I would like to do image conversion/rewriting with PIL just using RAM memory. I have the image in bytes in RAM and I would like to convert it to some other format or possibly the same. I know I can do it like saving it in on the file system with some name, but I would lik...
PIL image conversion not using file system
I would like to do image conversion/rewriting with PIL just using RAM memory. I have the image in bytes in RAM and I would like to convert it to some other format or possibly the same. I know I can do it like saving it in on the file system with some name, but I would like to do it just using RAM without touching the f...
[ "You can use a StringIO file object instead of a regular file as well with both PIL Image.open and Image.save\n# somewhere earlier in the code:\n# data = ...\n\nfrom StringIO import StringIO\nfd = StringIO(data)\nimage = Image.open(fd)\nimage.show()\n\nThere's also a frombuffer function \n" ]
[ 5 ]
[]
[]
[ "python", "python_imaging_library", "rewriting" ]
stackoverflow_0007803539_python_python_imaging_library_rewriting.txt
Q: How to filter by joinloaded table in SqlAlchemy? Lets say I got 2 models, Document and Person. Document got relationship to Person via "owner" property. Now: session.query(Document)\ .options(joinedload('owner'))\ .filter(Person.is_deleted!=True) Will double join table Person. One person table will be sel...
How to filter by joinloaded table in SqlAlchemy?
Lets say I got 2 models, Document and Person. Document got relationship to Person via "owner" property. Now: session.query(Document)\ .options(joinedload('owner'))\ .filter(Person.is_deleted!=True) Will double join table Person. One person table will be selected, and the doubled one will be filtered which is n...
[ "You are right, table Person will be used twice in the resulting SQL, but each of them serves different purpose:\n\none is to filter the the condition: filter(Person.is_deleted != True)\nthe other is to eager load the relationship: options(joinedload('owner'))\n\nBut the reason your query returns wrong results is b...
[ 22 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007793842_python_sqlalchemy.txt
Q: Set / get objects with memcached In a Django Python app, I launch jobs with Celery (a task manager). When each job is launched, they return an object (lets call it an instance of class X) that lets you check on the job and retrieve the return value or errors thrown. Several people (someday, I hope) will be able t...
Set / get objects with memcached
In a Django Python app, I launch jobs with Celery (a task manager). When each job is launched, they return an object (lets call it an instance of class X) that lets you check on the job and retrieve the return value or errors thrown. Several people (someday, I hope) will be able to use this web interface at the same t...
[ "I think django-celery does this work for you. Did you had a look at the tables made by django-celery? I.e. djcelery_taskstate holds all data for a given task like state, worker_id and so on. For periodic tasks there is a table called djcelery_periodictask.\nIn a Django view you can access the TaskMeta object:\nfro...
[ 1 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0007799816_celery_django_python.txt
Q: python, plotting and c api I have a little C program that's continuously acquiring a stream of data and sending it via UDP, and in real time, to a different computer. The basic framework for what I originally set out to do has been laid. In addition, however, I'd like to visualize in real time the data that's bei...
python, plotting and c api
I have a little C program that's continuously acquiring a stream of data and sending it via UDP, and in real time, to a different computer. The basic framework for what I originally set out to do has been laid. In addition, however, I'd like to visualize in real time the data that's being acquired. To that end, I was ...
[ "You can quite easily listen to your UDP port with the standard socket module. Examples are available.\nAs a first step, your data could go in a simple Python list, as lists are optimized for appending data. Removing the first elements takes much more time, so you might want to only do this from time to time, an...
[ 1, 0 ]
[]
[]
[ "c", "plot", "python", "real_time" ]
stackoverflow_0007803425_c_plot_python_real_time.txt
Q: Bespoke CMS or 3rd Party? I am planning a side project and I want to know your experiences with CMS builds. The project is a fairly straightforward CMS with no e-commerce functionality needed. I know I can build something like this using Zend Framework quite simply. As it is a side project I don't want to spending...
Bespoke CMS or 3rd Party?
I am planning a side project and I want to know your experiences with CMS builds. The project is a fairly straightforward CMS with no e-commerce functionality needed. I know I can build something like this using Zend Framework quite simply. As it is a side project I don't want to spending time doing the tedious stuff l...
[ "In my experience you always need to keep your options open. People always decide they want new features down the line, and if those people are not coders they will not be able to appreciate that their requirements in the beginning have now made it very difficult for you to implement their new ideas.\nZend Framewor...
[ 5, 0 ]
[]
[]
[ "content_management_system", "php", "python", "zend_framework" ]
stackoverflow_0007804468_content_management_system_php_python_zend_framework.txt
Q: run for loop limited iterations in python I have an extremely large list of objects and I need to find all that have the identical attribute (any_object.any_attribute) and then append them to a new list. So I have pre-sorted them and run a binary search algo. I have found the object with the matching attribute but...
run for loop limited iterations in python
I have an extremely large list of objects and I need to find all that have the identical attribute (any_object.any_attribute) and then append them to a new list. So I have pre-sorted them and run a binary search algo. I have found the object with the matching attribute but the problem is that there are more than one su...
[ "Try this:\nelse:\n # Find the first element that matches\n while mid > 0 and sortedSamples[mid - 1].attr == desired_attr:\n mid -= 1\n\n # Iterate until an element that doesn't match is found.\n while mid < len(sortedSamples) and sortedSamples[mid].attr == desired_attr:\n newList.append(s...
[ 4, 2, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0007804497_for_loop_python.txt
Q: f2py error: undefined symbol I need to wrap a simply fortran90 code with f2py. The fortran module "test.f90" is module util contains FUNCTION gasdev(idum) implicit none INTEGER(kind=4), intent(inout) :: idum REAL(kind=8) :: gasdev, ran2 print*,idum gasdev = ran2(idum) return END FUNCTION FUNCTION ran2(idum) imp...
f2py error: undefined symbol
I need to wrap a simply fortran90 code with f2py. The fortran module "test.f90" is module util contains FUNCTION gasdev(idum) implicit none INTEGER(kind=4), intent(inout) :: idum REAL(kind=8) :: gasdev, ran2 print*,idum gasdev = ran2(idum) return END FUNCTION FUNCTION ran2(idum) implicit none INTEGER(kind=4), intent...
[ "In function gasdev you declare ran2 as an external function. As you then don't link in any such function importing the module will fail. \nInstead, remove the declaration of ran2 in gasdev, in which case the ran2 call uses the explicit interface to the ran2 function in the module, and everything works.\n" ]
[ 6 ]
[]
[]
[ "f2py", "fortran", "python" ]
stackoverflow_0007803799_f2py_fortran_python.txt
Q: dateutil.parser.parse() gives error "initial_value must be unicode or None, not str" on Windows platform I'm sure there's a really simple solution to this, but I'm still fairly new to Python. I'm trying to use dateutil.parser.parse() to parse a string with a timestamp in it: >>> import dateutil.parser >>> a = date...
dateutil.parser.parse() gives error "initial_value must be unicode or None, not str" on Windows platform
I'm sure there's a really simple solution to this, but I'm still fairly new to Python. I'm trying to use dateutil.parser.parse() to parse a string with a timestamp in it: >>> import dateutil.parser >>> a = dateutil.parser.parse("2011-10-01 12:00:00+01:00") >>> print a 2011-10-01 12:00:00+01:00 This works fine on my Li...
[ "It's not a Windows issue, it's Python version / library version issue.\ndateutil 2.0 is written to support only Python 3, not Python 2.X. Both cases here contain bugs when used with Python 2.X.\nIn the first case:\ndateutil.parser.parse(\"2011-10-01 12:00:00+01:00\")\n\nthe io.StringIO class allows only unicode ar...
[ 17 ]
[]
[]
[ "python", "python_dateutil" ]
stackoverflow_0007804505_python_python_dateutil.txt
Q: Python unicode list join I want to join a unicode python list, for example: a = [u'00', u'0c', u'29', u'58', u'86', u'16'] I want a string that looks like this: '00:0c:29:58:86:16' How would I join this? A: >>> a = [u'00', u'0c', u'29', u'58', u'86', u'16'] >>> u":".join(a) u'00:0c:29:58:86:16' >>> str(u":".jo...
Python unicode list join
I want to join a unicode python list, for example: a = [u'00', u'0c', u'29', u'58', u'86', u'16'] I want a string that looks like this: '00:0c:29:58:86:16' How would I join this?
[ ">>> a = [u'00', u'0c', u'29', u'58', u'86', u'16']\n>>> u\":\".join(a)\nu'00:0c:29:58:86:16'\n>>> str(u\":\".join(a))\n'00:0c:29:58:86:16'\n\n" ]
[ 18 ]
[ "How about this:\nif __name__ == \"__main__\":\n a = [u'00', u'0c', u'29', u'58', u'86', u'16']\n\n s = u''\n j = True\n\n for i in a:\n if j == True:\n s += i\n j = False\n else:\n s += u'...
[ -2 ]
[ "list", "python", "string", "unicode" ]
stackoverflow_0007804743_list_python_string_unicode.txt
Q: How to save panels position in wx.aui How can i save the position of my wx.aui panels in *.ini file (for examples)? Methods GetPosition() and GetSize() give me only the defaultsizes and positions. A: Use wx.aui.AuiManager.SavePerspective and wx.aui.AuiManager.LoadPerspective to load and save layout data (assumin...
How to save panels position in wx.aui
How can i save the position of my wx.aui panels in *.ini file (for examples)? Methods GetPosition() and GetSize() give me only the defaultsizes and positions.
[ "Use wx.aui.AuiManager.SavePerspective and wx.aui.AuiManager.LoadPerspective to load and save layout data (assuming you have a consistent set of panes when you load as you had when you saved)\nFor wxPython SavePerspective will just return a string which you can store somewhere and then pass into LoadPerspective. Th...
[ 3 ]
[]
[]
[ "python", "wxwidgets" ]
stackoverflow_0007803776_python_wxwidgets.txt
Q: combine query from multiple tables in django I get two tables, data_table and old_data_table for example, they contains exactly the same structure. data_table contains only 1 month data. say from '2011-10-01' to now. old_data_table contains the rest data. Now if I have to query data between day '2011-09-01' to da...
combine query from multiple tables in django
I get two tables, data_table and old_data_table for example, they contains exactly the same structure. data_table contains only 1 month data. say from '2011-10-01' to now. old_data_table contains the rest data. Now if I have to query data between day '2011-09-01' to day '2011-10-07', is there a way to query it from bo...
[ "I haven't checked this code, but you'll want something like this...\nfrom datetime import datetime\nfrom itertools import chain\n\nmy_date = datetime.date(2011, 10, 1)\nold_data = OldData.objects.filter(date_gte=my_date)\ncurrent_data = CurrentData.objects.filter(date_gte=my_date)\nall_data = sorted(chain(old_data...
[ 0 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0007804096_django_orm_python.txt
Q: How to remove item from the following data type in Python? If I have the following data type: [('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')] How to I remove item b so the output will look like: [('a', 'digital-text'), ('c', '1318913293'), ('d', '1-3')] How do I also check if b exist...
How to remove item from the following data type in Python?
If I have the following data type: [('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')] How to I remove item b so the output will look like: [('a', 'digital-text'), ('c', '1318913293'), ('d', '1-3')] How do I also check if b exists before deleting it? I tried if 'b' in xxxx but this can't find...
[ "\nYou could use a list comprehension like this:\nsomething = [(key, value) for key, value in something if key != 'b']\n\nHowever, it looks like you're trying to reinvent a dictionary for some reason. If it doesn't have to be ordered, just use a dictionary:\nsomething = {\n 'a': 'digital-text',\n 'b': 'bbbbbb...
[ 7, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007802893_python.txt
Q: Create a python dictionary of lists I am new to python and django and was wondering how I would go about making a dict of lists. My 4 lists are; ap = request.POST.getlist('amount_paid[]') pd = request.POST.getlist('paid_date[]') method = request.POST.getlist('method[]') comments = request.POST.getlist('comments[]'...
Create a python dictionary of lists
I am new to python and django and was wondering how I would go about making a dict of lists. My 4 lists are; ap = request.POST.getlist('amount_paid[]') pd = request.POST.getlist('paid_date[]') method = request.POST.getlist('method[]') comments = request.POST.getlist('comments[]') How would I make that into a dictionar...
[ "You could create:\nthe_dict = dict(amount_paid=ap, paid_date=pd, method=method, comments=comments)\n\nAlso your template code does not make sense. You are iterating over the keys of the dict and not using them in the body.\nEDIT\n{% for key in the_dict %}\n {% for val in the_dict[key] %}\n <input name=\"...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007804186_django_python.txt
Q: Is there a way to set a breakpoint on variable access in Python with PyDev? I have a global variable (I know) that is being changed from a good value to a bad value somewhere. I don't know where, and I'd like to find out where. I would like my debugger (Eclipse/PyDev) to break any time any code writes to this glob...
Is there a way to set a breakpoint on variable access in Python with PyDev?
I have a global variable (I know) that is being changed from a good value to a bad value somewhere. I don't know where, and I'd like to find out where. I would like my debugger (Eclipse/PyDev) to break any time any code writes to this global variable, something akin to hardware breakpoints in OllyDBG. One trick I've f...
[ "Unfortunately, PyDev does not have such a feature (and after thinking a bit on how would that be implemented, I couldn't come up with a way to implement that) -- your solution on changing it for a property is the one I use when I need that feature (and it won't work for a global variable as you said... in this cas...
[ 2 ]
[]
[]
[ "breakpoints", "debugging", "pydev", "python" ]
stackoverflow_0007799650_breakpoints_debugging_pydev_python.txt
Q: Fabric asks for root password I am using Fabric to run the following: def staging(): """ use staging environment on remote host""" env.user = 'ubuntu' env.environment = 'staging' env.hosts = ['host.dev'] _setup_path() def bootstrap(): """ initialize remote host environment (virtualenv, dep...
Fabric asks for root password
I am using Fabric to run the following: def staging(): """ use staging environment on remote host""" env.user = 'ubuntu' env.environment = 'staging' env.hosts = ['host.dev'] _setup_path() def bootstrap(): """ initialize remote host environment (virtualenv, deploy, update) """ require('root'...
[ "meta: Just realized this question is still unanswered. I have no idea what really happened there but here's a guess.\nThis was probably caused by failing to use a keyfile when connecting to a machine where plaintext password SSH connection was disabled.\nProper usage would be:\nfab -i keyfile.pem <fabric_task>\n\n...
[ 6 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0004416848_fabric_python.txt
Q: error in make-messages.py I run this command: make-messages.py -l fa but it has this error: 'make-messages.py' is not recognized as an internal or external command. I run it in my project root,app roo and django root,but all of them cause this error what should I do? A: That's obsolete. You should replace invok...
error in make-messages.py
I run this command: make-messages.py -l fa but it has this error: 'make-messages.py' is not recognized as an internal or external command. I run it in my project root,app roo and django root,but all of them cause this error what should I do?
[ "That's obsolete. You should replace invoking make-messages.py with django-admin.py makemessages.\n", "Run this command in project root\npython manage.py makemessages -l fa\n\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007803284_django_python.txt
Q: Representing a set of URLs in a list as a tree structure I have a list of dicts that stores URLs. It has simply two fields, title and url. Example: [ {'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'}, {'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'}, {'...
Representing a set of URLs in a list as a tree structure
I have a list of dicts that stores URLs. It has simply two fields, title and url. Example: [ {'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'}, {'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'}, {'title': 'About Page', 'url': 'http://www.example.com/thatthing...
[ "Third time is the charm... that is some nice structure you have there :). In your comment you mention that you \"haven't been able to think of a better tree format to represent data like this\"... this made me again take the liberty to (just slightly) alter the formatting of the output. In order to dynamically add...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007794489_python.txt
Q: Getting HTTP Error 500 with SPARQL query to DBPedia endpoint using Python's SPARQLwrapper I am trying to receive all properties whose labels contain a certain string. I use the following query: SELECT ?p ?l count(?p) as ?count WHERE { ?someobj ?p ?s . ?p a <http://www.w3.org/1999/02/22-rdf-syntax-ns#P...
Getting HTTP Error 500 with SPARQL query to DBPedia endpoint using Python's SPARQLwrapper
I am trying to receive all properties whose labels contain a certain string. I use the following query: SELECT ?p ?l count(?p) as ?count WHERE { ?someobj ?p ?s . ?p a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> . ?p <http://www.w3.org/2000/01/rdf-schema#label> ?l . ?l bif:contain...
[ "I think it's a time out error on dbpedia's part because it looks it up in different graphs. When you are trying it through the dbpedia web interface it always includes the uri of the graph you are querying. So try adding that to your query:\nSELECT ?p ?l count(?p) as ?count FROM <http://dbpedia.org> WHERE { \n?som...
[ 2, 1 ]
[]
[]
[ "dbpedia", "python", "sparql" ]
stackoverflow_0007795689_dbpedia_python_sparql.txt
Q: python couchdb revision conflict I have a python program that accesses a couchDB database, creates new documents and updates existing ones. For a given database, db, and document, Doc, I try to take care and reload the document before each modification: somedoc = Doc.load(db,id) before updating via doc.store(db) ...
python couchdb revision conflict
I have a python program that accesses a couchDB database, creates new documents and updates existing ones. For a given database, db, and document, Doc, I try to take care and reload the document before each modification: somedoc = Doc.load(db,id) before updating via doc.store(db) As far as I am aware this shouldn't b...
[ "I still haven't worked out where the resource conflict is coming from, given that just before storing a doc I check that the revision is correct:\nlatestRev = CouchDoc.load(db,doc.id)\nif latestRev.rev != doc.rev:\n print 'revision mismatch ' + doc.rev + '\\t' + revs.rev\nelse:\n doc.store(db)\n\nHowever, th...
[ 1 ]
[ "Have you checked to make sure that doc's revision is updated when you store? Libraries I've used won't modify doc but instead return the new revision upon a successful store.\nEdit: I guess they will edit doc:\n>>> db = s.get_or_create_db('test')\n>>> doc = { '_id': 'abc', 'content': 'words' }\n>>> db.save_doc(doc...
[ -1 ]
[ "couchdb", "database", "python" ]
stackoverflow_0007796775_couchdb_database_python.txt
Q: Interconnected ForegnKey I have a task: To make a database model with essentially 'student' and 'group'. 'Student' contains: 'Name', 'student ID card', 'group' (must be ForeigKey to Group!) 'Group' contains: 'group name' and 'captain' (must be foreign key to Student!) Now I have a collision - right straight it's...
Interconnected ForegnKey
I have a task: To make a database model with essentially 'student' and 'group'. 'Student' contains: 'Name', 'student ID card', 'group' (must be ForeigKey to Group!) 'Group' contains: 'group name' and 'captain' (must be foreign key to Student!) Now I have a collision - right straight it's impossible. So I did it in th...
[ "Try to add a related_name:\nclass Student(models.Model):\n name = models.CharField(max_length=50)\n birth_date = models.DateField()\n std_ID_card = models.IntegerField()\n group = models.ForeignKey('Group')\n\nclass Group(models.Model):\n group_name = models.CharField(max_length=50) \n captain...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007806383_django_python.txt
Q: Calling parent's __call__ method within class I'd like to call a parent's call method from inherited class Code looks like this #!/usr/bin/env python class Parent(object): def __call__(self, name): print "hello world, ", name class Person(Parent): def __call__(self, someinfo): ...
Calling parent's __call__ method within class
I'd like to call a parent's call method from inherited class Code looks like this #!/usr/bin/env python class Parent(object): def __call__(self, name): print "hello world, ", name class Person(Parent): def __call__(self, someinfo): ...
[ "The super function takes the derived class as its first parameter, not the base class.\nsuper(Person, self).__call__(someinfo)\n\nIf you need to use the base class, you can do it directly (but beware that this will break multiple inheritance, so you shouldn't do it unless you're sure that's what you want):\nParent...
[ 18 ]
[]
[]
[ "inheritance", "methods", "python", "superclass" ]
stackoverflow_0007806593_inheritance_methods_python_superclass.txt
Q: Python readline and UTF-8 I'm trying to use raw_input() with readline and utf-8 encoding (on OSX 10.6.8). Imagine the following snippet: import readline while True: try: inp = raw_input('> ') except EOFError: break This works except when trying to type non standard ASCII letters, say 'å'...
Python readline and UTF-8
I'm trying to use raw_input() with readline and utf-8 encoding (on OSX 10.6.8). Imagine the following snippet: import readline while True: try: inp = raw_input('> ') except EOFError: break This works except when trying to type non standard ASCII letters, say 'å' or 'ä'. When doing this no inp...
[ "(Reposting as an answer): OSX ships with an inferior equivalent to readline called libedit (for licensing reasons, it can't ship readline itself).\nYou can do easy_install readline to get GNU readline in Python on a Mac.\nThis also causes a problem for IPython, which now displays an ugly warning if it detects that...
[ 2 ]
[]
[]
[ "macos", "python", "readline", "unicode" ]
stackoverflow_0007806225_macos_python_readline_unicode.txt
Q: How do I do matrix computations in python without rounding? I have some integer matrices of moderate size (a few hundred rows). I need to solve equations of the form Ax = b where b is a standard basis vector and A is one of my matrices. I have been using numpy.linalg.lstsq for this purpose, but the rounding errors...
How do I do matrix computations in python without rounding?
I have some integer matrices of moderate size (a few hundred rows). I need to solve equations of the form Ax = b where b is a standard basis vector and A is one of my matrices. I have been using numpy.linalg.lstsq for this purpose, but the rounding errors end up being too significant. How can I carry out an exact symb...
[ "If your only option is to use free tools written in python, sympy might work, but it could well be simpler to use mathematica.\n", "Note that if you're serious about your comment that you require your solution vector to be integer, then you're looking for something called the \"integer least squares problem\". W...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007787732_numpy_python.txt
Q: Getting dynamic collection names in mongoengine Here is the senario. I have a model called Permission. Lets assume it looks like this: class Permission(Document): meta = {'collection': 'permission'} permission = DictField() owner = ReferenceField('user') This inherits from the mongoengine's Document...
Getting dynamic collection names in mongoengine
Here is the senario. I have a model called Permission. Lets assume it looks like this: class Permission(Document): meta = {'collection': 'permission'} permission = DictField() owner = ReferenceField('user') This inherits from the mongoengine's Document class. Thus when I save an instance of this, a colle...
[ "That's not the intended API for the dynamic collection naming. Quick search through the commits in the branch you've mentioned shows this commit which shows how to use it:\nhttps://github.com/hmarr/mongoengine/commit/c62b6321adaba6c3eb54ce2dc2c1bd3069568399\n" ]
[ 1 ]
[]
[]
[ "mongoengine", "python" ]
stackoverflow_0007805763_mongoengine_python.txt
Q: Why is my Python regular expression checking for more than one group taking so long? This question originates in Django URL resolver, but the problem seems to be a general one. I want to match URLs built like this: 1,2,3,4,5,6/10,11,12/ The regular expression I'm using is: ^(?P<apples>([0123456789]+,?)+)/(?P<oran...
Why is my Python regular expression checking for more than one group taking so long?
This question originates in Django URL resolver, but the problem seems to be a general one. I want to match URLs built like this: 1,2,3,4,5,6/10,11,12/ The regular expression I'm using is: ^(?P<apples>([0123456789]+,?)+)/(?P<oranges>([0123456789]+,?)+)/$ When I try to match it against a "valid" URL (i.e. one that mat...
[ "This is a known deficiency in many regular expression engines, including Python's and Perl's. What is happening is the engine is backtracking and getting an exponential explosion of possible matches to try. Better regular expression engines do not use backtracking for such a simple regular expression.\nYou can f...
[ 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007807289_python_regex.txt
Q: How to reschedule a task if it hasn't been running for more than 10 minutes? I have task:recursive_task which will schedule the same task to be executed 5 seconds later, but if for some reason this task crashes it needs to be rerun again. I catched nearly every scenario but you never know what will happen in the ...
How to reschedule a task if it hasn't been running for more than 10 minutes?
I have task:recursive_task which will schedule the same task to be executed 5 seconds later, but if for some reason this task crashes it needs to be rerun again. I catched nearly every scenario but you never know what will happen in the future. I first made a repeated task:manage_tasks which checks the status of recur...
[ "Try acks_late setting CELERY_ACKS_LATE, it will have the task messages be acknowledged after the task has been executed. With this you may be able to rerun your tasks more easily.\n", "I can suggest to take a look at python signals:\nhttp://docs.python.org/library/signal.html\nimport signal\n\n# Set the signal h...
[ 1, 0 ]
[]
[]
[ "celery", "django", "django_celery", "python" ]
stackoverflow_0007807417_celery_django_django_celery_python.txt
Q: Binds C function using OpenCV to python with Swig I use OpenCV and its Python wrappers on a daily basis to produce computer vision algorithms. For several complex functions, we need to keep the C version which allows lower computation time and easier reuse. In this way, I would like to bind C functions that use ...
Binds C function using OpenCV to python with Swig
I use OpenCV and its Python wrappers on a daily basis to produce computer vision algorithms. For several complex functions, we need to keep the C version which allows lower computation time and easier reuse. In this way, I would like to bind C functions that use opencv structures like iplimage to use them in Python. ...
[ "Making a Python loadable module in C is quite easy. Start here: http://docs.python.org/c-api/\nIt's easy to take a small example from the Python source itself, extend to your own use. Look in the 'Modules' dir of the Python source.\n" ]
[ 0 ]
[]
[]
[ "binding", "c", "opencv", "python", "swig" ]
stackoverflow_0007807425_binding_c_opencv_python_swig.txt
Q: os.tmpfile() doesn't work under windows? I'm trying to use generateDS under windows, which uses os.tmpfile. Unfortunately, os.tmpfile doesn't work for me: (oneclickcos) C:\Users\Marcin\Documents\oneclickcos\xsd>python Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", ...
os.tmpfile() doesn't work under windows?
I'm trying to use generateDS under windows, which uses os.tmpfile. Unfortunately, os.tmpfile doesn't work for me: (oneclickcos) C:\Users\Marcin\Documents\oneclickcos\xsd>python Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more i...
[ "Run the script as administrator (right click on the script and select 'run as administrator'), the script lacks the permissions to execute os.tmpfile().\nEdit:\nAs I see you're using the interpreter, simply run the interpreter as administrator. If you're accessing it though a terminal, running the terminal as admi...
[ 3, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007807855_python_windows.txt
Q: Integrate Rails and Python This might sound like a vague question, but i wanted to know if there is to integrate Python code into my rails application. More specifically, if i had a game coded with something like pygame (and it might be pushing too far to say panda3d), how could i make it so someone could play thr...
Integrate Rails and Python
This might sound like a vague question, but i wanted to know if there is to integrate Python code into my rails application. More specifically, if i had a game coded with something like pygame (and it might be pushing too far to say panda3d), how could i make it so someone could play through their browser on my rails a...
[ "Panda3D applications can be run in the browser provided the user has a Panda3D plugin. See section III of the Panda3D manual Distributing Panda3D Applications.\npygame cannot be run in the browser and thus cannot be integrated into a rails application.\nI do not have rails experience, but I would be surprised if ...
[ 2 ]
[]
[]
[ "integrate", "panda3d", "pygame", "python", "ruby_on_rails" ]
stackoverflow_0007807856_integrate_panda3d_pygame_python_ruby_on_rails.txt
Q: Setting Meta.fields doesn't do what I expect Calling set_fields() here doesn't do what I'd expect. (The code's context is a django model, but I suspect I've just made a python error). class FooEdit(ModelForm): class Meta: model = Foo # Client should call set_fields() # fields = ('A', 'B...
Setting Meta.fields doesn't do what I expect
Calling set_fields() here doesn't do what I'd expect. (The code's context is a django model, but I suspect I've just made a python error). class FooEdit(ModelForm): class Meta: model = Foo # Client should call set_fields() # fields = ('A', 'B') def set_fields(self, pro): """Set fields c...
[ "You are setting class properties using an instance. For example\nclass A(object):\n a=0\n\nx=A()\nprint x.a #prints 0\nx.a=2\nx.a #prints 2\nA.a #prints 0\n\n" ]
[ 1 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0007808406_django_models_python.txt
Q: Which Python GUI IDE is the most widely used? I am still kind of new to programming and after playing around with a lot of languages trying to find which one worked best for me I stumbled across python and have been doing really well with it. The only problem/concern I have is that I do not mainly want to do web d...
Which Python GUI IDE is the most widely used?
I am still kind of new to programming and after playing around with a lot of languages trying to find which one worked best for me I stumbled across python and have been doing really well with it. The only problem/concern I have is that I do not mainly want to do web development. I want to create desktop apps with nice...
[ "You can use Visual Studio to build IronPython GUI applications as well: http://msdn.microsoft.com/en-us/library/bb165375(v=vs.80).aspx\nEDIT: You can now use pytools (http://pytools.codeplex.com/) to develop non-IronPython apps in VisualStudio.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007808494_python_wxpython.txt
Q: Selenium error: UnicodeEncodeError I am getting the following error when i execute the following command: text = idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station self.se.is_element_present("css=a[href]:contains('idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com mem...
Selenium error: UnicodeEncodeError
I am getting the following error when i execute the following command: text = idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station self.se.is_element_present("css=a[href]:contains('idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station')") The title I am searchin...
[ "Selenium itself is Unicode-safe. It's probably a pure-Python problem, not a Selenium problem.\n" ]
[ 0 ]
[]
[]
[ "css", "python", "selenium", "selenium_rc" ]
stackoverflow_0007805501_css_python_selenium_selenium_rc.txt
Q: do I understand the difference between instance attributes and class attributes in Python? Let's say I have a method and a class: def my_method(self): self.mark = 'Knopfler' class MySubclass(object) my_method = my_method I can think of 3 or 4 ways to use my_method within another class. Case 1: If I wan...
do I understand the difference between instance attributes and class attributes in Python?
Let's say I have a method and a class: def my_method(self): self.mark = 'Knopfler' class MySubclass(object) my_method = my_method I can think of 3 or 4 ways to use my_method within another class. Case 1: If I want to have access to my_method within yet another class like this: class MyClass(object): def...
[ "Answering to your last case, you can bind a method to a class instance with MethodType:\nimport types\n\nclass MyClass(object):\n def __init__(self):\n self.my_method = types.MethodType(my_method, self)\n\n" ]
[ 1 ]
[]
[]
[ "class", "instance", "methods", "python" ]
stackoverflow_0007656289_class_instance_methods_python.txt
Q: Calling method from inside POST in GAE I have my main.py looking like this:- #!/usr/bin/env python import cgi from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import util # imports for sending mail from google.appengine.api import ...
Calling method from inside POST in GAE
I have my main.py looking like this:- #!/usr/bin/env python import cgi from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import util # imports for sending mail from google.appengine.api import mail from google.appengine.api import users ...
[ "You're treating a class method like a function. Choose one:\ndef sendMail(request):\n message.send()\n\nclass MainHandler(webapp.RequestHandler):\n\n def post(self):\n sendMail(self.request)\n\nOr:\nclass MainHandler(webapp.RequestHandler):\n\n def sendMail(self):\n # request = self.request\...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007807984_google_app_engine_python.txt
Q: Python and Floats I have this code : N = 10 for i in range(1,N): P[i,i] = (i/N) + pow((1-i/N),2) But my division operations are getting rounded down to the nearest integer. How can I instruct Python to do floating-point division? A: You are doing integer division. Try something like this: N = 10 for i in ...
Python and Floats
I have this code : N = 10 for i in range(1,N): P[i,i] = (i/N) + pow((1-i/N),2) But my division operations are getting rounded down to the nearest integer. How can I instruct Python to do floating-point division?
[ "You are doing integer division. Try something like this:\nN = 10\nfor i in range(1,N):\n P[i,i] = (float(i)/N) + pow((1-float(i)/N),2)\n\n", "Add this line to the top of your script:\nfrom __future__ import division\n\nThis will allow division of integers to give floats with the usual division operator /. If...
[ 5, 5, 0 ]
[]
[]
[ "floating_point", "integer", "python" ]
stackoverflow_0007808891_floating_point_integer_python.txt
Q: Parsing XML and Ordering Node Attributes Automatically by ID in Python I have a question about Python, XML and IDs. My XML is: <settings> <plugin id="1"> <param id="1" name="mailsend" value="Send Mail" /> <param id="2" name="mailfunc" value="func/sendmail.py" /> <param id="3...
Parsing XML and Ordering Node Attributes Automatically by ID in Python
I have a question about Python, XML and IDs. My XML is: <settings> <plugin id="1"> <param id="1" name="mailsend" value="Send Mail" /> <param id="2" name="mailfunc" value="func/sendmail.py" /> <param id="3" name="mailfunccount" value="3" /> <param id="4" name="mailto" ...
[ "Well the xml is obviously nested, so your code will need to follow the nesting. You need two nested for statements:\nfor plugin in myfile.getElementsByTagName('plugin'):\n print \"Plugin \"+plugin.getAttribute('id')\n for param in plugin.getElementsByTagName('param'):\n print param.getAttribute('value...
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0007808787_python_xml.txt
Q: How can I successfully insert row columns selected from MySQL table into a destination MSSQL table using Python? This python script connects to MySQL database and MssQL 2008 R2 database. MySQL database runs on Linux Ubuntu 11.04. MssQL 2008 runs on Windows. The script runs from Linux (Ubuntu 11.04). #!...
How can I successfully insert row columns selected from MySQL table into a destination MSSQL table using Python?
This python script connects to MySQL database and MssQL 2008 R2 database. MySQL database runs on Linux Ubuntu 11.04. MssQL 2008 runs on Windows. The script runs from Linux (Ubuntu 11.04). #!/usr/bin/python import pymssql as ms import MySQLdb as mdb import sys ...
[ "The problem got resolved once I called commit() as follows connMSSQL.commit() immediately after curMSSQL.execute(qryINS) line\n #!/usr/bin/python\n\n import pymssql as ms\n import MySQLdb as mdb\n import sys\n\n #Connection to MSSQL\n connMSSQL=ms.connect(host='192.168.8.5...
[ 1, 0 ]
[]
[]
[ "linux", "mysql", "python", "sql_server", "windows" ]
stackoverflow_0007803496_linux_mysql_python_sql_server_windows.txt
Q: Why are the timestamps incorrect when debugging App Engine Python code Under my debugger: logging.info("TZ = %s -- It is now: %s", os.environ['TZ'], time.ctime()) TZ = UTC -- It is now: Mon Oct 17 12:10:44 2011 Under App Engine Launcher: logging.info("TZ = %s -- It is now: %s", os.environ['TZ'], time.ctime()) TZ ...
Why are the timestamps incorrect when debugging App Engine Python code
Under my debugger: logging.info("TZ = %s -- It is now: %s", os.environ['TZ'], time.ctime()) TZ = UTC -- It is now: Mon Oct 17 12:10:44 2011 Under App Engine Launcher: logging.info("TZ = %s -- It is now: %s", os.environ['TZ'], time.ctime()) TZ = UTC -- It is now: Mon Oct 17 17:09:24 2011 So what do I have setup wrong?...
[ "The issue is that the C runtime functions on Windows with Python 2.5 seem to cache the value of the TZ environment variable the first time either time or ctime is called. The following will display the time in local time and not in UTC:\nimport time, os\ntime.time()\nos.environ['TZ'] = 'UTC'\nprint time.ctime()\n...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007797164_google_app_engine_python.txt
Q: Attributes initialization/declaration in Python class: where to place them? I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function? i.e. class A(object): foo = None vs class A(object): def __init__(self): self...
Attributes initialization/declaration in Python class: where to place them?
I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function? i.e. class A(object): foo = None vs class A(object): def __init__(self): self.foo = None
[ "If you want the attribute to be shared by all instances of the class, use a class attribute:\nclass A(object):\n foo = None\n\nThis causes ('foo',None) to be a (key,value) pair in A.__dict__.\nIf you want the attribute to be customizable on a per-instance basis, use an instance attribute:\nclass A(object):\n ...
[ 75, 4 ]
[]
[]
[ "attributes", "coding_style", "python" ]
stackoverflow_0007809407_attributes_coding_style_python.txt
Q: How to parse timezone data? There has been a recent issue with the timezone data with a claim from some company that claim to has been violated, so IANA has taken it upon themselves to provide the timezone data. Now the problem is that data hosted here, isn't in a format I can parse easily is there something miss...
How to parse timezone data?
There has been a recent issue with the timezone data with a claim from some company that claim to has been violated, so IANA has taken it upon themselves to provide the timezone data. Now the problem is that data hosted here, isn't in a format I can parse easily is there something missing here or do I need to formulat...
[ "The fields are tab separated. There are Zone and Rule fields. Lines beginning with a # being comments.\nZone field format\n# Zone NAME GMTOFF RULES FORMAT [UNTIL]\n\nRule field format\n# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S\n\nTSV (or CSV) parsers in Python will be able to par...
[ 1 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0007808977_python_timezone.txt
Q: Matching a Comma Separated List I have a sample string like so: [{HST, AKST, PST, MST, CST, EST, AST, WAT, CET, GMT, EET, CCT, AWST, JST, EAST, NZT} {0:10}] I'm interested in the first set of items in brackets: {HST, AKST, PST, MST, CST, EST, AST, WAT, CET, GMT, EET, CCT, AWST, JST, EAST, NZT} I would like pars...
Matching a Comma Separated List
I have a sample string like so: [{HST, AKST, PST, MST, CST, EST, AST, WAT, CET, GMT, EET, CCT, AWST, JST, EAST, NZT} {0:10}] I'm interested in the first set of items in brackets: {HST, AKST, PST, MST, CST, EST, AST, WAT, CET, GMT, EET, CCT, AWST, JST, EAST, NZT} I would like parse the set and put it into a list. I'm...
[ "for match in re.finditer(\"(?i)[a-z]+\", subject):\n # match start: match.start()\n # match end (exclusive): match.end()\n # matched text: match.group()\n\nThis will help you iterate through the \"elements\" of your list.\nEDIT : You now write it's part of a larger string. That changes the original questi...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007809452_python_regex.txt
Q: Python naming conventions for attributes and methods meant to be overwritten I have some object oriented code in Python, where some classes are meant to be extended to provide the missing custom bits of code (a la Template Method pattern, but also with variables), that will only be used by the super class, not by ...
Python naming conventions for attributes and methods meant to be overwritten
I have some object oriented code in Python, where some classes are meant to be extended to provide the missing custom bits of code (a la Template Method pattern, but also with variables), that will only be used by the super class, not by the client code using them. Are there any style conventions for such abstract (or ...
[ "I usually use single underscore e.g. _myvar for protected (as in C++) methods/attributes, which can be used by derived classes and use double underscore e.g. __var when it should not be used by anybody else, and as double-underscore names at class definition level are mangled, so they can't be overridden in derive...
[ 13, 10, 2 ]
[]
[]
[ "naming_conventions", "python", "template_method_pattern" ]
stackoverflow_0007809287_naming_conventions_python_template_method_pattern.txt
Q: opencv getImage() error I wrapped opencv today with simplecv python interface. After going through the official SimpleCV Cookbook I was able to successfully Load, Save, and Manipulate images. Thus, I know the library is being loaded properly. However, under the Using a Camera, Kinect, or Virtual Camera heading I w...
opencv getImage() error
I wrapped opencv today with simplecv python interface. After going through the official SimpleCV Cookbook I was able to successfully Load, Save, and Manipulate images. Thus, I know the library is being loaded properly. However, under the Using a Camera, Kinect, or Virtual Camera heading I was unsuccessful in running so...
[ "since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:\ndef getImage(self):\n if (not self.threaded):\n cv.GrabFrame(self.capture)\n\n frame = cv.RetrieveFrame(self.capture)\n import pdb # <-- add this line\n pdb.set_trace() # <-- a...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "opencv", "python", "simplecv" ]
stackoverflow_0006990760_opencv_python_simplecv.txt
Q: I want to use NumPy/SciPy. Should I use Python 2 or 3? I am about to embark on some signal processing work using NumPy/SciPy. However, I have never used Python before and don't know where to start. I see there are currently two branches of Python in this world: Version 2.x and 3.x. Being a neophile, I instinctive...
I want to use NumPy/SciPy. Should I use Python 2 or 3?
I am about to embark on some signal processing work using NumPy/SciPy. However, I have never used Python before and don't know where to start. I see there are currently two branches of Python in this world: Version 2.x and 3.x. Being a neophile, I instinctively tend to go for the newer one, but there seems to be a lot...
[ "I am using Python 2.6 with Numpy. I can confirm that Python 3 is not backward compatible. So I myself am not very confident with upgrading. Have a look at the cookbook to get started\nhttp://www.scipy.org/Cookbook\n", "Both scipy and numpy are compatible with py3k. However, if you'll need to plot stuff: matplotl...
[ 3, 3, 3, 3, 2, 2 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0004758693_numpy_python_python_3.x.txt
Q: Need init.d script for Python application I have a python based application which works like a feed aggregator and needs to be part of init.d script so that I could control the execution with start/stop/restart options. Also I want the init.d script to be setup as a cron job (I have example here). I found one sam...
Need init.d script for Python application
I have a python based application which works like a feed aggregator and needs to be part of init.d script so that I could control the execution with start/stop/restart options. Also I want the init.d script to be setup as a cron job (I have example here). I found one sample here http://homepage.hispeed.ch/py430/pytho...
[ "You could consider writing a Upstart task for operating systems which use Upstart. \nExample:\n# Start zeya\n#\n\ndescription \"Start Zeya music server\"\n\nstart on startup\n\ntask\nexec python /home/r00t/code-hacking/serve-music/zeya/src/zeya/zeya.py\n--path=/home/r00t/Music\n\nAdd this to a file, say 'zeya....
[ 7, 2, 0, 0 ]
[]
[]
[ "init.d", "python", "ubuntu" ]
stackoverflow_0001984847_init.d_python_ubuntu.txt
Q: How does the shift "1<<i" work in Python? I have the following code in Python: for i in range(4): if self.start == self.corners[i]: self.visitedCorners += (1 << i) I'm working with co-ordinates. self.start and self.corners are co-ordinates. So with the code on the top I want to check whether the start is a ...
How does the shift "1<<i" work in Python?
I have the following code in Python: for i in range(4): if self.start == self.corners[i]: self.visitedCorners += (1 << i) I'm working with co-ordinates. self.start and self.corners are co-ordinates. So with the code on the top I want to check whether the start is a corner. If the start is the same of a corner, I...
[ "All that 1 << i does is produce the number with the i-th least significant bit set to 1 and all other bits set to 0:\n>>> for i in range(4): print bin(1 << i)\n... \n0b1\n0b10\n0b100\n0b1000\n\nIn the code, self.visitedCorners is a bit mask, where the four least significant bits correspond to the four corners. Eac...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007810573_python.txt
Q: Can you make multiple "if" conditions in Python? In JavaScript, one could do this: if (integer > 3 && integer < 34){ document.write("Something") } Is this possible in Python? A: Python indeed allows you to do such a thing if integer > 3 and integer < 34 Python is also smart enough to handle: if 3 < integer...
Can you make multiple "if" conditions in Python?
In JavaScript, one could do this: if (integer > 3 && integer < 34){ document.write("Something") } Is this possible in Python?
[ "Python indeed allows you to do such a thing\nif integer > 3 and integer < 34\n\nPython is also smart enough to handle:\nif 3 < integer < 34:\n # do your stuff\n\n", "Python replaces the usual C-style boolean operators (&&, ||, !) with words: and, or, and not respectively.\nSo you can do things like:\nif (isLa...
[ 57, 13, 11, 5, 3, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007809698_if_statement_python.txt
Q: Reading stdout from one program in another program I have a problem concerning the reading of the stdout in python. I have to explain a bit what I am trying to do. I have a Python program (foo); this calls a second python program (bar). bar will give back to stdout status details and other information to be logged...
Reading stdout from one program in another program
I have a problem concerning the reading of the stdout in python. I have to explain a bit what I am trying to do. I have a Python program (foo); this calls a second python program (bar). bar will give back to stdout status details and other information to be logged. The foo now has to read this. In principle it works. I...
[ "Er, bar.stdout.readline()? Going all the way to file descriptors is rarely necessary.\n", "How about Popen.communicate? This will also let you send input to the process if you want to.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "stdin", "stdout" ]
stackoverflow_0007808345_python_stdin_stdout.txt
Q: python: combine sort-key-functions itemgetter and str.lower I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters. dict1 = {'name':'peter','phone':'12355'} dict2 = {'name':'Paul','phone':'545435'} dict3 = {'name':'klaus','phone':'55345'} ...
python: combine sort-key-functions itemgetter and str.lower
I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters. dict1 = {'name':'peter','phone':'12355'} dict2 = {'name':'Paul','phone':'545435'} dict3 = {'name':'klaus','phone':'55345'} dict4 = {'name':'Krishna','phone':'12345'} dict5 = {'name':'Ali',...
[ "How about this:\nlist_of_dicts.sort(key=lambda a: a['name'].lower())\n\n", "In the general case, you'll want to write your key-extraction function for sorting purposes; only in special (though important) cases it happens that you can just reuse an existing callable to extract the keys for you, or just conjoin a ...
[ 16, 13, 5, 4, 4, 4, 2 ]
[]
[]
[ "function", "key", "python", "sorting" ]
stackoverflow_0001394475_function_key_python_sorting.txt
Q: What does python3 do with the methods passed to the "key" argument of sorted()? I have a question about how python treats the methods passed to sorted(). Consider the following small script: #!/usr/bin/env python3 import random class SortClass: def __init__(self): self.x = random.choice(range(10)) ...
What does python3 do with the methods passed to the "key" argument of sorted()?
I have a question about how python treats the methods passed to sorted(). Consider the following small script: #!/usr/bin/env python3 import random class SortClass: def __init__(self): self.x = random.choice(range(10)) self.y = random.choice(range(10)) def getX(self): return self.x ...
[ "Methods on classes are just functions.\nclass MyClass(object):\n... def my_method(self): pass\n...\n>>> MyClass.my_method\n<function my_method at 0x661c38>\n\nWhen you fetch a method from an instance of a class, Python uses some magic (called descriptors) to return a bound method. Bound methods automatically i...
[ 8, 0 ]
[]
[]
[ "python", "python_3.x", "sorting" ]
stackoverflow_0000770845_python_python_3.x_sorting.txt
Q: Check if two variables have values from two different sets, the DRY way I have a range of values (L,R,U,D) and two variables, d and newd, containing one of them. I need to check if d and newd are in the same subset (L,R or U,D) or not. I know I can do this: d in {'L','R'} and newd in {'U','D'} or d in {'U','D'} an...
Check if two variables have values from two different sets, the DRY way
I have a range of values (L,R,U,D) and two variables, d and newd, containing one of them. I need to check if d and newd are in the same subset (L,R or U,D) or not. I know I can do this: d in {'L','R'} and newd in {'U','D'} or d in {'U','D'} and newd in {'L','R'} this indeed returns False if they both have values in L...
[ "If you know that there are only two sets and that your values must be in one or the other, then you can simplify it to this:\n(d in set1) == (newd in set2)\n\nExplanation:\n\nIf d is in set 1 and newd is in set 2, both sides of the == are True, so the expression returns True.\nIf d is in set 2 and newd is in set 1...
[ 4, 0 ]
[]
[]
[ "coding_style", "dry", "python" ]
stackoverflow_0007811447_coding_style_dry_python.txt
Q: How to convert Tkinter canvas coordinate to window? Is there a way to convert canvas coordinates to window coordinates in Tkinter? It would be the opposite of converting from window to canvas coordinate, which is done like this: x = canvas.canvasx(event.x) A: Use the canvasx and canvasy methods, giving an argum...
How to convert Tkinter canvas coordinate to window?
Is there a way to convert canvas coordinates to window coordinates in Tkinter? It would be the opposite of converting from window to canvas coordinate, which is done like this: x = canvas.canvasx(event.x)
[ "Use the canvasx and canvasy methods, giving an argument of zero, to compute the x/y of the upper left corner of the visible canvas. Then just use math to convert the canvas coordinate to something relative to the window.\n# upper left corner of the visible region\nx0 = self.canvas.canvasx(0)\ny0 = self.canvas.can...
[ 10 ]
[]
[]
[ "coordinate_systems", "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0007811263_coordinate_systems_python_tkinter_tkinter_canvas.txt
Q: Saving embedded images in emails with python I am trying to grab images in an embedded email. The problem is that the image that i save is unreadable and i can't figure out why. The email (saved as a file which i load in the beginning of the code): MIME-Version: 1.0 Received: by 10.100.120.7 with HTTP; Tue, 18 Oc...
Saving embedded images in emails with python
I am trying to grab images in an embedded email. The problem is that the image that i save is unreadable and i can't figure out why. The email (saved as a file which i load in the beginning of the code): MIME-Version: 1.0 Received: by 10.100.120.7 with HTTP; Tue, 18 Oct 2011 10:36:48 -0700 (PDT) In-Reply-To: <8B4FDE0...
[ "You're writing the image in text mode and Python is mangling the line endings. Open it in wb mode to write it verbatim.\n", "The problem is in this lines: \nfor name, image in images:\n with open(r'c:\\shpiz\\test\\%s'%name,'w') as f:\n f.write(image)\n\nThe file that you create with open is a text fil...
[ 2, 0 ]
[]
[]
[ "email", "image", "python" ]
stackoverflow_0007811619_email_image_python.txt