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: Accessing list items with getattr/setattr in Python Trying to access/assign items in a list with getattr and setattr funcions in Python. Unfortunately there seems to be no way of passing the place in the list index along with the list name. Here's some of my tries with some example code: class Lists (object): de...
Accessing list items with getattr/setattr in Python
Trying to access/assign items in a list with getattr and setattr funcions in Python. Unfortunately there seems to be no way of passing the place in the list index along with the list name. Here's some of my tries with some example code: class Lists (object): def __init__(self): self.thelist = [0,0,0] Ls = Lists(...
[ "getattr(Ls, 'thelist')[0] = 2\ngetattr(Ls, 'thelist').append(3)\nprint getattr(Ls, 'thelist')[0]\n\nIf you want to be able to do something like getattr(Ls, 'thelist[0]'), you have to override __getattr__ or use built-in eval function.\n", "You could do:\nl = getattr(Ls, 'thelist')\nl[0] = 2 # for example\nl.app...
[ 9, 5, 3 ]
[]
[]
[ "getattr", "python", "setattr" ]
stackoverflow_0006893929_getattr_python_setattr.txt
Q: Python newline display in console So, when I try to print help/info of Python functions function.__doc__, the console output instead of printing a newline when \n occurs in the doc string, prints \n. Can anyone help me with disabling/helping out with this? This is my output: 'divmod(x, y) -> (div, mod)\n\nReturn t...
Python newline display in console
So, when I try to print help/info of Python functions function.__doc__, the console output instead of printing a newline when \n occurs in the doc string, prints \n. Can anyone help me with disabling/helping out with this? This is my output: 'divmod(x, y) -> (div, mod)\n\nReturn the tuple ((x-x%y)/y, x%y). Invariant: ...
[ "Looks like you inspected the object in the interactive shell, not printed it. If you mean print, write it.\n>>> \"abc\\n123\"\n\"abc\\n123\"\n>>> print \"abc\\n123\"\nabc\n123\n\nIn python 3.x print is an ordinary function, so you have to use (). The following (recommended) will work in both 2.x and 3.x:\n>>> from...
[ 24, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007115829_python.txt
Q: How to change tags on a web page using mechanize I am using mechanize to interact with a website. The website is a search engine with different channels such as knowledge, book, journal and newspaper. Some of the code like this: <UL> <LI id=me_0_1 style="DISPLAY: none; FONT-WEIGHT: bold;"> <A style="widt...
How to change tags on a web page using mechanize
I am using mechanize to interact with a website. The website is a search engine with different channels such as knowledge, book, journal and newspaper. Some of the code like this: <UL> <LI id=me_0_1 style="DISPLAY: none; FONT-WEIGHT: bold;"> <A style="width:30px;text-decoration:none;"> <FONT color=...
[ "You need to sniff what's happening inside the change_Tag function. Open its sources and look for AJAX-requests, redirects, script tag insections. After that just send the appropriate request using Mechanize.\n" ]
[ 0 ]
[]
[]
[ "javascript", "mechanize", "python", "web_crawler" ]
stackoverflow_0007116148_javascript_mechanize_python_web_crawler.txt
Q: Django ImportError I created my own Django application with directory structure /appname __init__.py models.py /submodule1 __init__.py a.py Inside a.py I have the following import from ..models import Something This works okay if I have /appname inside my /djangoproject folder, but wh...
Django ImportError
I created my own Django application with directory structure /appname __init__.py models.py /submodule1 __init__.py a.py Inside a.py I have the following import from ..models import Something This works okay if I have /appname inside my /djangoproject folder, but when I install the app to ...
[ "It turns out that it was a circular import error. models.py was importing a.py and a.py was importing models.py.\nBreaking this circle solved the import issues, but now it is time to figure out how to do lazy evaluation in Python :-)\n", "Put empty file named: __init__.py inside /submodule1 so Python can parse i...
[ 11, 3 ]
[]
[]
[ "django", "importerror", "python", "python_import" ]
stackoverflow_0007102852_django_importerror_python_python_import.txt
Q: noob python question, extract letter from list not sure why this isn't working. error I'm getting: ord() expected a character, but string of length 0 found code: phrase = 'test' number = 0 text = 0 random1 = '' while (number <= len(phrase)): letter = phrase[number:number+1] text = ord(letter) - ord('a...
noob python question, extract letter from list
not sure why this isn't working. error I'm getting: ord() expected a character, but string of length 0 found code: phrase = 'test' number = 0 text = 0 random1 = '' while (number <= len(phrase)): letter = phrase[number:number+1] text = ord(letter) - ord('a') .... number = number + 1 if a print lett...
[ "You are failing on your last iteration. Because you let number take the value len(phrase), you are trying to slice your string beyond the end.\nFor example:\n>>> \"abc\"[3:4]\n''\n\nString indices range from 0 to len(s)-1.\nBTW: Python gives you much nicer ways to iterate over strings:\nphrase = 'test'\nfor lette...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007116367_python.txt
Q: Python making gtk.Layout with Scrollbars How could I have a scrollbar inside a gtk.Layout. For example, in my code I have: import pygtk pygtk.require('2.0') import gtk class ScrolledWindowExample: def __init__(self): self.window = gtk.Dialog() self.window.connect("destroy", self.destroy) ...
Python making gtk.Layout with Scrollbars
How could I have a scrollbar inside a gtk.Layout. For example, in my code I have: import pygtk pygtk.require('2.0') import gtk class ScrolledWindowExample: def __init__(self): self.window = gtk.Dialog() self.window.connect("destroy", self.destroy) self.window.set_size_request(300, 300) ...
[ "Does it works if you either use gtk.Window() instead of gtk.Dialog(); or execute self.window.run() after self.window.show_all()?\nThe difference between Dialog and common Window is that Dialog has its own loop which processes events. As you do not run its run() command, this loop never gets the chance to catch the...
[ 0 ]
[]
[]
[ "dynamic", "gtk", "python", "scrollbar" ]
stackoverflow_0007112657_dynamic_gtk_python_scrollbar.txt
Q: Assigning a string to a JavaScript var from django I have the following template: var url = {{url}}; $.getJSON(url... and the following view: return render_to_response('template.html', {"url":"/this/url/"}) but for some reason javascript does not treat this as a string. Is there a reason why? What is the syntax ...
Assigning a string to a JavaScript var from django
I have the following template: var url = {{url}}; $.getJSON(url... and the following view: return render_to_response('template.html', {"url":"/this/url/"}) but for some reason javascript does not treat this as a string. Is there a reason why? What is the syntax that I should be using?
[ "This line in your template:\nvar url = {{url}};\n\nWill become this:\nvar url = /this/url;\n\nThere are no quotes in the template, and there are no quotes in the string, so there are no quotes in the output. You should use this:\nvar url = \"{{url}}\";\n\nor even better:\nvar url = \"{{url|escapejs}}\";\n\nso tha...
[ 3 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0007116464_django_javascript_jquery_python.txt
Q: Best way of storing incremental numbers? I'm implementing a voting system for a relatively large website and I'm wondering where should I store the vote count. The main problem is that storing them in the main database would put a lot of strain on it, as MySQL isn't very good at handing lots and lots of simple que...
Best way of storing incremental numbers?
I'm implementing a voting system for a relatively large website and I'm wondering where should I store the vote count. The main problem is that storing them in the main database would put a lot of strain on it, as MySQL isn't very good at handing lots and lots of simple queries. My best option so far is to use memcach...
[ "Can you accept some degree of vote loss? If so, you can do a hybrid solution. Every modulo 100 (10, something), update the SQL database with the current memcache value. You can also have a periodic script scan and update if required.\n", "I just ran this, which is basically the sqlite example from the docs excep...
[ 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "memcached", "python", "voting" ]
stackoverflow_0007112347_memcached_python_voting.txt
Q: How to convert CvMat to Numpy array? Looking to convert a CvMat to numpy array. A: From the OpenCV Python Cookbook: >>> import cv, numpy # Comments added by me >>> mat = cv.CreateMat(3, 5, cv.CV_32FC1) # make a 3x5 mat >>> cv.Set(mat, 7) # set the cells to 7 >>> a =...
How to convert CvMat to Numpy array?
Looking to convert a CvMat to numpy array.
[ "From the OpenCV Python Cookbook:\n>>> import cv, numpy # Comments added by me\n>>> mat = cv.CreateMat(3, 5, cv.CV_32FC1) # make a 3x5 mat\n>>> cv.Set(mat, 7) # set the cells to 7\n>>> a = numpy.asarray(mat) # convert it to a numpy array\n>>> print a\n[...
[ 6 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0007116751_numpy_opencv_python.txt
Q: Pylab.bar plotting difficulty I have been putting together this plotting program. It strips out numbers from a set of files, does some math, and then should plot out a bar chart to show how the numbers change. From what I can tell, the pylab.bar() part of the program is unable to properly take the calculated data ...
Pylab.bar plotting difficulty
I have been putting together this plotting program. It strips out numbers from a set of files, does some math, and then should plot out a bar chart to show how the numbers change. From what I can tell, the pylab.bar() part of the program is unable to properly take the calculated data and use it. The program keeps askin...
[ "I think you are right, it has to do with your data still being in string format. Here is a striped down version of your program:\nimport pylab\nfrom pylab import *\n\nsimp = \"11,22,1,.5,.75,1,1.2,.9\"\nt = [float(val) for val in simp.split(',')]\nc = t[2]\nan0 = t[3]\nan1 = t[4]\nan2 = t[5]\nan3 = t[6]\nan4 = t[7...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006986047_matplotlib_python.txt
Q: python - A strange problem when I'm trying to display an image in the Toplevel widget I'm using Python(2.5) to make a "web album viewer". I use Tkinter to write GUI, urllib2 to fetch the image from web, PIL to handle the image User would click a button, and then it would create a Toplevel widget, download the pic...
python - A strange problem when I'm trying to display an image in the Toplevel widget
I'm using Python(2.5) to make a "web album viewer". I use Tkinter to write GUI, urllib2 to fetch the image from web, PIL to handle the image User would click a button, and then it would create a Toplevel widget, download the picture, and display it in the Toplevel widget. The button is bound to the "look" method. So t...
[ "Without seeing more code, my guess is that you are neglecting to start the event loop, which is necessary for widgets to refresh themselves. When you add the code that throws an error, that error triggers the event loop which causes the window to refresh.\n", "My guess would be garbage collection.\nTry something...
[ 0, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007101124_python_tkinter.txt
Q: Different Parallel Module in Python These days I have to deal with extremely large log data (700GB after compressed as 7z), the performance issue is critical. Considering the environment i was working (8-Cores), I was thinking leveraging parallel programming to achieve better performance. Currently I was using th...
Different Parallel Module in Python
These days I have to deal with extremely large log data (700GB after compressed as 7z), the performance issue is critical. Considering the environment i was working (8-Cores), I was thinking leveraging parallel programming to achieve better performance. Currently I was using the built-in multiprocessing library, the p...
[ "First, just a few questions:\n\n700GB compressed so how much uncompressed?\nHow many files?\nWhat are you trying to do with these logs? How can we divide and\nconquer?\n\nI think you should look into MapReduce for this volume of data.\nFor the purposes of having an example task I'm just going to assume you have 8...
[ 3, 0, 0 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0007116428_parallel_processing_python.txt
Q: Vector2 multiplication causing Segmentation Fault in python I'm using pygame with python to dable in game development and I just hit a brick wall. When one of my entities attempts to move using Vector2 multiplication I get "Fatal Python error: (pygame parachute) Segmentation Fault". The immediate code around the ...
Vector2 multiplication causing Segmentation Fault in python
I'm using pygame with python to dable in game development and I just hit a brick wall. When one of my entities attempts to move using Vector2 multiplication I get "Fatal Python error: (pygame parachute) Segmentation Fault". The immediate code around the error is this: # destination and location are Vector2, and the di...
[ "It only crashes for me with in-place addition. v = v + v2 works fine. (Python 3.2, pygame 1.9.2pre). \nI don't see anything obviously wrong in math.c, vector_generic_math, but based on my experiments it seems there's a pointer bug somewhere. You should submit a bug report.\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007116813_pygame_python.txt
Q: How to make groups of five elements from the list? My GAE application receives several files in the upload (can be from 0 to N). I have there list in files_arguments list: files_arguments = self.request.arguments() I need to take first 5 elements, process them. Then take next 5 elements and process. And so on. La...
How to make groups of five elements from the list?
My GAE application receives several files in the upload (can be from 0 to N). I have there list in files_arguments list: files_arguments = self.request.arguments() I need to take first 5 elements, process them. Then take next 5 elements and process. And so on. Last group, of course, can have less than 5 elements. What...
[ "Here's the low-tech approach. It doesn't throw away the last group if it's smaller than n.\nn = 5\ngroups = [files_arguments[i:i + n] for i in range(0, len(files_arguments), n)]\n\n", "As it says in the documentation for zip, \n\nThe left-to-right evaluation order of the iterables is guaranteed. This makes possi...
[ 6, 3, 1, 1 ]
[]
[]
[ "google_app_engine", "list", "python" ]
stackoverflow_0006890065_google_app_engine_list_python.txt
Q: Python: overloading tuple multi-assignment capabilities? So i have made my own dict-based named-tuple class: class t(dict): def __getattr__(self, v): try: return self[v] except KeyError: raise AttributeError("Key " + str(v) + " does not exist.") def __init__(self, *args, **kwarg...
Python: overloading tuple multi-assignment capabilities?
So i have made my own dict-based named-tuple class: class t(dict): def __getattr__(self, v): try: return self[v] except KeyError: raise AttributeError("Key " + str(v) + " does not exist.") def __init__(self, *args, **kwargs): for source in args: for i, j in source.item...
[ "Yes. Implement __iter__(). \nclass unpackable_dict(dict):\n def __iter__(self):\n return (self[key] for key in sorted(self.keys()))\n\nd = unpackable_dict(a=1, b=2)\na, b = d\n\nThe reason you normally can't unpack values from a dict like you can a tuple is that dicts don't have a defined order. I've use...
[ 12 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0007117331_python_tuples.txt
Q: Problem with a User Define Function in Python Ok so here's my problem, I defined a function that's suppose to count the number of times a certain fragment occurs in a string. The function starts searching at Index[0] and subsequent searches start at the index of the last match in the string. HERE'S THE CODE def fu...
Problem with a User Define Function in Python
Ok so here's my problem, I defined a function that's suppose to count the number of times a certain fragment occurs in a string. The function starts searching at Index[0] and subsequent searches start at the index of the last match in the string. HERE'S THE CODE def function(fragment, string): count = -1 last_m...
[ "You should use existing functionality, if possible:\n\"aabbccaabb\".count(\"aa\")\n\nThe count method does exactly what you want. The above example returns 2.\n", "You have two mistakes:\n\nString documentation states that find will return -1 if the fragment is not found\nThe last_match returns the index of the ...
[ 4, 1, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007117443_function_python.txt
Q: python multithreading question Can anyone tell me why this code generates queue after starting the threads? Basically, queue is generated after the for loop but in ThreadUrl class it already uses queue.get() method. How does this work? How can it get the values from a queue that is not yet generated? for i in rang...
python multithreading question
Can anyone tell me why this code generates queue after starting the threads? Basically, queue is generated after the for loop but in ThreadUrl class it already uses queue.get() method. How does this work? How can it get the values from a queue that is not yet generated? for i in range(5): t = ThreadUrl(queue, out_q...
[ "Line host = self.queue.get() blocks executing thread until some element appear in the queue. \nSo \n#spawn a pool of threads, and pass them queue instance\nfor i in range(5):\n t = ThreadUrl(queue, out_queue)\n t.setDaemon(True)\n t.start()\n\ncreates 5 threads that are waiting for any element in the queu...
[ 6 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007117555_multithreading_python.txt
Q: Python site crawler, saving files with Scrapy I'm attempting to write a crawler that will take a certain search entry and saving a whole bunch of .CSV files correlated to the results. I already have the spider logging in, parsing all the html data I need, and now all I have left to do is figure out how I can save ...
Python site crawler, saving files with Scrapy
I'm attempting to write a crawler that will take a certain search entry and saving a whole bunch of .CSV files correlated to the results. I already have the spider logging in, parsing all the html data I need, and now all I have left to do is figure out how I can save the files I need. So the search returns links such...
[ "If you crawled the link to the CSV files you can simply download them with wget, which is able to login to a page too.\nYou either specify the --http-user and --http-passwd, or you use cookies as follows:\n$ wget --cookies=on --keep-session-cookies --save-cookies=cookie.txt --post-data \"login=USERNAME&password=PA...
[ 1 ]
[]
[]
[ "jsp", "python", "scrapy", "web_crawler" ]
stackoverflow_0007116849_jsp_python_scrapy_web_crawler.txt
Q: guitar tab to uke tab program help so i made this program where it take a guitar tab and gets the fret number and runs it through a dictionary which gets the note and searches for it in the uke note dictionary. but my probleme is if i have a tab in a txt file ex: |-----11----------11----------11------11--13--11---...
guitar tab to uke tab program help
so i made this program where it take a guitar tab and gets the fret number and runs it through a dictionary which gets the note and searches for it in the uke note dictionary. but my probleme is if i have a tab in a txt file ex: |-----11----------11----------11------11--13--11----------11----------11----------11------1...
[ "For the parsing, write a function that takes a line of tabs and a note, that yields the frets along with the position:\nimport re\n\ndef parse_line(line, note):\n fret_pattern = re.compile(r'\\d+')\n for match in fret_pattern.finditer(line):\n yield (match.start(), ''.join((note, match.group(0))))\n\n...
[ 3, 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007117515_file_python.txt
Q: How to install lxml into virtualenv from the local system? There is lxml module installed on my system (debian package python-lxml, for python 2.6), also I'm using virtualenv based on python2.6, installed with flag --no-site-packages. Is it possible to install lxml inside virtual environment without compilation us...
How to install lxml into virtualenv from the local system?
There is lxml module installed on my system (debian package python-lxml, for python 2.6), also I'm using virtualenv based on python2.6, installed with flag --no-site-packages. Is it possible to install lxml inside virtual environment without compilation using some standard tools (pip, easy_install etc) and already inst...
[ "You may create required symlinks automatically by bootstrap script.\n" ]
[ 3 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0007117361_python_virtualenv.txt
Q: tuple error on writing properties of a class as I am new to the stackoverflow community, I didnt know if I should post this as a new question or continuation of the question I asked here error with appending to a file and using an array. It's basically the same code from there only with an extra line: class c...
tuple error on writing properties of a class
as I am new to the stackoverflow community, I didnt know if I should post this as a new question or continuation of the question I asked here error with appending to a file and using an array. It's basically the same code from there only with an extra line: class component(object): def __init__(self, ...
[ "Argument *component is a tuple. Moreover you are passing to writeToFile a list of Components, while inside your method you are using passed argument as a Component.\nfor x in component:\n for c in x:\n line = \"width = %d\" % c.width\n self.lines.append(line)\n\n", "Your p...
[ 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0007117977_python_tuples.txt
Q: excel printing in to different column import xlrd import os path = "data" dirList=os.listdir(path) f = open('', 'w') f.write('') f.write("\n") for file in dirList: fullpath = os.path.join(path,file) if os.path.isfile(fullpath) == 1: wb = xlrd.open_workbook(fullpath) wb.sheet_names() ...
excel printing in to different column
import xlrd import os path = "data" dirList=os.listdir(path) f = open('', 'w') f.write('') f.write("\n") for file in dirList: fullpath = os.path.join(path,file) if os.path.isfile(fullpath) == 1: wb = xlrd.open_workbook(fullpath) wb.sheet_names() sh = wb.sheet_by_name(u'') for ...
[ "I think only a slight modification is required. You are putting a newline in between the x, y values that does not need to be there. This should produce rows with x, y. \n for j in range(21,sh.nrows):\n f.write(str(sh.cell(j,0).value))\n f.write(\", \")\n f.write(str(sh.cell(j,1).value))\n ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007117100_python_python_3.x.txt
Q: Which Python IDE Possible Duplicate: What IDE to use for Python? Hi recently started looking at Python, basically for scripting, so far I've been doing exercises from the web, which is OK. I'm using gEdit and its fine. but I'm curious to know what is a good IDE for python, that will still allow me to discover. O...
Which Python IDE
Possible Duplicate: What IDE to use for Python? Hi recently started looking at Python, basically for scripting, so far I've been doing exercises from the web, which is OK. I'm using gEdit and its fine. but I'm curious to know what is a good IDE for python, that will still allow me to discover. One of the things I'm ...
[ "You might want to try Vim or Eclipse.\n" ]
[ 1 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0007118813_ide_python.txt
Q: Splitting "admin.py" of a Django project? I'm trying to split admin.py of a Django project into separate files but failed. There's no information I can find from google about how to split it, so I have to try myself. Here's what I tried: make a directory named separated_admins and put an empty __init__.py in it c...
Splitting "admin.py" of a Django project?
I'm trying to split admin.py of a Django project into separate files but failed. There's no information I can find from google about how to split it, so I have to try myself. Here's what I tried: make a directory named separated_admins and put an empty __init__.py in it create files in separated_admins directory, some...
[ "The admin is just a python module. So the right way of splitting it would be as follows:\n\nCreate a folder called admin instead of admin.py\nUse multiple files within the admin folder, like your Some_Model_admin.py\nCreate a __init__.py in the admin folder and import * all the files into it.\nYou might also want ...
[ 17, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007118450_django_python.txt
Q: How to write smart card with pyscard I'm using reader/writer acr38f and my smart card is SLE4418. How do I read and write text to my smart card? For example: Hello World! apdu = [0XFF, 0X20,0x00,0x00,0x02, 0x00, 0x00] response, sw1, sw2 = cardservice.connection.transmit( apdu ) apdu = [0XFF,0xA4,0x00,0x00,0x01,0x...
How to write smart card with pyscard
I'm using reader/writer acr38f and my smart card is SLE4418. How do I read and write text to my smart card? For example: Hello World! apdu = [0XFF, 0X20,0x00,0x00,0x02, 0x00, 0x00] response, sw1, sw2 = cardservice.connection.transmit( apdu ) apdu = [0XFF,0xA4,0x00,0x00,0x01,0x05] response, sw1, sw2 = cardservice.conne...
[ "I do not have the hardware to test this, but this should get you going:\nCommunicating with smart cards involves sending APDU (Smart Card application protocol data unit) commands and receiving APDU responses.\nCommand APDUs are sent through the reader/write (your ACR38F) and consists of a 4-byte header followed by...
[ 13 ]
[]
[]
[ "python", "smartcard" ]
stackoverflow_0006572979_python_smartcard.txt
Q: Maintaining a roll-backable flow of code in python without extreme identation I've encountered a situation where I'm working over a piece of code where I command changes on a remote object (that is one I can't duplicate to work over a clone), then ask the remote object for some operation in the new state and rever...
Maintaining a roll-backable flow of code in python without extreme identation
I've encountered a situation where I'm working over a piece of code where I command changes on a remote object (that is one I can't duplicate to work over a clone), then ask the remote object for some operation in the new state and revert all the changes I made to it by a sequence of opposite commands. The problem is t...
[ "Wouldn't Context Manager objects and the with statement improve the situation? Especially if you can use a version of Python where the with statement supports multiple context expressions, as 2.7 or 3.x. Here's an example:\nclass Action(object):\n def __init__(self, count):\n self.count = count\n def ...
[ 5 ]
[]
[]
[ "flatten", "python", "try_finally" ]
stackoverflow_0007119471_flatten_python_try_finally.txt
Q: is there any better way try a function many times in python? i want to exec a test function many times when it found a exception like this try: test() except: try: test() except: try: test() except Exception,e: logg...
is there any better way try a function many times in python?
i want to exec a test function many times when it found a exception like this try: test() except: try: test() except: try: test() except Exception,e: logger.info(e) this case will when i request a url and get the url re...
[ "for _ in range(5):\n try:\n test()\n except SomeError:\n pass\n else:\n break\nelse:\n #All tries failed, do something.\n logger.info(...)\n\n", "Try this:\nfor i in xrange(3):\n try:\n test()\n except Exception, e:\n if i == 3:\n # handle excepti...
[ 7, 1, 1, 1 ]
[]
[]
[ "python", "try_catch" ]
stackoverflow_0007119600_python_try_catch.txt
Q: How to use the classifier obtained by Pyml I am a new user of PyML in Python. Using the tutorial, I did the following: from PyML import * data = SparseDataSet("heart") s = SVM() s.train(data) r = s.cv(data,5) I got the resultset r, but I don't understand how to use this resultset to classify a totally new insta...
How to use the classifier obtained by Pyml
I am a new user of PyML in Python. Using the tutorial, I did the following: from PyML import * data = SparseDataSet("heart") s = SVM() s.train(data) r = s.cv(data,5) I got the resultset r, but I don't understand how to use this resultset to classify a totally new instance with Python. Can anyone more experienced hel...
[ "In r = s.sv(data,5) you are doing crossvalidation, which is used to measure classifier performance by training and testing 5 times on different parts of the dataset. This is not necessary when your objective is to classify new instances.\nTo classify new instances, you should preferably have these in a different d...
[ 1 ]
[]
[]
[ "dataset", "libsvm", "pyml", "python", "svm" ]
stackoverflow_0005811215_dataset_libsvm_pyml_python_svm.txt
Q: [Error]: Returned Object is not JSON Serializable How to serialize date time object? I am trying something like this. my_date_time = json.dumps(list_of_objects) list_of_objects variable is the response from raw query to MYSQL. Please suggest how to serialize the response having some datetime object in it. Thanks!...
[Error]: Returned Object is not JSON Serializable
How to serialize date time object? I am trying something like this. my_date_time = json.dumps(list_of_objects) list_of_objects variable is the response from raw query to MYSQL. Please suggest how to serialize the response having some datetime object in it. Thanks!
[ "thanks to all of you, finaly i have made the solution using CAST(expr AS type) method.\nThe CAST() function takes an expression of any type and produces a result value of a specified type \nSELECT name, CAST(date AS CHAR(10)) FROM table WHERE condition.\nthanx to Zack and Hennele Kormano. \n" ]
[ 2 ]
[]
[]
[ "django", "mysql", "python", "serialization" ]
stackoverflow_0007069701_django_mysql_python_serialization.txt
Q: In Python, how can I get the file system of a given file path In python, given a directory or file path like /usr/local, I need to get the file system where its available. In some systems it could be / (root) itself and in some others it could be /usr. I tried os.statvfs it doesnt help. Do I have to run the df c...
In Python, how can I get the file system of a given file path
In python, given a directory or file path like /usr/local, I need to get the file system where its available. In some systems it could be / (root) itself and in some others it could be /usr. I tried os.statvfs it doesnt help. Do I have to run the df command with the path name and extract the file system from the outp...
[ "Here is a slightly modified version of a recipe found here.\nos.path.realpath was added so symlinks are handled correctly.\nimport os\ndef getmount(path): \n path = os.path.realpath(os.path.abspath(path))\n while path != os.path.sep:\n if os.path.ismount(path):\n return path\n ...
[ 7, 4, 2 ]
[]
[]
[ "filepath", "filesystems", "python" ]
stackoverflow_0007119630_filepath_filesystems_python.txt
Q: PIL Image.fromstring from PyOpengl buffer has the wrong size I use PyOpenGL to draw a 2D Image. Then I want to use the Python Imaging Library (PIL) to store this image to disk. I use GLUT to display the image which works perfectly. But when I use PIL to store the image it extracts the wrong clipping. It has the wr...
PIL Image.fromstring from PyOpengl buffer has the wrong size
I use PyOpenGL to draw a 2D Image. Then I want to use the Python Imaging Library (PIL) to store this image to disk. I use GLUT to display the image which works perfectly. But when I use PIL to store the image it extracts the wrong clipping. It has the wrong size. Here is a minimal example which reproduces the effect an...
[ "I managed to solve my own Problem. \nFirst I tried the following solution which might also help people with related problems:\nsolution1\nBut then, through extensive trial and error, I found that the solution is much simpler. \nI simply had to swap two lines from:\nglutCreateWindow(\"Draw Polygons\")\nglutInitWind...
[ 1, 0 ]
[]
[]
[ "glut", "pyopengl", "python", "python_imaging_library" ]
stackoverflow_0007107707_glut_pyopengl_python_python_imaging_library.txt
Q: Does Python have decorators in the standard library? Apart from @staticmethod and @classmethod? Most languages have some basic libraries making use of most of the language features. It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt...
Does Python have decorators in the standard library?
Apart from @staticmethod and @classmethod? Most languages have some basic libraries making use of most of the language features. It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt python decorators which do them. Are there such things?
[ "property is usually used as a decorator. \nfunctools has several functions normally used as a decorator, such as total_ordering, update_wrapped, lru_cache, and wraps.\ncontextlib has the contextmanager decorator.\nKeep in mind, you can use any function as a decorator:\n@decorator\ndef function(): pass\n\nis just t...
[ 24, 10, 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0007120342_decorator_python.txt
Q: Skype python API Is there a skype web API or a python API that can be integrated into the Django APP. Server : Python 2.4, linux RHEL5 A: Yes there is. Look at: https://developer.skype.com/ And: http://sourceforge.net/projects/skype4py/ A: SkypeKit has a Python API, too and does not require the Skype client ru...
Skype python API
Is there a skype web API or a python API that can be integrated into the Django APP. Server : Python 2.4, linux RHEL5
[ "Yes there is.\nLook at: https://developer.skype.com/\nAnd: http://sourceforge.net/projects/skype4py/\n", "SkypeKit has a Python API, too and does not require the Skype client running. However, you do need a helper application - but on the skype developer website you can compile it for various architectures and o...
[ 2, 1 ]
[]
[]
[ "linux", "python", "skype", "web_applications" ]
stackoverflow_0007120806_linux_python_skype_web_applications.txt
Q: When does a webbrowser send If-Modified-Since? I'm serving a dynamically created recent.rss via python flask and naturally that way it is always sent via 200 OK. I was going to fix this by setting the header Expires a week into the future and checking if the browser sent If-Modified-Since. If so (after comparing d...
When does a webbrowser send If-Modified-Since?
I'm serving a dynamically created recent.rss via python flask and naturally that way it is always sent via 200 OK. I was going to fix this by setting the header Expires a week into the future and checking if the browser sent If-Modified-Since. If so (after comparing dates) I would just do return nothing, 304 instead of...
[ "RFC 2616 HTTP/1.1 has this note in 14.25 If-Modified-Since:\n\nWhen handling an If-Modified-Since header field, some\n servers will use an exact date comparison function, rather than a\n less-than function, for deciding whether to send a 304 (Not\n Modified) response. To get best results when ...
[ 12 ]
[]
[]
[ "browser", "flask", "if_modified_since", "python" ]
stackoverflow_0007120934_browser_flask_if_modified_since_python.txt
Q: (python) make a file that has a name of a variable and an extension I have a python code and i want it to make a file where it exports what the person wants(for a order). I want to export to a file never created but i want it to be named (the costumer's name).txt for example John Smith.txt if they said there name...
(python) make a file that has a name of a variable and an extension
I have a python code and i want it to make a file where it exports what the person wants(for a order). I want to export to a file never created but i want it to be named (the costumer's name).txt for example John Smith.txt if they said there name was john smith. My working code requires you to write your filename afte...
[ "If you're just looking to create a simple file from a variable with a fixed extension:\nmyVar=\"Joe Smart\"\n\nx = open (myVar+\".txt\", \"w\")\nx.write(\"hello\")\nx.close()\n\nCreates Joe Smart.txt in the current directory. You'd want to do better error checking than I did.\n", "You probably want to use someth...
[ 5, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007120998_file_python.txt
Q: SQLAlchemy bug? I'm not sure from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy.ext.declarative import declarative_base from bottle import route, post, get, request import os Base = decla...
SQLAlchemy bug? I'm not sure
from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy.ext.declarative import declarative_base from bottle import route, post, get, request import os Base = declarative_base() class User(Base): ...
[ "Very nice write up here about using SQLAlchemy and SQLite in this tutorial\nYou need to verify that you are on at least version 0.7 of SQLAlchemy\n>>> import sqlalchemy\n>>> sqlalchemy.__version__ \n0.7.0\n\nuse echo to display the SQL generated\n>>> from sqlalchemy import create_engine\n>>> engine = create_engine...
[ 3 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0004947434_python_sqlalchemy_sqlite.txt
Q: Retrieve text inside #{ } I have the following text: #{king} for a ##{day}, ##{fool} for a #{lifetime} And the following (broken) regex: [^#]#{[a-z]+} I want to match all #{words} but not the ##{words} (Doubling '#' acts like escaping) . Today I've noticed that the regex I have is ignoring the first word (refus...
Retrieve text inside #{ }
I have the following text: #{king} for a ##{day}, ##{fool} for a #{lifetime} And the following (broken) regex: [^#]#{[a-z]+} I want to match all #{words} but not the ##{words} (Doubling '#' acts like escaping) . Today I've noticed that the regex I have is ignoring the first word (refuses to match #{king}, but correc...
[ "You have to use a \"negative lookbehind assertion\", the correct regex would look like this:\nimport re\nt = \"#{king} for a ##{day}, ##{fool} for a #{lifetime}\"\nre.findall(r'(?<!#)#{([a-z]+)}', t)\n\nreturns\n['king', 'lifetime']\n\nExplanation:\nThe (?<!prefix)pattern expression matches pattern only if it's n...
[ 6, 2, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007121157_python_regex.txt
Q: How do I deserialise (deserialize) HTML fragments in JSON from simplejson.dumps? I'm working on a Django project where one of the front end guys has asked that, for one of our ajax request, he would like me to return a JSON dict, with one of the keys being some rendered HTML from a template. So, eg: d = { "hits...
How do I deserialise (deserialize) HTML fragments in JSON from simplejson.dumps?
I'm working on a Django project where one of the front end guys has asked that, for one of our ajax request, he would like me to return a JSON dict, with one of the keys being some rendered HTML from a template. So, eg: d = { "hits": 22, "page": 3, "somehhtml": """<div id='item1'>Something</div><div id='item2'>M...
[ "I don't understand why you need to unescape your json string, while it should be escaped to be a valid javascript and python string ?\nAnd by the way the newlines \\n don't have nothing to do with json dumper is just because the value of the key \"somehhtml\" is a multiline string that contain new lines (which i t...
[ 1 ]
[]
[]
[ "ajax", "django", "jquery", "json", "python" ]
stackoverflow_0007121039_ajax_django_jquery_json_python.txt
Q: wxPython: How to refresh and draw on wx.Frame from an unrelated class I have two classes in an application and the first is a wx class, which is instantiated as follows: if __name__ == '__main__': app = wx.App() ExampleFrame(None, 'Does Nothing') NewX = X(sys.argv) app.MainLoop() The class itself ...
wxPython: How to refresh and draw on wx.Frame from an unrelated class
I have two classes in an application and the first is a wx class, which is instantiated as follows: if __name__ == '__main__': app = wx.App() ExampleFrame(None, 'Does Nothing') NewX = X(sys.argv) app.MainLoop() The class itself looks like the following: class ExampleFrame(wx.Frame): def __init__(se...
[ "You can assign references of wx objects to variables and at that point you can access their functions like any other object:\nef = ExampleFrame(None, 'Something')\nNewX = X(sys.argv, ef)\n\nNow from within X, you'd need to store this reference so other methods can access it:\ndef __init__(self, argv, ef):\n # So...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007119755_python.txt
Q: Process() called from from Pylons creates a fork I'm trying to create a background process for some heavy calculations from the main Pylons process. Here's the code: p = Process(target = instance_process, \ args = (instance_tuple.instance, parent_pipe, child_pipe,)) p.start() The process i...
Process() called from from Pylons creates a fork
I'm trying to create a background process for some heavy calculations from the main Pylons process. Here's the code: p = Process(target = instance_process, \ args = (instance_tuple.instance, parent_pipe, child_pipe,)) p.start() The process is created and started, but is seems to be a fork from ...
[ "Process IS a fork. If you look through it's implementation you'll find that Process.start() calls a fork. It does NOT, however, call any of the exec variations to change the execution context.\nStill, this may have nothing to do with listening on the same port (unless the parent process is multi-threaded). At whic...
[ 1 ]
[]
[]
[ "multiprocessing", "pylons", "python" ]
stackoverflow_0007121279_multiprocessing_pylons_python.txt
Q: What steps do i need to take to start developing iPhone apps? Possible Duplicate: How to Start learning to create iphone apps I only know basic Python as far as programing languages go. What do I need to learn to start developing iPhone apps? I learned part python with almost only learnpythonthehardway.org and ...
What steps do i need to take to start developing iPhone apps?
Possible Duplicate: How to Start learning to create iphone apps I only know basic Python as far as programing languages go. What do I need to learn to start developing iPhone apps? I learned part python with almost only learnpythonthehardway.org and that wasn't too difficult. I am confident I can learn how to make ...
[ "Welcome to the wonderful world of programming. Seriously, as you've probably seen it can be a lot of fun. Starting young is the way to go!\niPhone development is going to be harder than learning the basics of Python, but not unachievable.\nOne of the problems that you are going to have, is that the tools are not ...
[ 1, 0 ]
[]
[]
[ "iphone", "python" ]
stackoverflow_0007121579_iphone_python.txt
Q: module name in sys.modules and globals() If I import a module, the module name shows up in both sys.modules and globals(). If I again delete it, it is removed from globals(), but still resides in sys.modules. Why is it so? import mymodule 'mymodule' in globals() # True 'mymodule' in sys.modules # True del mymodu...
module name in sys.modules and globals()
If I import a module, the module name shows up in both sys.modules and globals(). If I again delete it, it is removed from globals(), but still resides in sys.modules. Why is it so? import mymodule 'mymodule' in globals() # True 'mymodule' in sys.modules # True del mymodule 'mymodule' in globals() # False 'mymodule...
[ "Just like any other Python object, a module continues to exist until there are no more references to it. In other words, sys.modules behaves like a regular dict, and\nimport mymodule\nlst = {mymodule.__name__: mymodule}\n'mymodule' in globals() # True\n'mymodule' in lst # True\ndel mymodule\n'mymodule' i...
[ 4, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007121802_python.txt
Q: inconsistency of redirecting sys.stderr in IPython and console Redirecting sys.stderr to a text file in IPython and console(Gnome terminal) yields different results. f=open('std.log','w') sys.stderr=f raise Exception,"message goes here" In IPython, the error message is printed directed into the screen. In [13]: r...
inconsistency of redirecting sys.stderr in IPython and console
Redirecting sys.stderr to a text file in IPython and console(Gnome terminal) yields different results. f=open('std.log','w') sys.stderr=f raise Exception,"message goes here" In IPython, the error message is printed directed into the screen. In [13]: run std.py ---------------------------------------------------------...
[ "The problem is not writing to stderr, but IPython's run command intercepting exceptions. When the program raises an unhandled exception, IPython will print the backtrace to its own console, plus an additional warning (WARNING: Failure executing file). This is done by installing an exception hook function as sys....
[ 2 ]
[]
[]
[ "console", "ipython", "python", "redirect", "stderr" ]
stackoverflow_0007118660_console_ipython_python_redirect_stderr.txt
Q: How to do dynamic creation of per-process queues in Python multiprocessing I want to dynamically create multiple Processes, where each instance has a queue for incoming messages from other instances, and each instance can also create new instances. So we end up with a network of processes all sending to each other...
How to do dynamic creation of per-process queues in Python multiprocessing
I want to dynamically create multiple Processes, where each instance has a queue for incoming messages from other instances, and each instance can also create new instances. So we end up with a network of processes all sending to each other. Every instance is allowed to send to every other. The code below would do wha...
[ "I'm not entirely sure what your use case actually is here. Perhaps if you elaborate a bit more on why you want to have each process dynamically spawn a child with a connected queue it'll be a bit more clear what the right solution would be in this situation.\nAnyway, with the question as is it seems that there is...
[ 3, 3, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007072875_multiprocessing_python.txt
Q: python iterate over the two lists while comparing items i have two lists eg x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10], i want to iterate over the two lists while comparing items. For those that match, i would like to call some function and remove them from the lists, in this example i should end up with x= [1...
python iterate over the two lists while comparing items
i have two lists eg x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10], i want to iterate over the two lists while comparing items. For those that match, i would like to call some function and remove them from the lists, in this example i should end up with x= [1,2] and y = [8,9,10]. Sets will not work for this problem bec...
[ "Edit: After discovering the person asking the question simply didn't know about __hash__ I provided this information in a comment:\n\nTo use sets, implement __hash__. So if obj1 == obj2 when obj1.a == obj2.a and ob1.b == obj2.b, __hash__ should be return hash((self.a, self.b)) and your sets will work as expected.\...
[ 4, 3, 1 ]
[ "how about this:\nimport itertools\nx = [1,2,3,4,4,5,6,7,7] \ny = [3,4,5,6,7,8,9,10]\noutput = map(somefunction, itertools.product(x,y))\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0007122282_list_python.txt
Q: updating python-elementtree to overcome xpath selector issue I'm getting an error when searching for the attribute of a node in my xml using ElementTree. expected path separator ([) The source code is: home_team_node = game_node.find( "team/team-metadata[@alignment='home']" ) This discussion on Stackoverflow lea...
updating python-elementtree to overcome xpath selector issue
I'm getting an error when searching for the attribute of a node in my xml using ElementTree. expected path separator ([) The source code is: home_team_node = game_node.find( "team/team-metadata[@alignment='home']" ) This discussion on Stackoverflow leads me to conclude I need a newer version of ElementTree. ElementTr...
[ "lxml is a very useful library for parsing XML, and it has a complete implementation of the ElementTree API. Try installing it with:\nsudo apt-get install python-lxml\n\nYou'll then need to change your import statments to use the lxml version instead of the bundled elementree.\n(I would resist using pip or easy_i...
[ 4, 0 ]
[]
[]
[ "apt", "aptitude", "package", "python" ]
stackoverflow_0007122461_apt_aptitude_package_python.txt
Q: Rotation of patches in matplotlib not functioning as expected I am trying to overlay a rotated rectangle onto a matplotlib chart. I have the following code: fig = Figure((3.8, 3.4)) subp = fig.add_subplot(111) fig.axes[0].set_autoscale_on(False) fig.axes[0].set_ylim([float(self.getConfig('GUI'...
Rotation of patches in matplotlib not functioning as expected
I am trying to overlay a rotated rectangle onto a matplotlib chart. I have the following code: fig = Figure((3.8, 3.4)) subp = fig.add_subplot(111) fig.axes[0].set_autoscale_on(False) fig.axes[0].set_ylim([float(self.getConfig('GUI', 'chartmin', '-1')),float(self.getConfig('GUI', 'chartmax','4' ))]...
[ "By default, rotations are defined with respect to the origin. You don't want to rotate the blue rectangle around the origin, but around its center point. This is the same as first translating it so that its center lies on the origin, performing the rotation, then translating it back.\nFortunately, matplotlib has...
[ 6 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007122268_matplotlib_python.txt
Q: wxPython: how to lay one panel over another This is about wxPython. I would like to have 2 Panels laying one over the other: PanelBG should be some sort of a "background", with its own GridBagSizer with subPanels, StaticTexts and so on; PanelFG should be the "foreground" panel, also with its own GridBagSizer with ...
wxPython: how to lay one panel over another
This is about wxPython. I would like to have 2 Panels laying one over the other: PanelBG should be some sort of a "background", with its own GridBagSizer with subPanels, StaticTexts and so on; PanelFG should be the "foreground" panel, also with its own GridBagSizer with some StaticTexts, Buttons... but a transparent ba...
[ "This would be at least partially a change of direction, but it might be worth examining what other rendering options you have. \nIn particular, I'm thinking of wxWebKit (http://wxwebkit.kosoftworks.com/), which would let you do layering, etc. using the WebKit browser rendering engine. I'm not sure whether it's at ...
[ 1, 0 ]
[]
[]
[ "panel", "python", "sizer", "wxpython", "wxwidgets" ]
stackoverflow_0007113605_panel_python_sizer_wxpython_wxwidgets.txt
Q: documentations about how __init__.py works? I stumbled over the import of __init__.py in python packages. See posts: different import results at different directories how to reload a Class in python shell? I was directed by Nate to very good explanations at this post: Adding code to __init__.py. I want to read...
documentations about how __init__.py works?
I stumbled over the import of __init__.py in python packages. See posts: different import results at different directories how to reload a Class in python shell? I was directed by Nate to very good explanations at this post: Adding code to __init__.py. I want to read more about this topic and more related topics. C...
[ "Start here: \nPython provides some acceptable tutorials which lead you to a basic understanding how the concepts of the language work.\nThis http://docs.python.org/tutorial/modules.html describes how modules and their initializers work.\nIn addition to that - if you want it the most formal way and can't get along ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006953162_python.txt
Q: self.request.form not iterable? Hello I am making a form in HTML and python and I am having a problem with processing the arguments the problem comes in this section <form method="POST"> <input type="checkbox" name="brands" value="1" /> <input type="checkbox" name="brands" value="2" /> </form> and in the pyth...
self.request.form not iterable?
Hello I am making a form in HTML and python and I am having a problem with processing the arguments the problem comes in this section <form method="POST"> <input type="checkbox" name="brands" value="1" /> <input type="checkbox" name="brands" value="2" /> </form> and in the python I am using a self.request.form obj...
[ "I found you can retrieve a list of the same named inputs using this syntax\nself.request.form.getlist('brands')\n\n" ]
[ 1 ]
[]
[]
[ "forms", "python", "werkzeug" ]
stackoverflow_0007113388_forms_python_werkzeug.txt
Q: How to locate the file a code object come from? I need to know where a code object comes from ; its module. So I (naively) tried : os.path.abspath(code.co_filename) But that may or may not work, (I think it's because abspath depends on cwd) Any way to get the full path of a code object's module ? EDIT : The...
How to locate the file a code object come from?
I need to know where a code object comes from ; its module. So I (naively) tried : os.path.abspath(code.co_filename) But that may or may not work, (I think it's because abspath depends on cwd) Any way to get the full path of a code object's module ? EDIT : The functions from the inspect module : getfile, getsour...
[ "import inspect\nprint inspect.getfile(inspect)\n\n", "The inspect.getsourcefile() function is what you need, it returns the relative path to the file where the object's source can be found.\n", "If you have access to the module, try module.__file__.\n>>> import xml\n>>> xml.__file__\n'/usr/local/lib/python2.6/...
[ 3, 1, 0 ]
[]
[]
[ "inspect", "python" ]
stackoverflow_0007123233_inspect_python.txt
Q: Plotting values versus strings in matplotlib? I am trying to create a plot in matplotlib where the x-values are integers and the y-values are strings. Is it possible to plot data of this type in matplotlib? I examined the documentation and the gallery for matplotlib and could not find any examples of this type. I ...
Plotting values versus strings in matplotlib?
I am trying to create a plot in matplotlib where the x-values are integers and the y-values are strings. Is it possible to plot data of this type in matplotlib? I examined the documentation and the gallery for matplotlib and could not find any examples of this type. I have many lists bound to a variable called my_lists...
[ "You could probably do something like this, where you give each y \"string\" a unique index value. You may have to fiddle with the spacing for i. Ie. i*2 instead of i to make things look nice. After that you set the tick label for each of those indexes to its corresponding string.\nimport matplotlib.pyplot as pl...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007122879_matplotlib_python.txt
Q: What is :: (double colon) in numpy like in myarray[0::3]? Possible Duplicate: What is :: (double colon) in Python? I read the question What is :: (double colon) in Python when subscripting sequences?, but this not answer what myarray[x::y] mean. A: It prints every yth element from the list / array >>> a = [1,2...
What is :: (double colon) in numpy like in myarray[0::3]?
Possible Duplicate: What is :: (double colon) in Python? I read the question What is :: (double colon) in Python when subscripting sequences?, but this not answer what myarray[x::y] mean.
[ "It prints every yth element from the list / array\n>>> a = [1,2,3,4,5,6,7,8,9]\n>>> a[::3]\n[1, 4, 7]\n\nThe additional syntax of a[x::y] means get every yth element starting at position x\nie.\n>>> a[2::3]\n[3, 6, 9]\n\n" ]
[ 87 ]
[]
[]
[ "numpy", "python", "slice", "syntax" ]
stackoverflow_0007123888_numpy_python_slice_syntax.txt
Q: django-haystack problem when saving query in session I want to save the user input in my view, I don't know how to do it redefining the searchview so I did this: request.session['q']=request.GET.get('q') from haystack.views import SearchView search_view = SearchView(template = template_name) return search_...
django-haystack problem when saving query in session
I want to save the user input in my view, I don't know how to do it redefining the searchview so I did this: request.session['q']=request.GET.get('q') from haystack.views import SearchView search_view = SearchView(template = template_name) return search_view(request) but I got this error: Traceback (most rec...
[ "Finally I found the problem. In another view I was saving in the session the result of a SerchQuerySet, but the problem didn't raised at the time I've put the content but it raised when I've put other thing in the session. This was very difficult to find out.\n" ]
[ 0 ]
[]
[]
[ "django", "django_haystack", "python", "session_variables" ]
stackoverflow_0007095060_django_django_haystack_python_session_variables.txt
Q: What is the proper way to make class data inheritable in python? I'm new-ish to Python and coming from the Perl universe. I'm trying to determine what the best practice is regarding the storage and access to class data so that it can be inherited and potentially extended by a subclass. Reading the Python 2.7 docs ...
What is the proper way to make class data inheritable in python?
I'm new-ish to Python and coming from the Perl universe. I'm trying to determine what the best practice is regarding the storage and access to class data so that it can be inherited and potentially extended by a subclass. Reading the Python 2.7 docs (I'm stuck using 2.6 really), Dive In to Python and past questions her...
[ "Just so you know, using an mutable object like a dict as a default argument or outside of something like an __init__ method may not behave the way that you think it will.\nAs a simple example:\nclass A(object):\n a = {'foo':1}\n\na = A()\na.a['bar'] = 2\n\nb = A()\nprint b.a\n\nSo now, b.a is {'foo': 1, 'bar': ...
[ 2, 2 ]
[]
[]
[ "class", "inheritance", "oop", "python" ]
stackoverflow_0007123638_class_inheritance_oop_python.txt
Q: Graphics folder modules will not import after several installs (Mac OSX) A similar problem with the python gdal module Gdal will not import after several installs (Mac OSX) was solved by modifying my shell profile to ensure MacPorts-installed ports are found, and then using sudo port select python python27. But th...
Graphics folder modules will not import after several installs (Mac OSX)
A similar problem with the python gdal module Gdal will not import after several installs (Mac OSX) was solved by modifying my shell profile to ensure MacPorts-installed ports are found, and then using sudo port select python python27. But this time it's every module in my graphics folder that deals with tiff and png r...
[ "For most Python packages, MacPorts has separate ports available for each supported Python version. For example, if you are trying to use PIL (the Python Imaging Library), you need to install the 2.7 version of that port:\nsudo port install py27-pil\n\nThat will also install the MacPorts version of Python 2.7, if ...
[ 1 ]
[]
[]
[ "png", "python", "tiff" ]
stackoverflow_0007110885_png_python_tiff.txt
Q: Why does this simple usage of Python's subprocess hang? import subprocess proc1 = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc2 = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc1.stdin.close() proc1.wait() When running this on Debian with Python 2.6...
Why does this simple usage of Python's subprocess hang?
import subprocess proc1 = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc2 = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc1.stdin.close() proc1.wait() When running this on Debian with Python 2.6.6, the program never exits. The strange thing is when I chan...
[ "Try typing \"cat\" with no arguments in a terminal. \"cat\" requires something to concatenate to the stdout.\n>>> from subprocess import Popen, PIPE\n>>> args = [\"cat\", \"foobar\"]\n>>> reply = Popen(args, stdout=PIPE).communicate()[0]\n>>> print (reply)\nline 0\nline 1\nline 2\n\n>>>\n\nDocs have a pretty good ...
[ 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007124157_python_subprocess.txt
Q: django: is there a black magic on extra fields on many-to-many relationships? It's from Django's official doc: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships The models are like: class Person(models.Model): name = models.CharField(max_length=128) def __u...
django: is there a black magic on extra fields on many-to-many relationships?
It's from Django's official doc: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships The models are like: class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = mod...
[ "Its not a magic of ManyToMany fields; its a universal one of the django ORM with foreign key (including ManyToMany) relations.\nE.g., if you have\nclass Musician(models.Model):\n name = models.CharField(max_length=128)\n band = models.ForeignKey(\"Band\")\n\nclass Band(models.Model):\n name = models.CharF...
[ 2, 1 ]
[]
[]
[ "django", "many_to_many", "python" ]
stackoverflow_0007124235_django_many_to_many_python.txt
Q: Is there an option to print the output of help()? Is there an option to print the output of help('myfun'). The behaviour I'm seeing is that output is printed to std.out and the script waits for user input (i.e. type 'q' to continue). There must be a setting to set this to just dump docstrings. Alternatively, if I ...
Is there an option to print the output of help()?
Is there an option to print the output of help('myfun'). The behaviour I'm seeing is that output is printed to std.out and the script waits for user input (i.e. type 'q' to continue). There must be a setting to set this to just dump docstrings. Alternatively, if I could just dump the docstring PLUS the "def f(args):" l...
[ "To get exactly the help that's printed by help(str) into the variable strhelp:\nimport pydoc\nstrhelp = pydoc.render_doc(str, \"Help on %s\")\n\nOf course you can then easily print it without paging, etc.\n", "If you want to access the raw docstring from code:\n myvar = obj.__doc__\n print(obj.__doc__)\n\nTh...
[ 26, 5, 5, 2 ]
[]
[]
[ "docstring", "pydoc", "python" ]
stackoverflow_0007123660_docstring_pydoc_python.txt
Q: KeyErrors while generating a dict Below is the list of dict using trying to generate dict data = [ {'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8}, {'date': datetime.date(2011, 8, 15), 'name': u'ab', 'total': 8}, {'date': datetime.date(2011, 8, 16), 'name': u'ab', 'total': 8}, {'date': da...
KeyErrors while generating a dict
Below is the list of dict using trying to generate dict data = [ {'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8}, {'date': datetime.date(2011, 8, 15), 'name': u'ab', 'total': 8}, {'date': datetime.date(2011, 8, 16), 'name': u'ab', 'total': 8}, {'date': datetime.date(2011, 8, 17), 'name': u'ab'...
[ "Why shouldn't you get a KeyError? You're asking for the value associated with type from the first row of data and there's no such key.\nEDIT:\n@agf says this is underhelpful, so let me try again.\nThe first line of data is\n{'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8}\n\nin the loop fetch (btw,...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007124297_python.txt
Q: Using NLTK Library in Iron Python I am trying to use NLTK library and importing it using Iron Python. I am not able to get that done and an error is reported saying that the library is not found. Please do let me know what could be the problem. I am a beginner in python and looking to use NLTK with Iron Python and...
Using NLTK Library in Iron Python
I am trying to use NLTK library and importing it using Iron Python. I am not able to get that done and an error is reported saying that the library is not found. Please do let me know what could be the problem. I am a beginner in python and looking to use NLTK with Iron Python and C#. I have NLTK libraries installed us...
[ "Maybe this issue in the codeplex of ironpython can help you.\n" ]
[ 0 ]
[]
[]
[ "iron", "nltk", "python" ]
stackoverflow_0007124807_iron_nltk_python.txt
Q: How to prevent a for loop from advancing in Python? Is it possible to prevent the for loop from proceeding to the next value in the list/iterator if a certain condition is satisfied? lst = list('abcde') for alphabet in lst: if some_condition: # somehow prevent the for loop from advancing so that in the ...
How to prevent a for loop from advancing in Python?
Is it possible to prevent the for loop from proceeding to the next value in the list/iterator if a certain condition is satisfied? lst = list('abcde') for alphabet in lst: if some_condition: # somehow prevent the for loop from advancing so that in the # next iteration, the value of alphabet remains the same...
[ "What you seem to want is a nested while loop. Only when the while loop exits will the for loop continue to the next value.\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nfor letter in alphabet:\n while some_condition:\n # do something\n\n", "You can use break to exit the loop immediately, or continue to skip t...
[ 8, 4, 2, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0007124733_for_loop_python.txt
Q: Python syntax error When I run this code in python, it is giving me a syntax error and highlighting the "l" in the line that I have pointed out. Why is it doing this? from Euler import primeSieve,sumDig def powerSieve(n): powers = [] primes = primeSieve(100) for i in primes: j = 2 whil...
Python syntax error
When I run this code in python, it is giving me a syntax error and highlighting the "l" in the line that I have pointed out. Why is it doing this? from Euler import primeSieve,sumDig def powerSieve(n): powers = [] primes = primeSieve(100) for i in primes: j = 2 while i ** j <= n: ...
[ "You're missing a close bracket on the line before. Change this:\nif l * (i ** j) >= 10: powers.append(l * (i ** j)\n\nTo this:\nif l * (i ** j) >= 10: powers.append(l * (i ** j))\n\n", "You forgot to close the brackets on the preceding line. It should be:\npowers.append(l * (i ** j))\n\n", "You have an if stat...
[ 2, 0, 0 ]
[]
[]
[ "new_operator", "operators", "python", "syntax" ]
stackoverflow_0007124919_new_operator_operators_python_syntax.txt
Q: python-ldap OS X 10.6 and Python 2.6 Trying to install python-ldap for my Django project -- so far tried easy_install, pip, as well as building myself, but still getting the same errors: dlopen(/Library/Python/2.6/site-packages/_ldap.so, 2): Symbol not found: _ldap_create_assertion_control_value Referenced from: /...
python-ldap OS X 10.6 and Python 2.6
Trying to install python-ldap for my Django project -- so far tried easy_install, pip, as well as building myself, but still getting the same errors: dlopen(/Library/Python/2.6/site-packages/_ldap.so, 2): Symbol not found: _ldap_create_assertion_control_value Referenced from: /Library/Python/2.6/site-packages/_ldap.so ...
[ "pip install python-ldap==2.3.13 did the trick for me (Mac OS X 10.6)\n", "The problem and solution are documented here.\nSummary: The 10.7.{0,1} system tools and headers are all from OpenLDAP 2.4.x while the libraries are from OpenLDAP 2.2.0. The solution is to build the OpenLDAP libs to match the system headers...
[ 7, 7, 2, 1 ]
[]
[]
[ "django", "python", "python_ldap" ]
stackoverflow_0006475118_django_python_python_ldap.txt
Q: A complex ordering algorithm for a Python list? I need to order a list of comments so they appear in their threaded order. Each comment has a: Top parent comment (for queries) Parent comment Indentation level If I'm fetching the comments as a list, what would be the most efficient way of sorting it so each comme...
A complex ordering algorithm for a Python list?
I need to order a list of comments so they appear in their threaded order. Each comment has a: Top parent comment (for queries) Parent comment Indentation level If I'm fetching the comments as a list, what would be the most efficient way of sorting it so each comment is below its parent? It has to remain as a 1-dimen...
[ "So... you've got something like this?\nclass Comment(object):\n all_comments = []\n\n def __init__(self, message, parent):\n self.message = message\n self.parent = parent\n self.all_comments.append(self)\n\n def __iter__(self):\n \"\"\"\n Yields tuples of (indentation le...
[ 1, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0007125082_list_python_sorting.txt
Q: proper names for the constant values while using matplotlib, Being a newbie to using matplotlib ,I was trying out some code ,from examples I found on the net.I was using a lot of constants to adjust the dimensions of the plot elements.I found that I am at a loss ,when it came to naming the constants properly. for ...
proper names for the constant values while using matplotlib,
Being a newbie to using matplotlib ,I was trying out some code ,from examples I found on the net.I was using a lot of constants to adjust the dimensions of the plot elements.I found that I am at a loss ,when it came to naming the constants properly. for example when creating a bar chart from a pair of x_list and y_list...
[ "First, I find that plotting figures is generally a messy business and often my code just does not look nice. It has become better over the years but in the end, to get a production-grade plot there will always be hand tweaking. And this will include many constants which probably don't have 'proper' names, like t...
[ 2 ]
[]
[]
[ "constants", "matplotlib", "naming", "python" ]
stackoverflow_0007124747_constants_matplotlib_naming_python.txt
Q: Appending various strings between two delimeters in one string. python I've been stuck here a day. So I thought to ask the experts. I am reading contents from a file which has data in form |something| |something else| |something_1 something_2 someting_3| |something blah blah| .. and so on.. so as you guys figur...
Appending various strings between two delimeters in one string. python
I've been stuck here a day. So I thought to ask the experts. I am reading contents from a file which has data in form |something| |something else| |something_1 something_2 someting_3| |something blah blah| .. and so on.. so as you guys figured it out.. the delimiter is '|' now.. I want the output in following form |...
[ "import re\nprint re.findall(r\"\\|[^|]*\\|\", text)\n\nIf you haven't seen this before, its a regular expression. Basically you describe a pattern in text that you are looking for. I recommend reading up on it if you don't know them.\n", "I think you're making this too complicated for yourself. The way you've de...
[ 1, 0 ]
[]
[]
[ "delimiter", "python", "string" ]
stackoverflow_0007125400_delimiter_python_string.txt
Q: MongoDB insert speed trade-offs In short: There is a huge difference in insert speeds when I keep a JSON object with many fields in a single, string field of MongoDB, or keep each field of the JSON object in its own MongoDB field. 1) Is this difference normal? 2) Are these insertion speeds typical? I have many rec...
MongoDB insert speed trade-offs
In short: There is a huge difference in insert speeds when I keep a JSON object with many fields in a single, string field of MongoDB, or keep each field of the JSON object in its own MongoDB field. 1) Is this difference normal? 2) Are these insertion speeds typical? I have many records each with a unique string id and...
[ "If possible, enable the C extensions, as they will provide a significant performance improvement. I think the difference in speed is due to the larger number of keys that must be serialized (by pure-Python code, since you have the extensions disabled) into the BSON document. With the C extensions enabled, this wil...
[ 3 ]
[]
[]
[ "bson", "json", "mongodb", "python" ]
stackoverflow_0007124319_bson_json_mongodb_python.txt
Q: Python with statements I'm experimenting with Python's with statements, and I've found that in the following code listing my __init__ method gets called twice, while my __exit__ method gets called once. This presumably means that there will be a resource leak if this code did anything useful. class MyResource: ...
Python with statements
I'm experimenting with Python's with statements, and I've found that in the following code listing my __init__ method gets called twice, while my __exit__ method gets called once. This presumably means that there will be a resource leak if this code did anything useful. class MyResource: def __enter__(self): ...
[ "You shouldn't return a new instance from __enter__. Instead, return self (the instance for which __enter__ is being called. That's why __init__() is called twice -- you call it twice, once in your with statement, once in __enter__(). Here's a correct version:\ndef __enter__(self):\n print 'Entering MyResource'\...
[ 20, 6, 3, 2 ]
[]
[]
[ "python", "raii", "with_statement" ]
stackoverflow_0007125727_python_raii_with_statement.txt
Q: Tkinter: Updating Labels mid-loop I would like to update a Label in my GUI to be a sort of progress bar, display how complete a data transfer is. Everywhere I look, people say to use the textvariable option of Label and then to set the string and the label updates. This does not work for me. The label updates at...
Tkinter: Updating Labels mid-loop
I would like to update a Label in my GUI to be a sort of progress bar, display how complete a data transfer is. Everywhere I look, people say to use the textvariable option of Label and then to set the string and the label updates. This does not work for me. The label updates at the end of the data collection loop. I...
[ "Short answer is to call update_idletasks. This works because widget updating is handled as an idle task. These normally get executed by the event loop but you can cause them to be called vial update_idletasks.\nFor a little more background, see the answers to the question How do widgets update in Tkinter?, or just...
[ 5 ]
[]
[]
[ "python", "tkinter", "while_loop" ]
stackoverflow_0007125398_python_tkinter_while_loop.txt
Q: python matrix multiplication: how to handle very large matrices? a = numpy.zeros((17770,5)) b = numpy.zeros((5,20000)) ma = numpy.matrix(a) mb = numpy.matrix(b) That is, ma.shape = (17770,5), mb.shape = (5,20000), both are numpy.matrix. I need ma*mb. But I get the error message "ValueError: array is too big". ...
python matrix multiplication: how to handle very large matrices?
a = numpy.zeros((17770,5)) b = numpy.zeros((5,20000)) ma = numpy.matrix(a) mb = numpy.matrix(b) That is, ma.shape = (17770,5), mb.shape = (5,20000), both are numpy.matrix. I need ma*mb. But I get the error message "ValueError: array is too big". Are these matrices too large for Python multiplication? BTW, I tested ...
[ "I can compute ma*mb on my machine (Python 2.7.1 |EPD 7.0-2 (64-bit) on 64-bit Ubuntu).\nMake sure you're using 64-bit Python on a 64-bit OS since a 17770x20000 matrix of double-precision floats requires 2.8GB of RAM, which exceeds (or is very close to) what most 32-bit platforms can handle.\nDepending on your requ...
[ 5 ]
[]
[]
[ "matrix_multiplication", "numpy", "python" ]
stackoverflow_0007126004_matrix_multiplication_numpy_python.txt
Q: Python/Pyside: Create Image Histogram What is the most effective way to create an image (QImage) histogram in PySide? My test image is 1,9MB, 3648x2736px, jpeg photo I tried two ways: 1. import time start = time.time() for y in range(h): line = img.scanLine(y) # img - instance of QImage for x in range(w)...
Python/Pyside: Create Image Histogram
What is the most effective way to create an image (QImage) histogram in PySide? My test image is 1,9MB, 3648x2736px, jpeg photo I tried two ways: 1. import time start = time.time() for y in range(h): line = img.scanLine(y) # img - instance of QImage for x in range(w): color = struct.unpack('I', line[x...
[ "Another approach you might try is getting the image data into a numpy array (hopefully possible reasonably efficiently) and using numpy.histogram.\n" ]
[ 0 ]
[]
[]
[ "histogram", "pyside", "python" ]
stackoverflow_0007123669_histogram_pyside_python.txt
Q: Python Multiple Inheritance/Mixin I have the following problem: class A: animal = 'gerbil' def __init__(self): self.result = self.calculate_animal() def calculate_animal(self): print(self.animal) return self.animal class B(A): animal = 'zebra' def __init__(self): ...
Python Multiple Inheritance/Mixin
I have the following problem: class A: animal = 'gerbil' def __init__(self): self.result = self.calculate_animal() def calculate_animal(self): print(self.animal) return self.animal class B(A): animal = 'zebra' def __init__(self): super(B, self).__init__() Now, I ...
[ "The order of the parent classes is important, you should do it like so: \nclass C(CapitalizeAnimal, A):\n animal = 'puma'\n\n def __init__(self):\n super(C, self).__init__()\n\nMore info can be found by reading about the MRO (Method Resolution Order).\n\nAlso, super only works with new style classe...
[ 5, 0 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0007126376_multiple_inheritance_python.txt
Q: Python: Indentation Error My younger cousin somehow got hold of a python book and has been trying to learn Python. He's asked me for help. But I'm having trouble doing that. He is using IDLE and he reports that he gets this error: Error: Inconsistent indentation detected! 1) Your indentati...
Python: Indentation Error
My younger cousin somehow got hold of a python book and has been trying to learn Python. He's asked me for help. But I'm having trouble doing that. He is using IDLE and he reports that he gets this error: Error: Inconsistent indentation detected! 1) Your indentation is outright incorrect (easy ...
[ "with open('problem_script.py','r') as f:\n content = f.read()\n print(repr(content))\n\nChances are good there are hidden invisible characters in his file. Using the program above will help him find them.\n", "Perhaps this is a Windows/Unix line ending issue. Are you exchanging the python code between two ...
[ 5, 1 ]
[]
[]
[ "indentation", "python", "python_idle" ]
stackoverflow_0007126474_indentation_python_python_idle.txt
Q: Free JSON Parser (python) I have a file that JSON statements that look like this 20110812 09:00:00:012000 INFO - #JSON{"name": "YMean", "args": {"timestamp": "1313157600012", "YMean": "[15770.064851138422] . I need a python parser that will parse a whole file that consists of this kind of JSON statements.Any sugg...
Free JSON Parser (python)
I have a file that JSON statements that look like this 20110812 09:00:00:012000 INFO - #JSON{"name": "YMean", "args": {"timestamp": "1313157600012", "YMean": "[15770.064851138422] . I need a python parser that will parse a whole file that consists of this kind of JSON statements.Any suggests what would be most useful ...
[ "Your best bet possibly is the official Python JSON-library. Take a look at the docs to see how you can parse your JSON-data, it is very well documented.\n", ">>> import json\n>>> corpus = '''20110812 09:00:00:012000 INFO - #JSON{\"name\": \"YMean\", \"args\": {\"timestamp\": \"1313157600012\", \"YMean\": \"[1577...
[ 3, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007125849_json_python.txt
Q: String formatting in python Recently I've been doing a lot of music based programming, and as such find myself doing this kind of thing a lot to deal with missing metadata in some songs: default = {'title': 'Unknown title', 'artist': 'unknown Artist'} default.update(song) print '{title} - {artist}'.format(**defaul...
String formatting in python
Recently I've been doing a lot of music based programming, and as such find myself doing this kind of thing a lot to deal with missing metadata in some songs: default = {'title': 'Unknown title', 'artist': 'unknown Artist'} default.update(song) print '{title} - {artist}'.format(**default) Is there a cleaner way to do ...
[ "Executive summary: encapsulate the song in a class.\nIt sounds to me like a song is a primary data type in your code and is worthy of having a dedicated class to represent it. By all means use a dict internal to the class to store the data but try and move to a higher level of abstraction than a dict.\nYou should ...
[ 6, 3, 1 ]
[ "I prefer Jared's version but if you really want to implement it yourself, here is one way:\n>>> class Song(dict):\n... def __getitem__(self, key):\n... if key in self.keys(): return super(Song, self).__getitem__(key)\n... return 'Unknown {key}'.format(key=key)\n... \n>>> s = Song()\n>>>...
[ -1, -1 ]
[ "python", "string_formatting" ]
stackoverflow_0007126803_python_string_formatting.txt
Q: Python regular expressions - find a string in a file that occurs somewhere before another string? My programming knowledge is very limited, I would really appreciate any help on this possibly obvious problem! Lets say I have a text file, that somewhere contains the text: "I own two (Some text in between...) bicycl...
Python regular expressions - find a string in a file that occurs somewhere before another string?
My programming knowledge is very limited, I would really appreciate any help on this possibly obvious problem! Lets say I have a text file, that somewhere contains the text: "I own two (Some text in between...) bicycles." How could I for example change two to three? Meaning I need a function to find the string "bicycl...
[ "You could do this with regular expressions:\n>>> import re\n>>> s = 'I own two (Some text in between...) bicycles and two dogs.'\n>>> re.sub('two(.*bicycles)', 'three\\\\1', s)\n'I own three (Some text in between...) bicycles and two dogs.'\n\nor regular string functions:\n>>> try:\n... p = s.rindex('two', 0, s....
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007120323_python_regex.txt
Q: Python C bindings Py_InitModule issue This latest programming project of mine has pushed some boundaries I haven't crossed before; mainly, I've begun doing some serious C programming. Stack Overflow's users have been exceptionally helpful so far, so I will draw on your knowledge again. I want to write some binding...
Python C bindings Py_InitModule issue
This latest programming project of mine has pushed some boundaries I haven't crossed before; mainly, I've begun doing some serious C programming. Stack Overflow's users have been exceptionally helpful so far, so I will draw on your knowledge again. I want to write some bindings C function bindings (drawing pixels to th...
[ "That's the mangled name of the function, which isn't found in the library because it's a macro from modsupport.h:\n#define Py_InitModule3(name, methods, doc) \\\n Py_InitModule4(name, methods, doc, (PyObject *)NULL, \\\n PYTHON_API_VERSION)\n\nmodsupport.h gets included by Python.h.\n" ]
[ 1 ]
[]
[]
[ "binding", "compilation", "python" ]
stackoverflow_0007126295_binding_compilation_python.txt
Q: Sequentially Combining Three Lists Created with Regular Expressions - Python I have a text file I am reading with three regular expressions. I'd like to combine each item from each regex search line by line and print them out using the same format as the last line below. I just cannot get the loop right to combine...
Sequentially Combining Three Lists Created with Regular Expressions - Python
I have a text file I am reading with three regular expressions. I'd like to combine each item from each regex search line by line and print them out using the same format as the last line below. I just cannot get the loop right to combine everything. Sample Text from three different sources(you can see info is sometim...
[ "You can use zip [docs] or itertools.izip [docs]:\nfor i, j, k in zip(cusip_result, bond_name_result, bond_price_result):\n print i, j, k\n\nDepending on the format of the file, the csv [docs] module might be helpful too (instead of using regular expressions to extract the content).\nYou could also iterate over ...
[ 1, 1 ]
[]
[]
[ "expression", "list", "python" ]
stackoverflow_0007127381_expression_list_python.txt
Q: Python: Find location of data within JSON object, parse the corresponding data I am getting this JSON object from a Simplegeo request. For certain areas, you will not have Address data. In those cases, I want to be able to find the part in the data with "subcategory":"County" and then query the corresponding name....
Python: Find location of data within JSON object, parse the corresponding data
I am getting this JSON object from a Simplegeo request. For certain areas, you will not have Address data. In those cases, I want to be able to find the part in the data with "subcategory":"County" and then query the corresponding name. What is the best way to find the location of data within a JSON response and grab t...
[ "First you will need to convert your JSON string into a Python dictionary using the json module.\nIf data is your new dictionary, the information you are looking for is in the list data[\"features\"]. You will need to iterate over this list and filter out any entries that you do not want. In your case, for each i...
[ 17 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007127053_json_python.txt
Q: Declaring variables in python I wanted parse a file to search one word and print next line i have written python script as follows infile = open("s.sdf","r") output = open("sample.txt","w") d = None HD = None HA = None M = None for line in infile: if line.startswith("> <PUBCHEM_COMPOUND_CID>"): d ...
Declaring variables in python
I wanted parse a file to search one word and print next line i have written python script as follows infile = open("s.sdf","r") output = open("sample.txt","w") d = None HD = None HA = None M = None for line in infile: if line.startswith("> <PUBCHEM_COMPOUND_CID>"): d = infile.next().strip() pr...
[ "To skip lines that do not match those strings add a check:\nif any(bool(x) for x in d, HD, HA, M):\n print ...\n output.write\n\nTry running the script in a debugger:\n$ python -m pdb your_script.py\n\nand see what variables are there and what's wrong. Since PDB is not convenient, you might want to install i...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007127813_python.txt
Q: Executing system commands in python I have experience with perl for writing scripts, which made it easy for me executing linux commands by using back-ticks. I was wondering, how can I do this Python ? Is there a special way for capturing the result of a command (output) ? thank you :) A: To add to urschrei's an...
Executing system commands in python
I have experience with perl for writing scripts, which made it easy for me executing linux commands by using back-ticks. I was wondering, how can I do this Python ? Is there a special way for capturing the result of a command (output) ? thank you :)
[ "To add to urschrei's answer, here's an example (Windows):\n>>> import subprocess\n>>> p = subprocess.Popen(['ping', '192.168.111.198'], stdout=subprocess.PIPE, st\nderr=subprocess.PIPE)\n>>> out, err = p.communicate()\n>>> print out\n\nPinging 192.168.111.198 with 32 bytes of data:\nReply from 192.168.111.198: byt...
[ 6, 2 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0007127829_python_sys.txt
Q: Multiple 'in' operators in Python? Is there a shorthand way of checking for keys in a dictionary? Something that I can use instead of using multiple in and and operators - instead of the following: ('somekey' in d) and ('someotherkey' in d) and ('somekeyggg' in d) A: all( word in d for word in [ 'somekey', 'some...
Multiple 'in' operators in Python?
Is there a shorthand way of checking for keys in a dictionary? Something that I can use instead of using multiple in and and operators - instead of the following: ('somekey' in d) and ('someotherkey' in d) and ('somekeyggg' in d)
[ "all( word in d for word in [ 'somekey', 'someotherkey', 'somekeyggg' ] )\n\n", "set(['somekey', 'someotherkey', 'somekeyggg']).issubset(d)\n\n" ]
[ 24, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007128153_python.txt
Q: export matlab variable to text for python usage So let's start off by saying I'm a total beginner in matlab. I'm working with python and now I've recieved some data in a matlab file that I need to export to a format I could use with python. I've googled around and found I can export a matlab variable to a text fil...
export matlab variable to text for python usage
So let's start off by saying I'm a total beginner in matlab. I'm working with python and now I've recieved some data in a matlab file that I need to export to a format I could use with python. I've googled around and found I can export a matlab variable to a text file using: dlmwrite('my_text', MyVariable, 'delimiter' ...
[ "To exchange big chunks of numerical data between Python and Matlab I\nrecommend HDF5\n\nhttp://en.wikipedia.org/wiki/Hierarchical_Data_Format\n\nThe Python binding is called h5py\n\nhttp://code.google.com/p/h5py\n\nHere are two examples for both directions. First from\nMatlab to Python\n% matlab\npoints = [1 2 3 ...
[ 6, 0, 0, 0 ]
[]
[]
[ "file_io", "matlab", "python" ]
stackoverflow_0007117797_file_io_matlab_python.txt
Q: LDAP Python query and converting the appropriate dictionary Sorry, I couldn't think of a better title for my question. So I'm a starter at Python and I really trying to learn how to use it. My current problem deals with creating a simple way to reduce the results received from a python query. If I understand what ...
LDAP Python query and converting the appropriate dictionary
Sorry, I couldn't think of a better title for my question. So I'm a starter at Python and I really trying to learn how to use it. My current problem deals with creating a simple way to reduce the results received from a python query. If I understand what I'm dealing with, the LDAP query returns a List of a List of Dict...
[ "Haha I'm not sure you ever want such a complicated data structure around. Consider refactoring your code to make your data structures easier to understand. Read: object-oriented programming, classes, functional programming principles.\nHere's the answer if you just want to do it for a single dictionary:\ndata = {k...
[ 0 ]
[]
[]
[ "dictionary", "django", "ldap", "python" ]
stackoverflow_0007128233_dictionary_django_ldap_python.txt
Q: Removing windows from the taskbar, Windows 7 I have a little Tkinter application here, as well as a handle to the Tkinter window. What I'm trying to do is remove the window from the taskbar using some combination of Windows API calls. Basically I don't want the window to show up in the task bar. import Tkinter a...
Removing windows from the taskbar, Windows 7
I have a little Tkinter application here, as well as a handle to the Tkinter window. What I'm trying to do is remove the window from the taskbar using some combination of Windows API calls. Basically I don't want the window to show up in the task bar. import Tkinter as tk import string import win32ui import win32con...
[ "I hope this helps, or at least guides you somehow.\nI'm not sure how to do this in python, but speaking for the winapi part, this has to do with the window ex style. This is what MSDN says:\n\nThe Shell creates a button on the taskbar whenever an application\n creates a window that isn't owned. To ensure that the...
[ 4 ]
[]
[]
[ "python", "pywin32", "tkinter", "winapi", "windows_7" ]
stackoverflow_0007128434_python_pywin32_tkinter_winapi_windows_7.txt
Q: python serial port I want to communicate with my serial port in python. I installed pyserial and uspp for linux: import serial ser = serial.Serial('/dev/pts/1', 19200, timeout=1) print ser.portstr #check which port was really used ser.write("hello") #write a string ser.close() # It gives th...
python serial port
I want to communicate with my serial port in python. I installed pyserial and uspp for linux: import serial ser = serial.Serial('/dev/pts/1', 19200, timeout=1) print ser.portstr #check which port was really used ser.write("hello") #write a string ser.close() # It gives the following error: Trace...
[ "if you are working with linux, generally, serial ports are named /dev/tty* ; just replace the * with s and the number of the port like /dev/ttyS1. I work with a arduino that communicates via usb-serial, and it's /dev/ttyUSB0.\n" ]
[ 6 ]
[]
[]
[ "linux", "pyserial", "python" ]
stackoverflow_0004040151_linux_pyserial_python.txt
Q: Efficiently change a key of a Python dict I'm looking to replace the keys of a dict to shorter variants so that it can be sent across the wire in a compact form. Is there a way to updating a key, rather than creating a new item in in the dict and deleting the old? What I'm doing now: >>> a = dict(long_key=None) >>...
Efficiently change a key of a Python dict
I'm looking to replace the keys of a dict to shorter variants so that it can be sent across the wire in a compact form. Is there a way to updating a key, rather than creating a new item in in the dict and deleting the old? What I'm doing now: >>> a = dict(long_key=None) >>> a['l'] = a['long_key'] >>> del a['long_key'] ...
[ "A more elegant solution might be to create a new dictionary... essentially make a slightly different shallow copy:\na_send = dict((k[0], v) for k,v in a.items())\n\nThat will certainly be less space-efficient, though - are you looking for space efficiency, time efficiency, or code elegance?\n", "That's premature...
[ 4, 3, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007128653_dictionary_python.txt
Q: Python: Homemade Tab Completion Help I need some help. I am completely stumped. I'm trying to write my own tab completion module for a custom shell style program (also completing arguments) I can tab complete the commands, but the arguments are giving me trouble. Can some one write a sample tab completing modul...
Python: Homemade Tab Completion Help
I need some help. I am completely stumped. I'm trying to write my own tab completion module for a custom shell style program (also completing arguments) I can tab complete the commands, but the arguments are giving me trouble. Can some one write a sample tab completing module for me to look at? Available Commands: [...
[ "In the end I figured it out after the 7th rewrite. A little messier than I would like, but workable, likely I will clean this up later. Anyways, here's the code:\n\"\"\"defined earlier in the script:\"\"\"\nCOMMANDS=['show', 'exit', 'ship']\ndef complete(text, state, list = COMMANDS):\n for option in list:\n ...
[ 1, 0, 0 ]
[]
[]
[ "command_line_interface", "homebrew", "python", "tab_completion" ]
stackoverflow_0007125745_command_line_interface_homebrew_python_tab_completion.txt
Q: Python: How to save the output of os.system In Python , If I am using "wget" to download a file using os.system("wget ), it shows on the screen like: Resolving... Connecting to ... HTTP request sent, awaiting response... 100%[==================================================================================...
Python: How to save the output of os.system
In Python , If I am using "wget" to download a file using os.system("wget ), it shows on the screen like: Resolving... Connecting to ... HTTP request sent, awaiting response... 100%[===================================================================================================================================...
[ "The os.system functions runs the command via a shell, so you can put any stdio redirects there as well. You should also use the -q flag (quiet) to wget. \ncmd = \"wget -q \" + theurl + \" >/dev/null 2>&1\" \n\nHowever, there are better ways of doing this in python, such as the pycurl wrapper for libcurl, or the \"...
[ 20, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007129107_python.txt
Q: Do function pointers remain valid across processes? I have written an extension module that uses C++ function pointers to store sequences of function calls. I want to 'run' these call sequences in separate processes using python's multiprocessing module (there's no shared state, so no synchronization issues). I ne...
Do function pointers remain valid across processes?
I have written an extension module that uses C++ function pointers to store sequences of function calls. I want to 'run' these call sequences in separate processes using python's multiprocessing module (there's no shared state, so no synchronization issues). I need to know if function pointers (not data pointers) remai...
[ "Sure--the address space is copied when you fork, so the pointers are still valid afterward for both parent and child processes.\n" ]
[ 4 ]
[]
[]
[ "c++", "function_pointers", "multiprocessing", "python", "python_extensions" ]
stackoverflow_0007129342_c++_function_pointers_multiprocessing_python_python_extensions.txt
Q: User defined __mul__ method is not commutative I wrote a class to represent vectors in Python (as an exercise) and I'm having problems with extending the built-in operators. I defined a __mul__ method for the vector class. The problem is that in the expression x * y the interpreter calls the __mul__ method of x, ...
User defined __mul__ method is not commutative
I wrote a class to represent vectors in Python (as an exercise) and I'm having problems with extending the built-in operators. I defined a __mul__ method for the vector class. The problem is that in the expression x * y the interpreter calls the __mul__ method of x, not y. So vector(1, 2, 3) * 2 returns a vector <2, 4...
[ "If you want commutativity for different types you need to implement __rmul__(). If implemented, it is called, like all __r*__() special methods, if the operation would otherwise raise a TypeError. Beware that the arguments are swapped:\nclass Foo(object):\n def __mul_(self, other):\n ''' multiply self wi...
[ 36, 3 ]
[]
[]
[ "built_in", "extend", "python" ]
stackoverflow_0007129441_built_in_extend_python.txt
Q: Standard error in non-linear regression I have been doing some Monte Carlo physics simulations with Python and I am in unable to determine the standard error for the coefficients of a non-linear least square fit. Initially, I was using SciPy's scipy.stats.linregress for my model since I thought it would be a linea...
Standard error in non-linear regression
I have been doing some Monte Carlo physics simulations with Python and I am in unable to determine the standard error for the coefficients of a non-linear least square fit. Initially, I was using SciPy's scipy.stats.linregress for my model since I thought it would be a linear model but noticed it is actually some sort ...
[ "Finally found the answer to this long asked question! I'm hoping this can at least save someone a few hours of hopeless research for this topic. Scipy has a special function called curve_fit under its optimize section. It uses the least square method to determine the coefficients and best of all, it gives you the ...
[ 14, 2 ]
[]
[]
[ "gnuplot", "numpy", "python", "scipy" ]
stackoverflow_0007126190_gnuplot_numpy_python_scipy.txt
Q: How to access a decorated method local variables ( locals() ) from inside a Python decorator? Here's what I need: Let's say I have this decorator: def deco(func): def decoret(*args, **kwargs): print(func.__locals__) # I know __locals__ is not valid, but I need something like this return decoret @d...
How to access a decorated method local variables ( locals() ) from inside a Python decorator?
Here's what I need: Let's say I have this decorator: def deco(func): def decoret(*args, **kwargs): print(func.__locals__) # I know __locals__ is not valid, but I need something like this return decoret @deco def func(): test1 = 123 test2 = 456 func() I want to fetch a list of all local variab...
[ "There are no locals in a function until it's executed. The only things available to you when it's decorated are what is there when it's defined.\nd = 'd'\ndef a(d=d):\n b = 'b'\n c = 'c'\n\nprint a.__dict__\n# {}\nprint a.b\n# AttributeError: 'function' object has no attribute 'b'\nprint dir(a)\n# Doesn't pr...
[ 3, 1 ]
[]
[]
[ "decorator", "python", "python_3.x" ]
stackoverflow_0007123521_decorator_python_python_3.x.txt
Q: Django statelessness? I'm just wondering if Django was designed to be a fully stateless framework? It seems to encourage statelessness and external storage mechanisms (databases and caches) but I'm wondering if it is possible to store some things in the server's memory while my app is in develpoment and runs via m...
Django statelessness?
I'm just wondering if Django was designed to be a fully stateless framework? It seems to encourage statelessness and external storage mechanisms (databases and caches) but I'm wondering if it is possible to store some things in the server's memory while my app is in develpoment and runs via manage.py runserver.
[ "Sure it's possible. But if you are writing a web application you probably won't want to do that because of threading issues.\n", "That depends on what you mean by \"store things in the server's memory.\" It also depends on the type of data. If you can, you're better off storing \"global data\" in a database or i...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007128868_django_python.txt
Q: python variable method name How can you execute a method by giving its name, from another method that is in the same class with the called method? Like this: class Class1: def __init__(self): pass def func1(self, arg1): # some code def func2(self): function = getattr(sys.modules...
python variable method name
How can you execute a method by giving its name, from another method that is in the same class with the called method? Like this: class Class1: def __init__(self): pass def func1(self, arg1): # some code def func2(self): function = getattr(sys.modules[__name__], "func1") # apparently...
[ "how about getattr(self, \"func1\")? Also, avoid using the name function\nFor example:\n>>> class C:\n... def f1(self, arg1): print arg1\n... def f2(self): return getattr(self, \"f1\")\n... \n>>> x=C()\n>>> x.f2()(1)\n1\n\n", "You should get the attribute from the class, not the module.\ndef func2(self):\n ...
[ 11, 6 ]
[]
[]
[ "function", "methods", "python", "variables" ]
stackoverflow_0007129736_function_methods_python_variables.txt
Q: UnboundLocalError- local variable referenced before assignment - Django You guys have helped me out so much this week it has been awesome.Hopefully you can help me out with this one. I tried looking at the other posts on the site about this type of error, but none of them really helped me out. Basically I am submi...
UnboundLocalError- local variable referenced before assignment - Django
You guys have helped me out so much this week it has been awesome.Hopefully you can help me out with this one. I tried looking at the other posts on the site about this type of error, but none of them really helped me out. Basically I am submitting a form on one page and the POST data is going to the same view that it ...
[ "This is happening because request.method == 'POST' is True (first condition passes) but form.is_valid() is False (second nested condition fails), which means the final return after the else is run but ctxt is not defined.\nPerhaps you intended that final return to be indented as a part of the else clause?\n" ]
[ 8 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0007129795_django_django_forms_django_views_python.txt
Q: Display Text in Template? I have a text field in my model that contains markdown text. I need to convert the text to html and show it in my .pt template. what is the best way to do it? I realise that I can add a method to my model that converts the field and returns HTML, and then call the method from my template,...
Display Text in Template?
I have a text field in my model that contains markdown text. I need to convert the text to html and show it in my .pt template. what is the best way to do it? I realise that I can add a method to my model that converts the field and returns HTML, and then call the method from my template, but can I do it without this e...
[ "Plone, which uses TAL for it's templating engine and can use StructuredText, reStructuredText, and other rich text formats, does all the rendering to HTML outside TAL. So you might be barking up the wrong tree in the approach you're going for.\nThat said, TAL has a somewhat extensible \"expression\" system which ...
[ 1 ]
[]
[]
[ "chameleon", "markdown", "pyramid", "python", "template_tal" ]
stackoverflow_0007129377_chameleon_markdown_pyramid_python_template_tal.txt
Q: no Error Messages in imported python classes i have a couple of python classes, which i import and use in my main program. ## path to classes sys.path.append(basePath + "classes") ## import some classes import mainmod mainModHandler = mainmod.Mainmod() I have no problem, working with them, but i wonder, if i h...
no Error Messages in imported python classes
i have a couple of python classes, which i import and use in my main program. ## path to classes sys.path.append(basePath + "classes") ## import some classes import mainmod mainModHandler = mainmod.Mainmod() I have no problem, working with them, but i wonder, if i have a error in my imported class, i do not get an ...
[ "If all you're doing is importing your module then you wouldn't get an error since that error would only happen when instantiating the class. It's unclear from your question if the code that you give as an example is the exact code you expect to produce the error.\nIf that isn't it, provide more context, maybe lin...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006699072_python.txt
Q: setuptools searching for false dependency I am running into a bizarre problem where I try to install my python package (using setuptools) on a Linux system and it tries to install pywin32 as a dependency. This only happens if I run it from a specific directory. If I move the whole tree to a different directory, it...
setuptools searching for false dependency
I am running into a bizarre problem where I try to install my python package (using setuptools) on a Linux system and it tries to install pywin32 as a dependency. This only happens if I run it from a specific directory. If I move the whole tree to a different directory, it installs fine. My setup.py does reference pywi...
[ "Try removing the *.egg-info in the dist develop directory. If that doesn't work, try starting with a fresh, untouched checkout of your code without any of the other setuptools/dist artifacts and see if that reproduces the problem. If it doesn't then you know it's one of the setuptools/dist artifacts that just ne...
[ 0 ]
[]
[]
[ "linux", "python", "pywin32", "setuptools" ]
stackoverflow_0006308381_linux_python_pywin32_setuptools.txt