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: Create launchable GUI script from Python setuptools (without console window!) The way I currently add an executable for my Python-based GUI is this: setup( # ... entry_points = {"gui_scripts" : ['frontend = myfrontendmodule.launcher:main']}, # ... ) On Windows, this will create "frontend.e...
Create launchable GUI script from Python setuptools (without console window!)
The way I currently add an executable for my Python-based GUI is this: setup( # ... entry_points = {"gui_scripts" : ['frontend = myfrontendmodule.launcher:main']}, # ... ) On Windows, this will create "frontend.exe" and "frontend-script.pyw" in Python's scripts folder (using Python 2.6). When I...
[ "Alright, I investigated a bit in the setuptools source code and it all boils down to a bug in setuptools (easy_install.py):\n# On Windows/wininst, add a .py extension and an .exe launcher\nif group=='gui_scripts':\n ext, launcher = '-script.pyw', 'gui.exe'\n old = ['.pyw']\n new_header = re.sub('(?i)pytho...
[ 12, 0 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0003542119_distutils_python_setuptools.txt
Q: Python: using ctypes I need to use Dll from python using ctypes but I read the tutorial and I don´t understand anything!! I wants to load the dll from path and access to its functions... SOS!! Thanks A: import ctypes foo = ctypes.CDLL("/path/to/library") foo.function_name() You should maybe look for a better tu...
Python: using ctypes
I need to use Dll from python using ctypes but I read the tutorial and I don´t understand anything!! I wants to load the dll from path and access to its functions... SOS!! Thanks
[ "import ctypes\nfoo = ctypes.CDLL(\"/path/to/library\")\nfoo.function_name()\n\nYou should maybe look for a better tutorial. Here is one: http://python.net/crew/theller/ctypes/tutorial.html\n" ]
[ 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003542409_ctypes_python.txt
Q: Pitfalls of number values in Python, "How deep?" I'm a fairly green programmer, and I'm learning Python right now. I'm up to chapter 17 in "Learn to Think Like a Computer Scientist" (Classes and Methods), and I just wrote my first doctest that failed in a way I truly do not fully understand: class Point(object): ...
Pitfalls of number values in Python, "How deep?"
I'm a fairly green programmer, and I'm learning Python right now. I'm up to chapter 17 in "Learn to Think Like a Computer Scientist" (Classes and Methods), and I just wrote my first doctest that failed in a way I truly do not fully understand: class Point(object): ''' represents a point object. attributes: ...
[ ">>> point.x\n\ncalls repr function which is for string representation holding more technical information than strfunction, which is called when \n>>> print point.x\n\noccurs\n", "This has to do with how computers store floating point numbers. A detailed description of this is here. However, for your case, the qu...
[ 4, 3, 2, 1, 1 ]
[]
[]
[ "ambiguity", "binary", "floating_point", "python" ]
stackoverflow_0003542229_ambiguity_binary_floating_point_python.txt
Q: What's this text encoding? I used Python's imaplib to pull mail from a gmail account... but I got an email with this confusing text body: > RGF0ZSBldCBoZXVyZTogICAgICAgICAgICAgICAgICAgICAgICAgICAyMi8wOC8yMDEwIDE0 > OjMzOjAzIEdNVCBVbmtub3duDQpQcsOpbm9tOiAgICAgICAgICAgICAgICAgICAgICAgICAg > ICAgICAgICAgamFjaW50bw0KT...
What's this text encoding?
I used Python's imaplib to pull mail from a gmail account... but I got an email with this confusing text body: > RGF0ZSBldCBoZXVyZTogICAgICAgICAgICAgICAgICAgICAgICAgICAyMi8wOC8yMDEwIDE0 > OjMzOjAzIEdNVCBVbmtub3duDQpQcsOpbm9tOiAgICAgICAgICAgICAgICAgICAgICAgICAg > ICAgICAgICAgamFjaW50bw0KTm9tOiAgICAgICAgICAgICAgICAgICAgI...
[ "It looks like base64. In Python you can either use base64.b64decode or str.decode('base64').\nmessage = '''\nRGF0ZSBldCBoZXVyZTogICAgICAgICAgICAgICAgICAgICAgICAgICAyMi8wOC8yMDEwIDE0\nOjMzOjAzIEdNVCBVbmtub3duDQpQcsOpbm9tOiAgICAgICAgICAgICAgICAgICAgICAgICAg\nICAgICAgICAgamFjaW50bw0KTm9tOiAgICAgICAgICAgICAgICAgICAgIC...
[ 14, 1, 1 ]
[]
[]
[ "character", "encoding", "gmail", "imaplib", "python" ]
stackoverflow_0003542842_character_encoding_gmail_imaplib_python.txt
Q: Store user defined data after inputted I am making a python program, and I want to check if it is the users first time running the program (firstTime == True). After its ran however, I want to permanently change firstTime to False. (There are other variables that I want to take input for that will stay if it is th...
Store user defined data after inputted
I am making a python program, and I want to check if it is the users first time running the program (firstTime == True). After its ran however, I want to permanently change firstTime to False. (There are other variables that I want to take input for that will stay if it is the first run, but that should be solved the s...
[ "If you want to persist data, it will \"eventually\" be to disk files (though there might be intermediate steps, e.g. via a network or database system, eventually if the data is to be persistent it will be somewhere in disk files).\nTo \"find out where you are\",\nimport os\nprint os.path.dirname(os.path.abspath(__...
[ 3, 0 ]
[]
[]
[ "python", "store" ]
stackoverflow_0003542455_python_store.txt
Q: how to keep count of replaced strings I have a massive string im trying to parse as series of tokens in string form, and i found a problem: because many of the strings are alike, sometimes doing string.replace()will cause previously replaced characters to be replaced again. say i have the string being replaced is ...
how to keep count of replaced strings
I have a massive string im trying to parse as series of tokens in string form, and i found a problem: because many of the strings are alike, sometimes doing string.replace()will cause previously replaced characters to be replaced again. say i have the string being replaced is 'goto' and it gets replaced by '41' (hex) a...
[ "If you're trying to substitute strings at once, you can use a dictionary:\ntranslation = {'PRINT': '32', 'GOTO': '41'}\ncode = ' '.join(translation[i] if i in translation else i for i in code.split(' '))\n\nwhich is basically O(2|S|+(n*|dict|)). Very fast. Although memory usage could be quite substantial. Keeping ...
[ 1 ]
[]
[]
[ "parsing", "python", "str_replace", "string" ]
stackoverflow_0003534997_parsing_python_str_replace_string.txt
Q: How to input n numbers in list one by one? I want my program to ask a value of n. After user inputs the value, program takes input for n values and stores them in a list or something like array (in C). Input must be in the format: Enter value of n: 4 2 5 7 1 I want to store this input in a list for my later use. ...
How to input n numbers in list one by one?
I want my program to ask a value of n. After user inputs the value, program takes input for n values and stores them in a list or something like array (in C). Input must be in the format: Enter value of n: 4 2 5 7 1 I want to store this input in a list for my later use.
[ "The simplest approach is something like this:\nn = int(input())\nl = [int(input()) for _ in range(n)]\n\nHowever this has a number of problems:\n\nIt will crash on invalid inputs.\nIt evaluates the inputs which is dangerous - the user could modify your program state. (Python 2.x)\nThe user could enter floating poi...
[ 3, 1 ]
[]
[]
[ "input", "list", "python" ]
stackoverflow_0003542753_input_list_python.txt
Q: GAE self.request.environ and server host I'm trying to obtain the base URL (hostname) of the server in which my appengine app is running on. Ie something along the lines of wsgiref.util.application_uri(self.request.environ) However it's returning the PATH_INFO which I do not want. Perhaps I'm missing something bu...
GAE self.request.environ and server host
I'm trying to obtain the base URL (hostname) of the server in which my appengine app is running on. Ie something along the lines of wsgiref.util.application_uri(self.request.environ) However it's returning the PATH_INFO which I do not want. Perhaps I'm missing something but even this article states the path info shoul...
[ "The request object is a Webob request object. As such, you can get the hostname from self.request.host, the hostname with protocol from self.request.host_url, and so forth.\n", "You can find the hostname in os.environ['HTTP_HOST'].\nThat won't include the protocol, but it should be easy to parse from the value y...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "python", "wsgi" ]
stackoverflow_0003534273_google_app_engine_python_wsgi.txt
Q: use gtk in a nautilus extension using python The following code import gtk import nautilus import os def alert(message): """A function to debug""" dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) dialog.run() dialog.destroy() class TestExtension(naut...
use gtk in a nautilus extension using python
The following code import gtk import nautilus import os def alert(message): """A function to debug""" dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) dialog.run() dialog.destroy() class TestExtension(nautilus.MenuProvider): def __init__(self): ...
[ "On the nautilus mailing list Ahmad Sherif found my error:\n\ngtk.MessageDialog is not working with your code because the fifth argument\n has to be either string or None, and the variable name is of type\n nautilus.FileInfo, which means you need to call alert(name.get_name())\n not just alert(name)\n Please re...
[ 2 ]
[]
[]
[ "gtk", "nautilus", "python" ]
stackoverflow_0003325772_gtk_nautilus_python.txt
Q: Obtain distances to nearest landmarks (Mall, Hospital, and Airport etc.) using google map I am working on a project in which I have around 100000 addreses in major cities in India(it is a table in a database). I want to know if it is possible to obtain the distances to to nearest landmarks (Mall, Hospital, and Ai...
Obtain distances to nearest landmarks (Mall, Hospital, and Airport etc.) using google map
I am working on a project in which I have around 100000 addreses in major cities in India(it is a table in a database). I want to know if it is possible to obtain the distances to to nearest landmarks (Mall, Hospital, and Airport etc.). Ideally I want these distances to be mergeed to the parent table. We have Java and...
[ "(I will probably state the obvious here, but, if that is the case, please overlook those points and read on.)\nGeneral Distances\n(\"As The Crow Flies\" and for Limiting Search/Processing Loads)\nDetermining Distances Between Two Points can be done within the SQL Database / SELECT statement.\nReference: MySQL Grea...
[ 2 ]
[]
[]
[ "java", "php", "python" ]
stackoverflow_0002752713_java_php_python.txt
Q: What substitutes xreadlines() in Python 3? In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar t...
What substitutes xreadlines() in Python 3?
In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar to xreadlines()? I know I can do for line in f: ...
[ "The file object itself is already an iterable.\n>>> f = open('1.txt')\n>>> f\n<_io.TextIOWrapper name='1.txt' encoding='UTF-8'>\n>>> next(f)\n'1,B,-0.0522642316338,0.997268450092\\n'\n>>> next(f)\n'2,B,-0.081127897359,2.05114559572\\n'\n\n\nUse itertools.islice to get an arbitrary element from an iterable.\n>>> f....
[ 17, 1 ]
[]
[]
[ "iterator", "python", "python_3.x", "readlines" ]
stackoverflow_0003541274_iterator_python_python_3.x_readlines.txt
Q: Variable interpolation in Python Possible Duplicate: Unpythonic way of printing variables in Python? In PHP one can write: $fruit = 'Pear'; print("Hey, $fruit!"); But in Python it's: fruit = 'Pear' print("Hey, {0}!".format(fruit)) Is there a way for me to interpolate variables in strings instead? And if not, h...
Variable interpolation in Python
Possible Duplicate: Unpythonic way of printing variables in Python? In PHP one can write: $fruit = 'Pear'; print("Hey, $fruit!"); But in Python it's: fruit = 'Pear' print("Hey, {0}!".format(fruit)) Is there a way for me to interpolate variables in strings instead? And if not, how is this more pythonic? Bonus point...
[ "The closest you can get to the PHP behaviour is and still maintaining your Python-zen is:\nprint \"Hey\", fruit, \"!\"\n\nprint will insert spaces at every comma.\nThe more common Python idiom is:\nprint \"Hey %s!\" % fruit\n\nIf you have tons of arguments and want to name them, you can use a dict:\nprint \"Hey %(...
[ 12, 7, 2, 1 ]
[ "Don't do it. It is unpythonic. As example, when you add translations to your app, you can't longer control which variables are used unless you check all the translations files yourself.\nAs example, if you change a local variable, you'll have to change it in all translated strings too. \n" ]
[ -3 ]
[ "python", "string" ]
stackoverflow_0003542714_python_string.txt
Q: OpenCV Python binds incredibly slow iterations through image data I recently took some code that tracked an object based on color in OpenCV c++ and rewrote it in the python bindings. The overall results and method were the same minus syntax obviously. But, when I perform the below code on each frame of a video it ...
OpenCV Python binds incredibly slow iterations through image data
I recently took some code that tracked an object based on color in OpenCV c++ and rewrote it in the python bindings. The overall results and method were the same minus syntax obviously. But, when I perform the below code on each frame of a video it takes almost 2-3 seconds to complete where as the c++ variant, also bel...
[ "Try using numpy to do your calculation, rather than nested loops. You should get C-like performance for simple calculations like this from numpy.\nFor example, your nested for loops can be replaced with a couple of numpy expressions...\nI'm not terribly familiar with opencv, but I think the python bindings now ha...
[ 6 ]
[]
[]
[ "c++", "opencv", "performance", "python" ]
stackoverflow_0003542968_c++_opencv_performance_python.txt
Q: Benchmarks of scripting languages doing the same task? Does anyone know where I could find reviews or reports on tasks that people implemented in two or more scripting languages to see which was more suited to a specific job? I want to know which languages are best suited to which types of operation so that I can ...
Benchmarks of scripting languages doing the same task?
Does anyone know where I could find reviews or reports on tasks that people implemented in two or more scripting languages to see which was more suited to a specific job? I want to know which languages are best suited to which types of operation so that I can make the most of them. "Types of operation" could be sockets...
[ "There's the programming language shootout:\nhttp://shootout.alioth.debian.org/\nAlthough it may not measure enough of the things you're looking for.\nHowever, benchmarks almost certainly won't tell you anything useful about high level ideas of the sort you listed. For those things, the performance (as in speed of ...
[ 5, 3, 2 ]
[]
[]
[ "benchmarking", "perl", "php", "python", "ruby" ]
stackoverflow_0003543193_benchmarking_perl_php_python_ruby.txt
Q: python regex match and replace I need to find, process and remove (one by one) any substrings that match a rather long regex: # p is a compiled regex # s is a string while 1: m = p.match(s) if m is None: break process(m.group(0)) #do something with the matched pattern s = re.sub(m.group(0...
python regex match and replace
I need to find, process and remove (one by one) any substrings that match a rather long regex: # p is a compiled regex # s is a string while 1: m = p.match(s) if m is None: break process(m.group(0)) #do something with the matched pattern s = re.sub(m.group(0), '', s) #remove it from string s ...
[ "The re.sub function can take a function as an argument so you can combine the replacement and processing steps if you wish:\n# p is a compiled regex\n# s is a string \ndef process_match(m):\n # Process the match here.\n return ''\n\ns = p.sub(process_match, s)\n\n" ]
[ 21 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003543559_python_regex.txt
Q: Get variable from parent I have two files. main.py that has main program logic and functions.py that has additional functions. Lets say main.py has this code import functions some_var = 'some value' I would like to print out value of some_var in my functions.py file. How can I achieve this. A: In general, you c...
Get variable from parent
I have two files. main.py that has main program logic and functions.py that has additional functions. Lets say main.py has this code import functions some_var = 'some value' I would like to print out value of some_var in my functions.py file. How can I achieve this.
[ "In general, you can do this my simply importing the main module within functions.py\nWithin your functions.py file:\nimport main\nprint main.some_var\n\nHowever, you currently have a circular dependency problem. See Circular (or cyclic) imports in Python\nYou could put some_var into a third module, let's say cons...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003543592_python.txt
Q: Script won't run in Python3.0 This script will run as expected and pass doctests without any errors in Python 2.6: def num_even_digits(n): """ >>> num_even_digits(123456) 3 >>> num_even_digits(2468) 4 >>> num_even_digits(1357) 0 >>> num_even_digits(2) 1 >>>...
Script won't run in Python3.0
This script will run as expected and pass doctests without any errors in Python 2.6: def num_even_digits(n): """ >>> num_even_digits(123456) 3 >>> num_even_digits(2468) 4 >>> num_even_digits(1357) 0 >>> num_even_digits(2) 1 >>> num_even_digits(20) 2 ""...
[ "I'm guessing you need n //= 10 instead of n /= 10. In other words, you want to explictly specify integer division. Otherwise 1 / 10 will return 0.1 instead of 0. Note that //= is valid python 2.x syntax, as well (well, starting with version ~2.3, I think...).\n", "And now for something completely different:\nco...
[ 13, 5, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003543453_python_python_3.x.txt
Q: Email body is a string sometimes and a list sometimes. Why? My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I w...
Email body is a string sometimes and a list sometimes. Why?
My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message obj...
[ "Well, the answers are correct, you should read the docs, but for an example of a generic way:\ndef get_first_text_part(msg):\n maintype = msg.get_content_maintype()\n if maintype == 'multipart':\n for part in msg.get_payload():\n if part.get_content_maintype() == 'text':\n re...
[ 13, 10, 10, 0 ]
[]
[]
[ "email", "message", "payload", "python" ]
stackoverflow_0000594545_email_message_payload_python.txt
Q: What is the Django way to do this? class Article(models.Model): def user_may_see_full_version(self, user): # do something very sophisticated with the user return [True/False whatever] now i want to create a template like this: {% for article in articles %} {% if article.user_may_see_full_v...
What is the Django way to do this?
class Article(models.Model): def user_may_see_full_version(self, user): # do something very sophisticated with the user return [True/False whatever] now i want to create a template like this: {% for article in articles %} {% if article.user_may_see_full_version request.user %}{{ article }}{% el...
[ "There's no way to pass an argument to a method directly from a template. A template filter is the best way to go:\n{% if article|user_may_see_full_version:user %}{{ article }}{% else %}{{article.title }}{% endif %}\n\nThe filter is implemented like this:\n@register.filter()\ndef user_may_see_full_version(article,...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003543603_django_python.txt
Q: adding text to image using python Is the following function correct, this code is meant to add a phrase to image. Note that i cannot use image.text function or any other but can only use getpixel, putpixel, load, and save. def insertTxtImage(srcImage, phrase): pixel = srcImage.getpixel(30,30); srcImage.put...
adding text to image using python
Is the following function correct, this code is meant to add a phrase to image. Note that i cannot use image.text function or any other but can only use getpixel, putpixel, load, and save. def insertTxtImage(srcImage, phrase): pixel = srcImage.getpixel(30,30); srcImage.putpixel(pixel,phrase); srcImage.save;...
[]
[]
[ "No, the functions you are using modify pixels. \nTo draw font you want to use something like following:\nf= pygame.font.Font(None, 12)\nsurf= f.render(phrase)\nsrcImage.blit(surf, (30,30))\n\nfor more documentation see here: (scroll down a bit)\nhttp://www.pygame.org/docs/ref/font.html\nEDIT: nvm, I don't even kno...
[ -1 ]
[ "python" ]
stackoverflow_0003543573_python.txt
Q: Accessing later index in array using enumerate(array) Python hey guys, how would you access an array from array[n] in an array of 100 floats in this for loop (i need the enumerate): for index,value in enumerate(array): #do stuff with array[n] n=n+1 im trying to make it so that it operates in a smaller and...
Accessing later index in array using enumerate(array) Python
hey guys, how would you access an array from array[n] in an array of 100 floats in this for loop (i need the enumerate): for index,value in enumerate(array): #do stuff with array[n] n=n+1 im trying to make it so that it operates in a smaller and smaller space each iteration.. thanks
[ "You should probably clarify whether you mean a list, a numpy array, an array.array, or something else...\nThat having been said, it sounds like you want to slice whatever your \"array\" is. Perhaps something like this?:\ndata = range(10)\nfor i in range(len(data)):\n print data[i:]\n\nWhich would output:\n[0,...
[ 2, 2 ]
[]
[]
[ "arrays", "enumerate", "for_loop", "python" ]
stackoverflow_0003543382_arrays_enumerate_for_loop_python.txt
Q: Ordering of evaluation using boolean or So I've got this snippet of code. And it works (It says 1 is non-prime).: n = 1 s = 'prime' for i in range(2, n / 2 + 1): if n == 1 or n % i == 0: s= 'non-' +s break print s My problem is that if I change the fourth line to: if n % i == 0 or n == 1:, it...
Ordering of evaluation using boolean or
So I've got this snippet of code. And it works (It says 1 is non-prime).: n = 1 s = 'prime' for i in range(2, n / 2 + 1): if n == 1 or n % i == 0: s= 'non-' +s break print s My problem is that if I change the fourth line to: if n % i == 0 or n == 1:, it doesn't work (it says 1 is prime.) Why is th...
[ "In both cases, the body of the loop does not run, because when 'n' is 1, it does not fall within the range of (n,n/2+1)\nThe code you posted says that 1 is prime (again, because the loop body does not execute at all)\n", "i think the problem is when n is 1, the loop is skipped.\n", "The precedence is fine. % i...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "boolean", "or_operator", "python" ]
stackoverflow_0003544591_boolean_or_operator_python.txt
Q: Python: email.message_from_string performance with large data in email body I've been playing around with Python's imaplib and email module recently. I tried sending and receiving large emails (with most of the data in the body of the email rather than attachments) using the imaplib/email modules. However, I've n...
Python: email.message_from_string performance with large data in email body
I've been playing around with Python's imaplib and email module recently. I tried sending and receiving large emails (with most of the data in the body of the email rather than attachments) using the imaplib/email modules. However, I've noticed a problem when I download large emails (of size greater than 8MB or so) fr...
[ "Okay, I did some digging on my own by examining the source code for the email module. The parsing function (parse()) in email/parser.py is the function which actually processes the email message when email.message_from_string() is called. It seems to parse strings in blocks of 8192 bytes which is why it takes so l...
[ 1 ]
[]
[]
[ "email", "imaplib", "python" ]
stackoverflow_0003543118_email_imaplib_python.txt
Q: Bandwidth test, delay test using urllib2 I want to make a python script that tests the bandwidth of a connection. I am thinking of downloading/uploading a file of a known size using urllib2, and measuring the time it takes to perform this task. I would also like to measure the delay to a given IP address, such as ...
Bandwidth test, delay test using urllib2
I want to make a python script that tests the bandwidth of a connection. I am thinking of downloading/uploading a file of a known size using urllib2, and measuring the time it takes to perform this task. I would also like to measure the delay to a given IP address, such as is given by pinging the IP. Is this possible u...
[ "You can use PyCurl for this. curl_easy_getinfo gives info about:\nCURLINFO_TOTAL_TIME, CURLINFO_NAMELOOKUP_TIME, CURLINFO_CONNECT_TIME, CURLINFO_PRETRANSFER_TIME etc. \n", "You could download an empty file to measure the delay. You measure more the only the network delay, but the difference should be too big I e...
[ 3, 0 ]
[]
[]
[ "bandwidth", "python", "urllib2" ]
stackoverflow_0003280391_bandwidth_python_urllib2.txt
Q: Accessing the name of an instance in Python for printing So as part of problem 17.6 in "Think Like a Computer Scientist", I've written a class called Kangaroo: class Kangaroo(object): def __init__(self, pouch_contents = []): self.pouch_contents = pouch_contents def __str__(self): ''' ...
Accessing the name of an instance in Python for printing
So as part of problem 17.6 in "Think Like a Computer Scientist", I've written a class called Kangaroo: class Kangaroo(object): def __init__(self, pouch_contents = []): self.pouch_contents = pouch_contents def __str__(self): ''' >>> kanga = Kangaroo() >>> kanga.put_in_pouch('olf...
[ "To put your request into perspective, please explain what name you would like attached to the object created by this code:\nmarsupials = []\nmarsupials.append(Kangaroo()) \n\nThis classic essay by the effbot gives an excellent explanation.\nTo answer the revised question in your edit: No.\nNow that you've come cle...
[ 6, 2, 2, 0, 0 ]
[]
[]
[ "class_method", "printing", "python", "string" ]
stackoverflow_0003543652_class_method_printing_python_string.txt
Q: Create frame class in Tkinter Gui I'm working on a Gui and I'd like to know how to create a class that would implement frame. e.g. class WindowContent(Tkinter.?) """ This class would create a frame for my program window """ class App(Tkinter.Tk): """ main window constructor """ def __init__(self): ...
Create frame class in Tkinter Gui
I'm working on a Gui and I'd like to know how to create a class that would implement frame. e.g. class WindowContent(Tkinter.?) """ This class would create a frame for my program window """ class App(Tkinter.Tk): """ main window constructor """ def __init__(self): Tkinter.Tk.__init__(self) ...
[ "I found the answer :\nclass WindowProgram(Tkinter.Frame)\n \"\"\" This class creates a frame for my program window \"\"\"\n def __init__(self, parent):\n Tkinter.Frame.__init__(self, parent)\n\nclass App(Tkinter.Tk):\n \"\"\" application constructor \"\"\"\n def __init__(self):\n Tkinter....
[ 2, 0 ]
[]
[]
[ "class", "frame", "python", "tkinter", "user_interface" ]
stackoverflow_0003528899_class_frame_python_tkinter_user_interface.txt
Q: which one to choose for future , c++ or python2.x/3.x since last four years i had been coding in c/c++, but those lenthy programs made me sick of them. then i got to know about python, and i have learned the basics. python seams to be more flexible and powerful than c++... But i want to know is python realy better...
which one to choose for future , c++ or python2.x/3.x
since last four years i had been coding in c/c++, but those lenthy programs made me sick of them. then i got to know about python, and i have learned the basics. python seams to be more flexible and powerful than c++... But i want to know is python realy better than c++? if yes/no in what ways , please explain. since i...
[ "Python is completely different than C/C++, so it's hard to compare. Python lets you write clear, concise programs and very quickly develop software at the price of performance. It lets you be very productive and in many cases program performance is less concern, than programmer performance.\nThere are many existin...
[ 2, 2 ]
[]
[]
[ "c", "c++", "python" ]
stackoverflow_0003545655_c_c++_python.txt
Q: Convert python pack to php pack I have this python script b_string = pack('>hqh2sh13sh5sh3sBiiihiiiiii', 21, 0, len(country), country, len(device), device, len('1.3.1'), "1.3.1", len('Web'), "Web", 27, 0, 0, ...
Convert python pack to php pack
I have this python script b_string = pack('>hqh2sh13sh5sh3sBiiihiiiiii', 21, 0, len(country), country, len(device), device, len('1.3.1'), "1.3.1", len('Web'), "Web", 27, 0, 0, 3, 0, cid, lac, ...
[ "Your parameter string is all screwed up. You indicate in places that you are going to pass 2, 5, 3 and 13 shorts, but only provide one each time. You indicate that you are going to provide a series of characters but then you provide a NUL terminated string. You indicate that you will be providing an unsigned char ...
[ 0 ]
[]
[]
[ "pack", "php", "python" ]
stackoverflow_0003545689_pack_php_python.txt
Q: How to optimize PyQt QSortFilterProxyModel filter reimplementation? I have a reimplemented QSortFilterProxyModel acceptRows to achieve custom behavior, i want it to not filter out items which have a valid child. class KSortFilterProxyModel(QSortFilterProxyModel): #FIXME: Funciona pero es endemoniadamente lento...
How to optimize PyQt QSortFilterProxyModel filter reimplementation?
I have a reimplemented QSortFilterProxyModel acceptRows to achieve custom behavior, i want it to not filter out items which have a valid child. class KSortFilterProxyModel(QSortFilterProxyModel): #FIXME: Funciona pero es endemoniadamente lento def __init__(self, parent=None): super(KSortFilterProxyModel...
[ "I don't see anything obviously wrong with what you're doing. Keep in mind that filterAcceptsRow is called for every item in your model, and this is of course going to be sluggish because the overhead of calling a Python function from C++ is a few milliseconds. This adds up rather quickly if you have a model with...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt4" ]
stackoverflow_0003474098_pyqt_pyqt4_python_qt4.txt
Q: Look for an example application of "pylons + sqlalchemy" I'm new to python, and starting to learn website development with pylons and sqlalchemy. I've read the document of sqlalchemy and pylons, but still have a lot of problems. I've tried 2 days, but a simple website with basic CRUD operations can't work yet. I ...
Look for an example application of "pylons + sqlalchemy"
I'm new to python, and starting to learn website development with pylons and sqlalchemy. I've read the document of sqlalchemy and pylons, but still have a lot of problems. I've tried 2 days, but a simple website with basic CRUD operations can't work yet. I met some big problems(for me), that the circular imports probl...
[ "You should read The Pylons Book.\n", "You should probably start looking from here, http://wiki.pylonshq.com/display/pylonscommunity/Sites+Using+Pylons as many of them are open-source.\nAnother source would be PyPI: http://pypi.python.org/pypi?%3Aaction=search&term=pylons&submit=search\nGood (but complex) example...
[ 4, 3 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0003545979_pylons_python_sqlalchemy.txt
Q: How to declared one-to-many if there are 2 fields for a same foreign key I'm new to python(sqlalchemy), and I'm learning to build web site with pylons and sqlalchemy. I have a problem when I declare the relationship between models. I've tried it several hours, but failed. But I think it should be a basic question...
How to declared one-to-many if there are 2 fields for a same foreign key
I'm new to python(sqlalchemy), and I'm learning to build web site with pylons and sqlalchemy. I have a problem when I declare the relationship between models. I've tried it several hours, but failed. But I think it should be a basic question. I have two classes: User and Article, user can create articles, and modified...
[ "Ah, thats obvious one. \nArticle class has two references to User, user_id and editor_id, so SQLA does not know which one of them to use for your relation. Just use explicit primaryjoin:\nuser = relation('User', backref='articles', primaryjoin=\"Article.user_id==User.id\")\n\n" ]
[ 2 ]
[]
[]
[ "one_to_many", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003546338_one_to_many_pylons_python_sqlalchemy.txt
Q: python: changing dictionary returned by groupdict() Is it safe to modify a mutable object returned by a method of a standard library object? Here's one specific example; but I'm looking for a general answer if possible. #m is a MatchObject #I know there's only one named group in the regex #I want to retrieve the n...
python: changing dictionary returned by groupdict()
Is it safe to modify a mutable object returned by a method of a standard library object? Here's one specific example; but I'm looking for a general answer if possible. #m is a MatchObject #I know there's only one named group in the regex #I want to retrieve the name and the value g, v = m.groupdict().popitem() #do some...
[ "Generally it's only guaranteed to be safe if the documentation says so. (In this particular case it seems very unlikely that another implementation would behave differently though.)\n", "groupdict returns a new dictionary every time:\nIn [20]: id(m.groupdict())\nOut[20]: 3075475492L\n\nIn [21]: id(m.groupdict()...
[ 1, 0, 0, 0 ]
[]
[]
[ "mutable", "object", "python" ]
stackoverflow_0003545502_mutable_object_python.txt
Q: How do I split a string and rejoin it without creating an intermediate list in Python? Say I have something like the following: dest = "\n".join( [line for line in src.split("\n") if line[:1]!="#"] ) (i.e. strip any lines starting with # from the multi-line string src) src is very large, so I'm assuming .split() ...
How do I split a string and rejoin it without creating an intermediate list in Python?
Say I have something like the following: dest = "\n".join( [line for line in src.split("\n") if line[:1]!="#"] ) (i.e. strip any lines starting with # from the multi-line string src) src is very large, so I'm assuming .split() will create a large intermediate list. I can change the list comprehension to a generator e...
[ "buffer = StringIO(src)\ndest = \"\".join(line for line in buffer if line[:1]!=\"#\")\n\nOf course, this really makes the most sense if you use StringIO throughout. It works mostly the same as files. You can seek, read, write, iterate (as shown), etc.\n", "Here's a way to do a general type of split using iterto...
[ 5, 5, 4, 2, 1 ]
[]
[]
[ "generator", "iterator", "python", "string" ]
stackoverflow_0003545620_generator_iterator_python_string.txt
Q: How to create MUC and send messages to existing MUC using Python and XMPP I was wondering if anyone here can provide some code samples on the following scenarios. I'm particularly interested in using xmpppy to do this as I'm already using the library for my app, but other libraries ok too. It is unfortunate that t...
How to create MUC and send messages to existing MUC using Python and XMPP
I was wondering if anyone here can provide some code samples on the following scenarios. I'm particularly interested in using xmpppy to do this as I'm already using the library for my app, but other libraries ok too. It is unfortunate that the xmpppy project website doesn't have any samples on this. Browsing the expert...
[ "While I dont know about specific MUC interface there, xmpppy supports custom messages, so it supports whole XMPP.\nTo join chat, you need to send presence stranza, conn.send(xmpp.Presence(to='{0}/{1}'.format(room, nick)))\nTo send a message to chat: \n stranza = \"<message to='{0}' type='groupchat'><body>{1}</b...
[ 5, 5 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0003528373_python_xmpp_xmpppy.txt
Q: Sending XHTML over Jabber using xmpppy I'm trying to send XHTML (a hyperlink) over Jabber (to Google Talk) using xmpppy, but can't find a good working example... I tried with this: http://intertwingly.net/blog/2007/08/09/Sending-XHTML-over-Jabber But didn't work... any ideas?? Thanks in advance! M A: Heres a nug...
Sending XHTML over Jabber using xmpppy
I'm trying to send XHTML (a hyperlink) over Jabber (to Google Talk) using xmpppy, but can't find a good working example... I tried with this: http://intertwingly.net/blog/2007/08/09/Sending-XHTML-over-Jabber But didn't work... any ideas?? Thanks in advance! M
[ "Heres a nugget I use to construct a XHTML message (thanks to Thomas Perl / Jabberbot.py)\n html_message = \"<b>Test!</b>\"\n\n plain_message = re.sub(r'<[^>]+>', '', html_message)\n message = xmpp.protocol.Message(body=plain_message)\n html = xmpp.Node('html', {'xmlns': 'http://jabber.org/protocol/xhtm...
[ 2 ]
[]
[]
[ "python", "xmpppy" ]
stackoverflow_0003310750_python_xmpppy.txt
Q: Quickly find differences between two large text files I have two 3GB text files, each file has around 80 million lines. And they share 99.9% identical lines (file A has 60,000 unique lines, file B has 80,000 unique lines). How can I quickly find those unique lines in two files? Is there any ready-to-use command li...
Quickly find differences between two large text files
I have two 3GB text files, each file has around 80 million lines. And they share 99.9% identical lines (file A has 60,000 unique lines, file B has 80,000 unique lines). How can I quickly find those unique lines in two files? Is there any ready-to-use command line tools for this? I'm using Python but I guess it's less p...
[ "If order matters, try the comm utility. If order doesn't matter, sort file1 file2 | uniq -u.\n", "I think this is the fastest method (whether it's in Python or another language shouldn't matter too much IMO). \nNotes:\n1.I only store each line's hash to save space (and time if paging might occur)\n2.Because of ...
[ 7, 3, 2, 1, 0 ]
[]
[]
[ "compare", "diff", "file", "python", "text" ]
stackoverflow_0003544331_compare_diff_file_python_text.txt
Q: Django model iterate fields how can I iterate and retrieve all fields of a django model? I know that foo.item._meta.get_all_field_names() brings me all field names. How can I access those fields (incl. their actual values) on a model instance? (Except the normal notation foo.fieldname). I need this in order to bui...
Django model iterate fields
how can I iterate and retrieve all fields of a django model? I know that foo.item._meta.get_all_field_names() brings me all field names. How can I access those fields (incl. their actual values) on a model instance? (Except the normal notation foo.fieldname). I need this in order to build a custom output for my model i...
[ "How about:\ngetattr(foo.__class__, <field_name>)\n\nThis should give you the field object, rather than the value in the given model instance. If you want the value of the field in the given model insance you can call it like this:\ngetattr(foo, <field_name>)\n\n", "This looks ugly but it will work:\nfor each in ...
[ 8, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003546382_django_django_models_python.txt
Q: simultaneous files downloading in python and qt In my program I need to download 3-4 files simultaneously (from different servers which are quite slow). I'm aware of the solution involving python threads or qt threads, but I'm wondering: since it seems to be a quite common task, maybe there's a library which I fee...
simultaneous files downloading in python and qt
In my program I need to download 3-4 files simultaneously (from different servers which are quite slow). I'm aware of the solution involving python threads or qt threads, but I'm wondering: since it seems to be a quite common task, maybe there's a library which I feed with urls and simply receive the files? Thanks in a...
[ "Yes, there is one - pycurl.\nIts not 'simply', since curl is low-level, but it does exactly what you need - you provide it some urls and it downloads then simultaneously and asynchronously.\nimport pycurl\nfrom StringIO import StringIO\n\ndef LoadMulti(urls):\n m = pycurl.CurlMulti()\n handles = {}\n for ...
[ 7, 3 ]
[]
[]
[ "download", "multithreading", "python", "qt" ]
stackoverflow_0003546534_download_multithreading_python_qt.txt
Q: Comparison of js andtemplate tags <script> function compare(profile_id) { {% ifequal '{{profile.id}}' %} selected_sub='selected'; {% endifequal %} } </script> How to compare {{profile.id}} and javascript variable profile_id A: function compare(profile_id){ if (profile_id == {{ profilegroup.subject.id }})...
Comparison of js andtemplate tags
<script> function compare(profile_id) { {% ifequal '{{profile.id}}' %} selected_sub='selected'; {% endifequal %} } </script> How to compare {{profile.id}} and javascript variable profile_id
[ "function compare(profile_id){\n if (profile_id == {{ profilegroup.subject.id }})\n \\\\ do something\n}\n\nKeep in mind, that the script must be in a template, not in some served statically file with scripts (it must be filled with values, to work). Remember also, that you simply have templated script, t...
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003546960_django_django_templates_python.txt
Q: How will Turbogears reach the critical mass of Ruby on Rails? I've been using Turbogears since I have a Python background, but I can't help feeling a pang of jealously seeing all the Ruby on Rails resources available. For example, for a crude comparison of the volume of resources, check out http://www.google.com/t...
How will Turbogears reach the critical mass of Ruby on Rails?
I've been using Turbogears since I have a Python background, but I can't help feeling a pang of jealously seeing all the Ruby on Rails resources available. For example, for a crude comparison of the volume of resources, check out http://www.google.com/trends?q=turbogears%2C+ruby+on+rails What would it take for Turbogea...
[ "Right now, neither Ruby nor Python have enough momentum to afford diversifying webdev community. In my opinion, here's a list of steps that we, as Ruby and Python web developers, should follow:\n\nCollect underpants.\n???\nDefeat PHP and dominate the web.\nSpawn myriad of wonderful web frameworks.\n\nSo, as others...
[ 1, 1, 0 ]
[]
[]
[ "python", "ruby_on_rails", "turbogears" ]
stackoverflow_0003350649_python_ruby_on_rails_turbogears.txt
Q: Write element value to an XML in Python I have a text file containing a key=value pairs. I have another XML file which contains the "key" as "Source" Node and "value" as "Destination Node". <message> <Source>key</Source> <Destination>value</Destination> </message> Suppose, I get a new text file containing t...
Write element value to an XML in Python
I have a text file containing a key=value pairs. I have another XML file which contains the "key" as "Source" Node and "value" as "Destination Node". <message> <Source>key</Source> <Destination>value</Destination> </message> Suppose, I get a new text file containing the same keys but different values, how do I g...
[ "It would be easier to regenerate the XML file than to modify it in place:\nfrom xml.dom.minidom import Document\n\ndoc = Document( )\nroot = doc.createElement( \"root\" )\n\nfor key, value in <some iterator>:\n message = doc.createElement( \"message\" )\n\n source = doc.createElement( \"Source\" )\n sourc...
[ 2 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0003547037_minidom_python_xml.txt
Q: Stripping server side comments in Python In JSP: <%-- Comments removed in server --%> What is the equivalent when I run in Python/Django ?!? I don't want the HTML comments visible in the client side... A: {% comment %} add your comment here :-) {% endcomment %} A: You can use Django template comment block h...
Stripping server side comments in Python
In JSP: <%-- Comments removed in server --%> What is the equivalent when I run in Python/Django ?!? I don't want the HTML comments visible in the client side...
[ "{% comment %}\n\nadd your comment here :-)\n\n{% endcomment %}\n\n", "You can use Django template comment block http://docs.djangoproject.com/en/dev/ref/templates/builtins/#comment\nThey won't be displayed on the client side, but you will see it when editing templates.\n" ]
[ 6, 2 ]
[]
[]
[ "comments", "django", "html", "python" ]
stackoverflow_0003547135_comments_django_html_python.txt
Q: Need help with NetworkX Currently im faced with the following problem: I have a script that searches through a specific directory that contains documents. Each document is assigned a number within the filename. Within each document are numbers that also represent another document (filename). How can I create a web...
Need help with NetworkX
Currently im faced with the following problem: I have a script that searches through a specific directory that contains documents. Each document is assigned a number within the filename. Within each document are numbers that also represent another document (filename). How can I create a web that shows what documents le...
[ "This is a textbook example of a directed graph. You should read the NetworkX tutorial to get a better idea of how to work with them; basically, you need to add all the nodes (points), in this case file numbers, and then add edges between them.\nimport os\nimport networkx as nx\n\ng = nx.DiGraph( )\nfor filename in...
[ 2 ]
[]
[]
[ "graph", "networkx", "nodes", "python" ]
stackoverflow_0003547236_graph_networkx_nodes_python.txt
Q: Lazy infinite sequences in Clojure and Python Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python: Clojure: (def fib-seq (lazy-cat [0 1] (map + fib-seq (rest fib-seq)))) sample usage: (take 5 fib-seq) Python: def fib(): a = b = 1 while Tr...
Lazy infinite sequences in Clojure and Python
Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python: Clojure: (def fib-seq (lazy-cat [0 1] (map + fib-seq (rest fib-seq)))) sample usage: (take 5 fib-seq) Python: def fib(): a = b = 1 while True: yield a a,b = b,a+b sample usage: for i in...
[ "I agree with Pavel, what is intuitive is subjective. Because I'm (slowly) starting to grok Haskell, I can tell what the Clojure code does, even though I've never written a line of Clojure in my life. So I would consider the Clojure line fairly intuitive, because I've seen it before and I'm adapting to a more funct...
[ 36, 14, 12, 6, 5, 2, 2 ]
[ "Think about how would you write lazy-cat with recur in clojure. \n", "(take 5 fibs)\n\nSeems about as intuitive as it could possibly get. I mean, that is exactly what you're doing. You don't even need to understand anything about the language, or even know what language that is, in order to know what should ha...
[ -1, -5 ]
[ "clojure", "python" ]
stackoverflow_0001587412_clojure_python.txt
Q: How to make a selective RNG for a game in Python? This is almost certainly a very novice question, but being as I am a complete novice, I'm fine with that. To put it simply, I'd like to know how to make a loot drop system in a simple game, where when you achieve a certain objective, you have a chance of getting c...
How to make a selective RNG for a game in Python?
This is almost certainly a very novice question, but being as I am a complete novice, I'm fine with that. To put it simply, I'd like to know how to make a loot drop system in a simple game, where when you achieve a certain objective, you have a chance of getting certain objects more than others. If there are any open-...
[ "Here's an easy, lazy way to do it.\nGiven a list of (item,weight) pairs.\nloot = [ (A,20), (B,20), (C,15), (D,10), (E,2), (F,1) ]\n\nNote, the weights don't have to add to anything in particular, they just have to be integers.\nOne-time preparation step.\nchoices = []\nfor item, weight in loot:\n choices.extend...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003535046_python_random.txt
Q: How much overhead do decorators add to Python function calls I've been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions. I've done this by creating a decorator & simply attaching it to any function in the controller I want timed. It's been pointed ou...
How much overhead do decorators add to Python function calls
I've been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions. I've done this by creating a decorator & simply attaching it to any function in the controller I want timed. It's been pointed out however that decorators could add a fair amount of overhead to t...
[ "The overhead added by using a decorator should be just one extra function call.\nThe work being done by the decorator isn't part of the overhead as your alternative is to add the equivalent code to the decorated object.\nSo it's possible that the decorate function takes twice as long to run, but that's because the...
[ 15, 5, 2 ]
[]
[]
[ "decorator", "performance", "python" ]
stackoverflow_0003545690_decorator_performance_python.txt
Q: How to "hide" curse words in a py file? I'm a school teacher who spent the summer writing a vocab training program in python that uses text available from wikipedia and gutenberg. Now all I have to do is figure out a way to filter out curse words so that I can distribute to students. Normally I would just have an ...
How to "hide" curse words in a py file?
I'm a school teacher who spent the summer writing a vocab training program in python that uses text available from wikipedia and gutenberg. Now all I have to do is figure out a way to filter out curse words so that I can distribute to students. Normally I would just have an array (list) of those curse words and do a si...
[ "What you could do is hash the words you want to search for. It makes the filtering a little harder, since you must break the input into words, hash each word, then see if you have a match for that hash.\nTake a look a the documentation for md5()\nYour source code will then just contain hashed words, and there is n...
[ 7, 6, 1, 1, 0 ]
[]
[]
[ "filter", "python" ]
stackoverflow_0003542095_filter_python.txt
Q: Numpy for R user? long-time R and Python user here. I use R for my daily data analysis and Python for tasks heavier on text processing and shell-scripting. I am working with increasingly large data sets, and these files are often in binary or text files when I get them. The type of things I do normally is to apply...
Numpy for R user?
long-time R and Python user here. I use R for my daily data analysis and Python for tasks heavier on text processing and shell-scripting. I am working with increasingly large data sets, and these files are often in binary or text files when I get them. The type of things I do normally is to apply statistical/machine le...
[ "R's strength when looking for an environment to do machine learning and statistics is most certainly the diversity of its libraries. To my knowledge, SciPy + SciKits cannot be a replacement for CRAN.\nRegarding memory usage, R is using a pass-by-value paradigm while Python is using pass-by-reference. Pass-by-value...
[ 12, 11 ]
[]
[]
[ "numpy", "python", "r", "scipy" ]
stackoverflow_0003545057_numpy_python_r_scipy.txt
Q: Google App Engine: how to parallelize downloads using TaskQueue or Async Urlfetch? My Gae application retrieves JSON data from a third party site; given an ID representing the item to download , the item's data on this site is organized in multiple pages so my code has to download chunks of data, page after page, ...
Google App Engine: how to parallelize downloads using TaskQueue or Async Urlfetch?
My Gae application retrieves JSON data from a third party site; given an ID representing the item to download , the item's data on this site is organized in multiple pages so my code has to download chunks of data, page after page, until the data of the last available page is retrieved. My simplified code looks like th...
[ "Use this: http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html\nWhich is simple like so:\ndef handle_result(rpc):\n result = rpc.get_result()\n # ... Do something with result...\n\n# Use a helper function to define the scope of the callback.\ndef create_callback(rpc):\n return l...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0003539240_google_app_engine_python_urlfetch.txt
Q: Unbound error using python's unittest module I would like a seperate class to run all of my tests, and then call that class from main to display the results. Unfortunately, I am getting an error like this: Traceback (most recent call last): File "/home/dhatt/workspace/pyqt_DALA_ServiceTracker/src/Main.py", line...
Unbound error using python's unittest module
I would like a seperate class to run all of my tests, and then call that class from main to display the results. Unfortunately, I am getting an error like this: Traceback (most recent call last): File "/home/dhatt/workspace/pyqt_DALA_ServiceTracker/src/Main.py", line 21, in <module> allsuite = unittest.TestLoade...
[ "The argument to loadTestsFromModule (in your case TestAllSuite), should be a module, not a subclass of unittest.TestCase:\nallsuite = unittest.TestLoader.loadTestsFromModule(TestAllSuite)\n\nFor example, here is a little script which runs all unit tests found in files of the form test_*.py:\nimport unittest\nimpor...
[ 4 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003548678_python_unit_testing.txt
Q: Unable to set custom permissions in Django I'm trying to setup some custom permissions for a Django application, but can't seem to get it working. The official documentation is a little scant, and doesn't mention (at least that I can find) how to actually set a permission? Based on a few 3rd party tutorials I foun...
Unable to set custom permissions in Django
I'm trying to setup some custom permissions for a Django application, but can't seem to get it working. The official documentation is a little scant, and doesn't mention (at least that I can find) how to actually set a permission? Based on a few 3rd party tutorials I found, I've extended the User class and it seems to ...
[ "I tested your code (Python 2.6.2, Django 1.2.1) and everything worked as expected. Can you write a unit test to exercise the same code snippet? \nOn a side note user.has_perm(custom_permission) will not return True. Try user.has_perm('app.is_custom'). \nUpdate\nCode snippet follows:\nIn [1]: from app.models import...
[ 1, 0 ]
[]
[]
[ "django", "permissions", "python" ]
stackoverflow_0003539812_django_permissions_python.txt
Q: Confusing python problem As part of a large python program I have the following code: for arg in sys.argv: if "name=" in arg: name = arg[5:] print(name) elif "uname=" in arg: uname = arg[6:] print(uname) elif "password=" in arg: password = arg...
Confusing python problem
As part of a large python program I have the following code: for arg in sys.argv: if "name=" in arg: name = arg[5:] print(name) elif "uname=" in arg: uname = arg[6:] print(uname) elif "password=" in arg: password = arg[9:] print(passwor...
[ "The elif \"uname=\" is never run because the string \"name=\" is in \"uname=\". Essentially, you are overwriting your name variable.\n>>> \"name=\" in \"uname=\"\nTrue\n\nYou could reorder your ifs so that so that the uname occurs before the name one. \n", "Let's look closely at this.\nif \"name=\" in arg:\n ...
[ 11, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003549240_python.txt
Q: Wxwidgets and Pyqt Is there a similar function PyOnDemandOutputWindow in Pyqt? This function redirect the console output to a separate window. A: It is possible to replace sys.std[out|err] with a wrapper that writes all output to e.g. a QPlainTextEdit. A very basic example: class StdoutWrapper(object): def ...
Wxwidgets and Pyqt
Is there a similar function PyOnDemandOutputWindow in Pyqt? This function redirect the console output to a separate window.
[ "It is possible to replace sys.std[out|err] with a wrapper that writes all output to e.g. a QPlainTextEdit. A very basic example:\nclass StdoutWrapper(object):\n def __init__(self, outwidget):\n self.widget = outwidget\n self.widget.setReadOnly(True) # assuming QPlainTextEdit\n self.widget.h...
[ 4 ]
[]
[]
[ "pyqt", "python", "wxwidgets" ]
stackoverflow_0003548937_pyqt_python_wxwidgets.txt
Q: Need help with a word-packing algorithm I have a list of sub-lists of letters, where the number of letters in each sub-list can vary. The list and sub-lists are ordered. This structure can be used to produce words by choosing a number X, taking a letter from position X in every sub-list and concatenating them in o...
Need help with a word-packing algorithm
I have a list of sub-lists of letters, where the number of letters in each sub-list can vary. The list and sub-lists are ordered. This structure can be used to produce words by choosing a number X, taking a letter from position X in every sub-list and concatenating them in order. If the number X is larger than the leng...
[ "Well, you said you're interested in sub-optimal solutions, so I'll give you one. It depens on the alphabet size. For example, for 26 array size will be little over 100 (regardless of amount of words to encode).\nIt's well-known that if you have two different prime numbers a and b and non-negative integers k and l ...
[ 3, 2, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003498275_algorithm_python.txt
Q: python threading: memory model and visibility Does python threading expose issues of memory visibility and statement reordering as Java does? Since I can't find any reference to a "Python Memory Model" or anything like that, despite the fact that lots of people are writing multithreaded Python code, I'm guessing t...
python threading: memory model and visibility
Does python threading expose issues of memory visibility and statement reordering as Java does? Since I can't find any reference to a "Python Memory Model" or anything like that, despite the fact that lots of people are writing multithreaded Python code, I'm guessing that these gotchas don't exist here. No volatile key...
[ "There is no formal model for Python's threading (hey, after all, there wasn't one for Java's for years... hopefully, one will also eventually be written for Python).\nIn practice, no Python implementation performs any advanced optimization such as statement reordering or temporarily treating shared variables as th...
[ 23 ]
[]
[]
[ "memory_model", "multithreading", "python" ]
stackoverflow_0003549833_memory_model_multithreading_python.txt
Q: Finding the index of a list in a loop I have a simple question. If I have a for loop in python as follows: for name in nameList: How do I know what the index is for the element name? I know I can some something like: i = 0 for name in nameList: i= i + 1 if name == "something": nameList[i] = "somet...
Finding the index of a list in a loop
I have a simple question. If I have a for loop in python as follows: for name in nameList: How do I know what the index is for the element name? I know I can some something like: i = 0 for name in nameList: i= i + 1 if name == "something": nameList[i] = "something else" I just feel there should be a m...
[ "Use the built in function enumerate.\nfor index, name in enumerate(nameList):\n ...\n\n" ]
[ 10 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0003549959_loops_python.txt
Q: Python PyDev, Prevent carriage returns from input() EDIT-4 I've gotten my sitecustomize.py to execute, but it tosses up an error. Here's the code for it. The error is: Error in sitecustomize; set PYTHONVERBOSE for traceback: RuntimeError: maximum recursion depth exceeded while calling a Python object I'm not te...
Python PyDev, Prevent carriage returns from input()
EDIT-4 I've gotten my sitecustomize.py to execute, but it tosses up an error. Here's the code for it. The error is: Error in sitecustomize; set PYTHONVERBOSE for traceback: RuntimeError: maximum recursion depth exceeded while calling a Python object I'm not terribly advanced with Python yet, so I figured I'd comment...
[ "Figured out a hack to make it work locally to my Python installation. In \\Lib\\site-packages\\ make a script called \"sitecustomize.py\", and put this code in it:\noriginal_input = builtins.input\n\ndef input(prompt=''): \n return original_input(prompt).rstrip('\\r')\n\ninput.__doc__ = original_input.__doc__\...
[ 2, 0 ]
[]
[]
[ "carriage_return", "eclipse", "pydev", "python", "windows" ]
stackoverflow_0003515007_carriage_return_eclipse_pydev_python_windows.txt
Q: Project Gutenberg Python problem? I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a hard time with a problem. First, here is my algorithm: Enter a sentence as input -this is called trigger string...
Project Gutenberg Python problem?
I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a hard time with a problem. First, here is my algorithm: Enter a sentence as input -this is called trigger string- Get longest word in trigger string Se...
[ "Given a list L of words, and a target word t,\nany(t.lower()==w.lower() for w in L)\n\ntells you whether L has word t in a case-insensitive way. It's faster, of course, to do\nlt = t.lower()\nany(lt==w.lower() for w in L)\n\nsince Python does not \"hoist\" the constant computation out of the loop and, unless you ...
[ 3, 0 ]
[]
[]
[ "nltk", "python", "regex", "text" ]
stackoverflow_0003549910_nltk_python_regex_text.txt
Q: wxPython or pygame for a simple card game? I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game? A: If all you want is a GUI, wxPython sh...
wxPython or pygame for a simple card game?
I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?
[ "If all you want is a GUI, wxPython should do the trick.\nIf you're looking to add sound, controller input, and take it beyond a simple card game, then you may want to use pygame.\n", "I haven't used wxPython, but Pygame by itself is rather low-level. It allows you to catch key presses, mouse events and draw stuf...
[ 6, 4, 3, 2, 1, 1 ]
[]
[]
[ "playing_cards", "pygame", "python", "wxpython" ]
stackoverflow_0000636990_playing_cards_pygame_python_wxpython.txt
Q: sqlalchemy session not recognizing changes in mysql database (done by other processes) Application consists of: main process (python+sqlalchemy) that periodically check db (sleeps most of the time) child processes that write to db web app that write to db Problem is that the main process session doesn't see...
sqlalchemy session not recognizing changes in mysql database (done by other processes)
Application consists of: main process (python+sqlalchemy) that periodically check db (sleeps most of the time) child processes that write to db web app that write to db Problem is that the main process session doesn't seem to register changes in the db done outside that session. How do ensure it does? (as of now...
[ "\nI am closing and reopening the session every time the process awakes and does its check\n\nSQLAlchemy will not work like this. Changes are tracked in the session. \nsomeobj = Session.query(SomeClass).first()\n\nputs someobj into Session internal cache. When you do someobj.attr = val, it marks the change in the S...
[ 1 ]
[]
[]
[ "database", "mysql", "python", "sqlalchemy" ]
stackoverflow_0003549949_database_mysql_python_sqlalchemy.txt
Q: Data Visualization - showing a Tree in HTML, CSS, JQuery I have a tree based dataset that I want to visualize in my webpage. the data is just your basic tree: there is a parent node, with subnodes and then subnodes of those nodes. I am looking for a package to visualize the data in a tree format. does anyone know ...
Data Visualization - showing a Tree in HTML, CSS, JQuery
I have a tree based dataset that I want to visualize in my webpage. the data is just your basic tree: there is a parent node, with subnodes and then subnodes of those nodes. I am looking for a package to visualize the data in a tree format. does anyone know of one? Google has one, but Im wondering if there ar other alt...
[ "The JavaScript InfoVis Toolkit is pretty sweet for web visualization and animation. Check out the demo page, particularly SpaceTree, RGraph, and HyperTree.\n" ]
[ 6 ]
[]
[]
[ "information_visualization", "jquery", "python" ]
stackoverflow_0003550317_information_visualization_jquery_python.txt
Q: Comparing two objects Is there any way to check if two objects have the same values, other than to iterate through their attributes and manually compare their values? A: @Joe Kington's solutions works if there is a __dict__ (some objects, including builtins, don't have one) and __eq__ works for all values of bot...
Comparing two objects
Is there any way to check if two objects have the same values, other than to iterate through their attributes and manually compare their values?
[ "@Joe Kington's solutions works if there is a __dict__ (some objects, including builtins, don't have one) and __eq__ works for all values of both dicts (a badly written __eq__ mayraise exceptions etc). But it is horribly unpythonic. It doesn't even handle nominal subtypes properly... much less structural subtypes (...
[ 11, 6, 2 ]
[ "object1.__dict__ == object2.__dict__ Should be all you need, I think...\nEdit: vars(object1) == vars(object2) is perhaps a bit more pythonic, though @delnan makes a valid point about objects (e.g. ints) that don't have a __dict__. I disagree that a custom __eq__ is a better approach for simple cases, though... So...
[ -3 ]
[ "python" ]
stackoverflow_0003550336_python.txt
Q: PHP exec() and custom Python module * edit * After reinstalling the module, everything worked fine. I have installed a python module on my webserver. When I do "whereis python" I get following path: python: /usr/bin/python2.4 /usr/bin/python /usr/lib/python2.4 /usr/include/python2.4 /usr/share/man/man1/python.1.gz...
PHP exec() and custom Python module
* edit * After reinstalling the module, everything worked fine. I have installed a python module on my webserver. When I do "whereis python" I get following path: python: /usr/bin/python2.4 /usr/bin/python /usr/lib/python2.4 /usr/include/python2.4 /usr/share/man/man1/python.1.gz Later when I check my modules path, it ...
[ "Should you be doing\nexec(\"/usr/bin/python /usr/lib/python2.4/site-packages/MyModule/myModule script.py -v pixfx.xml 2>&1\", $output, $return);\n\nOR \nexec(\"/usr/bin/python/python /usr/lib/python2.4/site-packages/MyModule/myModule script.py -v pixfx.xml 2>&1\", $output, $return);\n\n", "You might find it usef...
[ 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003548919_php_python.txt
Q: overlapping segments i have a huge list of two-element tuples which are coordinates of segments (start, end). In this way in a list below list = [ (1,4), (2, 3), (10, 20), (18, 45) ] there are 4 segments with their start and end localization. I would like to remove segments that overlap. I expect to have a list ...
overlapping segments
i have a huge list of two-element tuples which are coordinates of segments (start, end). In this way in a list below list = [ (1,4), (2, 3), (10, 20), (18, 45) ] there are 4 segments with their start and end localization. I would like to remove segments that overlap. I expect to have a list like this as a result: lis...
[ "There's a data structure designed for this exact purpose (efficient identification of interval overlaps), it's called interval tree.\n", "First, sort the list (for comparison first use start point end then end point). Then go through list and remove all the tuples which are overlapping the previous element in th...
[ 5, 3 ]
[]
[]
[ "algorithm", "comparison", "list", "python" ]
stackoverflow_0003550768_algorithm_comparison_list_python.txt
Q: Is there an analog of Python's vars() method in Ruby? In Python there is vars() method which returns a dictionary of names of local variables as keys, and their values, so it is possible to do something like this: a = 1 b = 2 "%(a)s %(b)s" % vars() Is there an analog of vars() in Ruby? The closest construct I can...
Is there an analog of Python's vars() method in Ruby?
In Python there is vars() method which returns a dictionary of names of local variables as keys, and their values, so it is possible to do something like this: a = 1 b = 2 "%(a)s %(b)s" % vars() Is there an analog of vars() in Ruby? The closest construct I can think of is local_variables.inject({}) {|res,var| res[var...
[ "The ruby equivalent of what you are doing is just\n\"#{a} #{b}\"\n\nIs there another reason you need vars()?\n", "You could implement it something like this, but it's not very pretty. And as gnibbler pointed out, it's just easier to use interpolation. About the only advantage I see to doing something like this...
[ 1, 1 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0003549006_python_ruby.txt
Q: Recovery Group with Exchange 2003 and Python Is there a way to create a recovery group in exchange 2003 with python? Maybe CDOEXM or VBScript? But I have been unsuccessful in finding any sample code. Any ideas? A: Going to just install powershell on the machine and use that.
Recovery Group with Exchange 2003 and Python
Is there a way to create a recovery group in exchange 2003 with python? Maybe CDOEXM or VBScript? But I have been unsuccessful in finding any sample code. Any ideas?
[ "Going to just install powershell on the machine and use that.\n" ]
[ 0 ]
[]
[]
[ "exchange_server", "python", "vbscript" ]
stackoverflow_0003478001_exchange_server_python_vbscript.txt
Q: Calling a midlet jar for retrieve data into a python code I have a JAR file midlet JAR file, which returns an INT value according to some input data... Problem is, i need to get that INT value by calling the jar file via some python code (and send the required input data to get the result data). How can i access ...
Calling a midlet jar for retrieve data into a python code
I have a JAR file midlet JAR file, which returns an INT value according to some input data... Problem is, i need to get that INT value by calling the jar file via some python code (and send the required input data to get the result data). How can i access the functions and variables of a midlet JAR file? I try to deco...
[ "Jython has native access to Java code, but I'm not sure if it supports MIDP.\n", "I don't know much about J2ME, but you might be able to use Python's pipe facility to invoke a method in the JAR, e.g. java -jar myjar.jar org.package.Main param1. See also the java command line options for your OS.\nAddendum: The e...
[ 0, 0, 0 ]
[]
[]
[ "java", "java_me", "python" ]
stackoverflow_0002122874_java_java_me_python.txt
Q: how to substitute part of a string in python? How to replace a set of characters inside another string in Python? Here is what I'm trying to do: let's say I have a string 'abcdefghijkl' and want to replace the 2-d from the end symbol (k) with A. I'm getting an error: >>> aa = 'abcdefghijkl' >>> print aa[-2] k >>> ...
how to substitute part of a string in python?
How to replace a set of characters inside another string in Python? Here is what I'm trying to do: let's say I have a string 'abcdefghijkl' and want to replace the 2-d from the end symbol (k) with A. I'm getting an error: >>> aa = 'abcdefghijkl' >>> print aa[-2] k >>> aa[-2]='A' Traceback (most recent call last): Fi...
[ "If it's always the same position you're replacing, you could do something like:\n>>> s = s[0:-2] + \"A\" + s[-1:]\n>>> print s\nabcdefghijAl\n\nIn the general case, you could do:\n>>> rindex = -2 #Second to the last letter\n>>> s = s[0:rindex] + \"A\" + s[rindex+1:]\n>>> print s\nabcdefghijAl\n\nEdit: The very gen...
[ 18, 11, 5, 5, 3 ]
[]
[]
[ "python", "string", "substitution", "substring" ]
stackoverflow_0003550327_python_string_substitution_substring.txt
Q: How to show list of deleted files in windows file system I am wondering if it is possible to compile a list of deleted files on a windows file system, FAT or NTFS. I do not need to actually recover the files, only have access to their name and any other accessible time (time deleted, created etc). Even if I can r...
How to show list of deleted files in windows file system
I am wondering if it is possible to compile a list of deleted files on a windows file system, FAT or NTFS. I do not need to actually recover the files, only have access to their name and any other accessible time (time deleted, created etc). Even if I can run a cmd line tool to achieve this it would be acceptable. The...
[ "This is a very complex task. I woudl look at open-source forensic tools.\nYou also should analyze the recylcing bin ( not completly deleted file )\nFor FAT you will not be able to get the first character of a deleted file.\nFor some deleted files the metadata will be gone. \nNTFS is much more complex and time cons...
[ 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003190226_python_windows.txt
Q: Python: create a distribution from a list based on number of items that fall within certain ranges I tagged this question with poisson as I am not sure if it will be helpful in this case. I need to create a distribution (probably formatted as an image in the end) from a list of data. For example: data = [1, 2, ...
Python: create a distribution from a list based on number of items that fall within certain ranges
I tagged this question with poisson as I am not sure if it will be helpful in this case. I need to create a distribution (probably formatted as an image in the end) from a list of data. For example: data = [1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 10, 10, 10, 22, 30, 30, 35, 46, 58, 59, 59] such that the data can be used t...
[ "If data is always sorted, a compact approach might be:\nimport itertools as it\n\nd = [k+1 for k, L in\n ((k, len(list(g))) for k, g in it.groupby(data,key=lambda x:x//10))\n if L>=3]\n\nIf data isn't sorted, or if you don't know, use sorted(data) as the first argument to itertools.groupby, instead of ...
[ 4, 4, 0 ]
[]
[]
[ "distribution", "poisson", "python" ]
stackoverflow_0003550264_distribution_poisson_python.txt
Q: how to 'marry' two strings in python? What would be a smart way to mix two strings in python? I need something to insert one string into another one with specified (default=1) intervals: >>> aa = 'abcdefghijkl' >>> bb = mix(aa) >>> bb 'a b c d e f g h i j k l ' >>> cc = mix(bb,'\n',8) >>> print cc a b c d e f g h...
how to 'marry' two strings in python?
What would be a smart way to mix two strings in python? I need something to insert one string into another one with specified (default=1) intervals: >>> aa = 'abcdefghijkl' >>> bb = mix(aa) >>> bb 'a b c d e f g h i j k l ' >>> cc = mix(bb,'\n',8) >>> print cc a b c d e f g h i j k l Is there an elegant way to writ...
[ "def mix(s, c=' ', n=1):\n return ''.join(s[i:i+n]+c for i in range(0,len(s),n))\n\n", "From the itertools there is the 'grouper' recipe, shown here:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return itertools.izip_longes...
[ 6, 2, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003550426_python_string.txt
Q: Potential errors with my makeValidFilename function? It is inspired by "How to make a valid Windows filename from an arbitrary string?", I've written a function that will take arbitrary string and make it a valid filename. My function should technically be an answer to this question, but I want to make sure I've n...
Potential errors with my makeValidFilename function?
It is inspired by "How to make a valid Windows filename from an arbitrary string?", I've written a function that will take arbitrary string and make it a valid filename. My function should technically be an answer to this question, but I want to make sure I've not done anything stupid, or overlooked anything, before po...
[ "One point I've noticed: Under NTFS, some files can not be created in specific directories.\nE.G. $Boot in root \n" ]
[ 1 ]
[]
[]
[ "file_rename", "filesystems", "python", "sanitization" ]
stackoverflow_0001902926_file_rename_filesystems_python_sanitization.txt
Q: How to make wx.TextEntryDialog larger and resizable I create a wx.TextEntryDialog as follows: import wx dlg = wx.TextEntryDialog(self, 'Rules:', 'Edit rules', style=wx.TE_MULTILINE|wx.OK|wx.CANCEL) dlg.SetValue(self.rules_text.Value) if dlg.ShowModal() == wx.ID_OK: … This results in...
How to make wx.TextEntryDialog larger and resizable
I create a wx.TextEntryDialog as follows: import wx dlg = wx.TextEntryDialog(self, 'Rules:', 'Edit rules', style=wx.TE_MULTILINE|wx.OK|wx.CANCEL) dlg.SetValue(self.rules_text.Value) if dlg.ShowModal() == wx.ID_OK: … This results in a dialog box that is too small for my needs, and that is...
[ "Time to learn how to write your own dialogs! ;-)\nThe built-in dialogs such as TextEntryDialog are only for the most basic programs. If you need much customization, you need to write your own dialogs.\nHere's an example, this should work for you.\nimport wx\n\nclass TextEntryDialog(wx.Dialog):\n def __init__(s...
[ 12 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0003551249_python_wxpython_wxwidgets.txt
Q: how to call methods within a class in python - TypeError problem I have a python class and within the class I call 2 different methods from one of the other methods. One works and one gives me a TypeError: get_doms() takes exactly 1 argument (2 given) : def start(self,cursor): recs = self.get_recs(cursor) ...
how to call methods within a class in python - TypeError problem
I have a python class and within the class I call 2 different methods from one of the other methods. One works and one gives me a TypeError: get_doms() takes exactly 1 argument (2 given) : def start(self,cursor): recs = self.get_recs(cursor) # No errors here doms = self.get_doms(cursor) # I get a TypeErro...
[ "I can't reproduce the error you mention. I think the code is okay. But I suggest do not use cursor._rows because the _rows attribute is a private attribute. Private attributes are an implementation detail -- they are not guaranteed to be there in future versions of cursor. You can achieve what you want without it,...
[ 0, 0 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0003551464_methods_python.txt
Q: how to change a variable value in a python file from a python script I currently have a python file with a bunch of global variables with values. I want to change these values permanently from a separate python script. I've tried setattr and such but it doesnt seem to work. Is there a way to do this? A: The shor...
how to change a variable value in a python file from a python script
I currently have a python file with a bunch of global variables with values. I want to change these values permanently from a separate python script. I've tried setattr and such but it doesnt seem to work. Is there a way to do this?
[ "The short answer is: don't. It won't be worth the trouble.\nIt sounds like you are trying to create a configuration file and then have your application update it. You should try using ConfigParser, a built-in module that can read and write configuration files for you with limited hassle: http://docs.python.org/lib...
[ 7, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003551577_python.txt
Q: Django, automatic HTML "sanitizing" when putting HTML to template, how to stop it? I'm kind of confused by this because it seems that Django templates have optional HTML filters but this seems to be happening automatically.. I am making this demo app where the user will do an action that calls a python script whic...
Django, automatic HTML "sanitizing" when putting HTML to template, how to stop it?
I'm kind of confused by this because it seems that Django templates have optional HTML filters but this seems to be happening automatically.. I am making this demo app where the user will do an action that calls a python script which retrieves a url, I then want to display this in a new window.. its all fine except whe...
[ "Use the safe filter:\n{{ myvariable|safe }}\n\nIf you need large parts of your template treated like this (that is, if you find yourself using |safe over and over), you can disable the autoescaping whole-sale:\n{% autoescape off %}\nblah {{myvariable}} blah {{myothervariable}}\n{% endautoescape %}\n\n", "Take a ...
[ 9, 5, 2 ]
[]
[]
[ "django", "html", "html_sanitizing", "python", "templates" ]
stackoverflow_0003551599_django_html_html_sanitizing_python_templates.txt
Q: python: comparing two strings I would like to know if there is a library that will tell me approximately how similar two strings are I am not looking for anything specific, but in this case: a = 'alex is a buff dude' b = 'a;exx is a buff dud' we could say that b and a are approximately 90% similar. Is there a lib...
python: comparing two strings
I would like to know if there is a library that will tell me approximately how similar two strings are I am not looking for anything specific, but in this case: a = 'alex is a buff dude' b = 'a;exx is a buff dud' we could say that b and a are approximately 90% similar. Is there a library which can do this?
[ "import difflib\n\n>>> a = 'alex is a buff dude'\n>>> b = 'a;exx is a buff dud'\n>>> difflib.SequenceMatcher(None, a, b).ratio()\n\n0.89473684210526316\n\n", "http://en.wikipedia.org/wiki/Levenshtein_distance\nThere are a few libraries on pypi, but be aware that this is expensive, especially for longer strings.\n...
[ 21, 7, 6, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003551423_python_string.txt
Q: combine list elements How can I merge/combine two or three elements of a list. For instance, if there are two elements, the list 'l' l = [(a,b,c,d,e),(1,2,3,4,5)] is merged into [(a,1),(b,2),(c,3),(d,4),(e,5)] however if there are three elements l = [(a,b,c,d,e),(1,2,3,4,5),(I,II,II,IV,V)] the list is converte...
combine list elements
How can I merge/combine two or three elements of a list. For instance, if there are two elements, the list 'l' l = [(a,b,c,d,e),(1,2,3,4,5)] is merged into [(a,1),(b,2),(c,3),(d,4),(e,5)] however if there are three elements l = [(a,b,c,d,e),(1,2,3,4,5),(I,II,II,IV,V)] the list is converted into [(a,1,I),(b,2,II),(...
[ "Use zip:\nl = [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)]\nprint zip(*l)\n\nResult:\n\n[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]\n\n" ]
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0003551797_python.txt
Q: Python to control macros in mutliple instances of Excel How Do control with python multiple instances of Excel. This is not read/write, but more running macros on different workbooks. Ex: Excel.exe running Book1.xls. has mac1 Excel.exe running Book2.xls. has mac2. I got one instance to work, this first instance,...
Python to control macros in mutliple instances of Excel
How Do control with python multiple instances of Excel. This is not read/write, but more running macros on different workbooks. Ex: Excel.exe running Book1.xls. has mac1 Excel.exe running Book2.xls. has mac2. I got one instance to work, this first instance, which use 2003. I could not figure out the other instance w...
[ "Unfortunately you cannot control which instance you get back when grabbing things from the ROT (running object table.) Only the first instance of an application will register itself.\nhttp://support.microsoft.com/kb/238975\nHowever, each document is registered in the ROT so in your case you may be able to find the...
[ 1 ]
[]
[]
[ "excel", "ms_office", "python", "vba" ]
stackoverflow_0003551893_excel_ms_office_python_vba.txt
Q: inconsistency when switching between timezones in python I have a datetime object created like this: tm = datetime.datetime.strptime('2010 Aug 04 14:15:16', '%Y %b %d %H:%M:%S') >>> tm datetime.datetime(2010, 8, 4, 14, 15, 16) I then set the timezone like this: tm.replace(tzinfo=pytz.timezone('UTC')) >>> tm datet...
inconsistency when switching between timezones in python
I have a datetime object created like this: tm = datetime.datetime.strptime('2010 Aug 04 14:15:16', '%Y %b %d %H:%M:%S') >>> tm datetime.datetime(2010, 8, 4, 14, 15, 16) I then set the timezone like this: tm.replace(tzinfo=pytz.timezone('UTC')) >>> tm datetime.datetime(2010, 8, 4, 14, 15, 16, tzinfo=<UTC>) Eventually...
[ "Yes, this is why you use .astimezone and not .replace when you have a datetime with a timezone. Using .astimezone gives the timezone a chance to adjust for things like daylight savings. Only use .replace to give a naïve datetime a tzinfo object.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003551085_python.txt
Q: Custom classes in python: does a method HAVE to be called with an instance? I'm processing data from an application that has a few quirks in how it keeps time. One of the simpler quirks is that it uses "day of year" (Jan 1 is 1, Febuary 1 is 32, etc) instead of month + day. So I want to make my own date class that...
Custom classes in python: does a method HAVE to be called with an instance?
I'm processing data from an application that has a few quirks in how it keeps time. One of the simpler quirks is that it uses "day of year" (Jan 1 is 1, Febuary 1 is 32, etc) instead of month + day. So I want to make my own date class that inherits from the default datetime class and has a few custom methods. I'm calli...
[ "You want @classmethod decorator. Then your method gets the class instead of object instance as the first argument. It's customary to call it cls:\n@classmethod\ndef from_file(cls, f):\n return cls(f.read())\n\n", "The OP's \"settled on\" solution has serious bugs (self.date needs to be called, not just mentio...
[ 8, 2 ]
[]
[]
[ "class", "datetime", "instance", "python" ]
stackoverflow_0003552045_class_datetime_instance_python.txt
Q: python tkinter listbox: adding items At program startup, I add some items to my listbox like this: for widget in WidgetNames: listbox.insert(0, widget) WidgetNames is obviously a list of some items, e.g. "Button" and "Canvas". The thing is, the listbox doesn't show the items that are added with above code. Ho...
python tkinter listbox: adding items
At program startup, I add some items to my listbox like this: for widget in WidgetNames: listbox.insert(0, widget) WidgetNames is obviously a list of some items, e.g. "Button" and "Canvas". The thing is, the listbox doesn't show the items that are added with above code. However, for widget in WidgetNames: lis...
[ "The code you're showing is not the problem -- it must be some other code which you are not showing. Please try to reproduce your problem in as small a compass as possible and edit your answer to include that minimal code. Here's a small script to show that the code you show is actually OK:\nfrom Tkinter import *\...
[ 4 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0003552446_python_python_3.x_tkinter.txt
Q: How to 3DES encrypt in Python using the M2Crypto wrapper? I have a working test of a hardware device that uses RSA encryption, in Python using M2Crypto. Now I need to test a similar device that uses 3DES encryption. But I can't figure out how to use M2Crypto to do triple DES encryption. I know it should be possi...
How to 3DES encrypt in Python using the M2Crypto wrapper?
I have a working test of a hardware device that uses RSA encryption, in Python using M2Crypto. Now I need to test a similar device that uses 3DES encryption. But I can't figure out how to use M2Crypto to do triple DES encryption. I know it should be possible from this chart. But unfortunately the documentation of M2...
[ "See here. There is reference for the following DES ciphers : 'des_ede_ecb', 'des_ede_cbc', 'des_ede_cfb', 'des_ede_ofb', 'des_ede3_ecb', 'des_ede3_cbc', 'des_ede3_cfb', 'des_ede3_ofb'.\nThe homepage seems to be here now.\n", "The following code worked for me:\nwith open(keyfile, 'rb') as f:\n key = f.read()\n...
[ 3, 0 ]
[]
[]
[ "3des", "cryptography", "encryption", "m2crypto", "python" ]
stackoverflow_0003541763_3des_cryptography_encryption_m2crypto_python.txt
Q: Passing a password to KLOG from within a script, using `subprocess.POPEN` A series of applications I'm writing require that the user be able to read from a filesystem with KLOG authentication. Some functions require the user to have KLOG tokens (i.e., be authenticated) and others don't. I wrote a small Python deco...
Passing a password to KLOG from within a script, using `subprocess.POPEN`
A series of applications I'm writing require that the user be able to read from a filesystem with KLOG authentication. Some functions require the user to have KLOG tokens (i.e., be authenticated) and others don't. I wrote a small Python decorator so that I can refactor the "you must be KLOGed" functionality within my m...
[ "Apparently, your script (or something else it's spawning later) and the subprocess running klog are \"competing\" for the /dev/tty -- and the subprocess is losing (after all, you're not calling the wait method of the object returned from subprocess.Popen, to ensure you wait until it terminates before continuing, s...
[ 2 ]
[]
[]
[ "python", "subprocess", "system_calls" ]
stackoverflow_0003552573_python_subprocess_system_calls.txt
Q: What encoding do normal python strings use? i know that django uses unicode strings all over the framework instead of normal python strings. what encoding are normal python strings use ? and why don't they use unicode? A: In Python 2: Normal strings (Python 2.x str) don't have an encoding: they are raw data. In...
What encoding do normal python strings use?
i know that django uses unicode strings all over the framework instead of normal python strings. what encoding are normal python strings use ? and why don't they use unicode?
[ "In Python 2: Normal strings (Python 2.x str) don't have an encoding: they are raw data. \nIn Python 3: These are called \"bytes\" which is an accurate description, as they are simply sequences of bytes, which can be text encoded in any encoding (several are common!) or non-textual data altogether.\nFor representin...
[ 33, 14, 4, 2, 1 ]
[ "Before Python 3.0, string encoding was ascii by default, but could be changed. Unicode string literals were u\"...\". This was silly.\n" ]
[ -2 ]
[ "encoding", "python" ]
stackoverflow_0003547534_encoding_python.txt
Q: PyGtk - TreeView and selected row I have a TreeView and when I click in it, i receive the error: Traceback (most recent call last): File "pyparty.py", line 76, in get_selected_user self.selected_user = tree_model.get_value(tree_iter, 0) TypeError: iter must be a GtkTreeIter It just happen for the first clic...
PyGtk - TreeView and selected row
I have a TreeView and when I click in it, i receive the error: Traceback (most recent call last): File "pyparty.py", line 76, in get_selected_user self.selected_user = tree_model.get_value(tree_iter, 0) TypeError: iter must be a GtkTreeIter It just happen for the first click. After that it works fine. I don't kn...
[ "I was using the wrong signal. This is the right one:\nself.tree_view.connect('cursor-changed', self.get_selected_user)\n\nThank you\n" ]
[ 6 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0003552668_gtk_gtktreeview_pygtk_python.txt
Q: how do i get python's mechanize to stop following meta refresh redirects? I have a script which gets a webpage with a meta refresh. I need to parse the retrieved page but mechanize seems to follow the redirect. How do I get it to stop following it? A: You can simply disable it import mechanize browser = mechaniz...
how do i get python's mechanize to stop following meta refresh redirects?
I have a script which gets a webpage with a meta refresh. I need to parse the retrieved page but mechanize seems to follow the redirect. How do I get it to stop following it?
[ "You can simply disable it\nimport mechanize\nbrowser = mechanize.Browser()\nbrowser.set_handle_refresh(False)\n\n" ]
[ 4 ]
[]
[]
[ "mechanize", "meta_tags", "python", "redirect", "refresh" ]
stackoverflow_0003553182_mechanize_meta_tags_python_redirect_refresh.txt
Q: Python parser script layout I'm writing a simple Python parser, where I loop over each line in a file, and prosess it further if the right conditions are met. My short start: def identify(hh_line): if(re.match(regex.new_round, hh_line)): m = re.match(regex.new_round, hh_line) # ...
Python parser script layout
I'm writing a simple Python parser, where I loop over each line in a file, and prosess it further if the right conditions are met. My short start: def identify(hh_line): if(re.match(regex.new_round, hh_line)): m = re.match(regex.new_round, hh_line) # insert into psql ... ...
[ "First of all, it's redundant to run the match twice - instead, run it, store the result, and branch off of that:\nm = re.match(regex.new_round, hh_line)\nif m:\n # ...\n\nNext, if you have a bunch of regex -> processing combinations, you might instead make a dict of regex -> function mappings, and then just ite...
[ 3 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003553234_parsing_python.txt
Q: Do you use data mappers with MongoDB? I've been diving into MongoDB with kind help of MongoKit and MongoEngine, but then I started thinking whether the data mappers are necessary here. Both mappers I mentioned enable one to do simple things without any effort. But is any effort required to do simple CRUD? It appea...
Do you use data mappers with MongoDB?
I've been diving into MongoDB with kind help of MongoKit and MongoEngine, but then I started thinking whether the data mappers are necessary here. Both mappers I mentioned enable one to do simple things without any effort. But is any effort required to do simple CRUD? It appears to me that in case of NoSQL the mappers ...
[ "We are running a production site using Mongodb for the backend (no direct queries to Mongo, we have a search layer in between). We wrote our own business / object layer, i suppose it just seemed natural enough for the programmers to write in the custom logic. We did separate the database and business layers, but...
[ 1 ]
[]
[]
[ "mongodb", "mongoengine", "mongokit", "orm", "python" ]
stackoverflow_0003533064_mongodb_mongoengine_mongokit_orm_python.txt
Q: How can I get a response with XMPP client in Python I'm using XMPP in Python, and I can send messages, but how can I receive? A: I must register a handler and process: def messageCB(sess,mess): print 'MESSAGE'*100 nick=mess.getFrom().getResource() text=mess.getBody() #print mess,nick print te...
How can I get a response with XMPP client in Python
I'm using XMPP in Python, and I can send messages, but how can I receive?
[ "I must register a handler and process:\ndef messageCB(sess,mess):\n print 'MESSAGE'*100\n nick=mess.getFrom().getResource()\n text=mess.getBody()\n #print mess,nick\n print text\n\nclient.RegisterHandler('message',messageCB)\n\nwhile 1:\n client.Process(1)\n\n", "Good post. I notice this code s...
[ 2, 0 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0003121518_python_xmpp_xmpppy.txt
Q: Python: Upload a photo to photobucket Can a Python script upload a photo to photo bucket and then retrieve the URL for it? Is so how? I found a script at this link: http://www.democraticunderground.com/discuss/duboard.php?az=view_all&address=240x677 But I just found that confusing. many thanks, Phil A: Yes, you ...
Python: Upload a photo to photobucket
Can a Python script upload a photo to photo bucket and then retrieve the URL for it? Is so how? I found a script at this link: http://www.democraticunderground.com/discuss/duboard.php?az=view_all&address=240x677 But I just found that confusing. many thanks, Phil
[ "Yes, you can. Photobucket has a well-documented API, and someone wrote a wrapper around it.\nDownload the it and put it into your Python path, then download httplib2 (you can use easy_install or pip for this one).\nThen, you have to request a key for the Photobucket API.\nIf you did everything right, you can write...
[ 8, 0 ]
[]
[]
[ "photobucket", "python" ]
stackoverflow_0003552102_photobucket_python.txt
Q: Installing lxml when Codespeak.net is down Codespeak.net is down and something, somewhere in my buildout wants to easy_install lxml from it, despite me boopstrapping with pip, having it installed already and removing it from my buildout files. How else can I get round this? A: A first way is to look at your buil...
Installing lxml when Codespeak.net is down
Codespeak.net is down and something, somewhere in my buildout wants to easy_install lxml from it, despite me boopstrapping with pip, having it installed already and removing it from my buildout files. How else can I get round this?
[ "A first way is to look at your buildout directory: you probably have an eggs/ subdirectory in there. Put your existing lxml egg in that directory and buildout should pick it up.\nA second, slightly more permanent, way is to tell buildout to use a cache directory. In your home dir, make a \".buildout\" directory w...
[ 1, 1 ]
[]
[]
[ "buildout", "easy_install", "lxml", "python" ]
stackoverflow_0003549284_buildout_easy_install_lxml_python.txt
Q: With python: intervals at x:00 repeat How do I sched a repeat timer for 5 min intervals. Which fire at 00 seconds, then repeat at 00. Ok, not hard real-time but as close as possible with sys lags. Trying to avoid a build up in lags and get near 00. Lang: Python, OS: WinXP x64 System has 25ms resolution. Any c...
With python: intervals at x:00 repeat
How do I sched a repeat timer for 5 min intervals. Which fire at 00 seconds, then repeat at 00. Ok, not hard real-time but as close as possible with sys lags. Trying to avoid a build up in lags and get near 00. Lang: Python, OS: WinXP x64 System has 25ms resolution. Any code would be helpful, tia
[ "I don't know how to do it any more accurately than with threading.Timer. It's \"one-shot\", but that just means the function you schedule that way must immediately re-schedule itself for another 300 seconds later, first thing. (You can add accuracy by measuring the exact time with time.time each time and varying...
[ 2, 0 ]
[]
[]
[ "ctime", "python", "time", "win64" ]
stackoverflow_0003553340_ctime_python_time_win64.txt
Q: How to display a table of images in Django template system? I'm developing a Django-based site for fun, and wondered if anyone knows how to solve this problem. I want to display images in a table, like a gallery, inside a template. Does anyone know how to do this? I've tried a multidimensional list, but I am getti...
How to display a table of images in Django template system?
I'm developing a Django-based site for fun, and wondered if anyone knows how to solve this problem. I want to display images in a table, like a gallery, inside a template. Does anyone know how to do this? I've tried a multidimensional list, but I am getting nowhere.
[ "I believe question is more CSS related than Django.\nAre all your images the same size? If yes, just float all of them and let the bounding div break the images. Your template would looks like something like this (ignore the inline CSS!):\n<div style=\"width:400px\">\n{% for image in image_list%}\n <div style=\...
[ 4, 2, 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003544449_django_django_templates_python.txt
Q: How do I loop this program? Once the program prints, it shuts down. How do I make it returns to the top of the code so that it loops, indefinitely asking for the users name? code: from time import sleep name = raw_input ("Please enter your name: ") print "Hello", name, "- good to see you!" sleep(2.00) pseudo-co...
How do I loop this program?
Once the program prints, it shuts down. How do I make it returns to the top of the code so that it loops, indefinitely asking for the users name? code: from time import sleep name = raw_input ("Please enter your name: ") print "Hello", name, "- good to see you!" sleep(2.00) pseudo-code: from time import sleep A nam...
[ "while True:\n # do something\n # do something else\n # do more things\n\nFor your specific example:\nfrom time import sleep\n\nwhile True:\n name = raw_input (\"Please enter your name: \")\n\n print \"Hello\", name, \"- good to see you!\"\n sleep(2.00)\n\nThe general format of this loop is as fol...
[ 6, 5, 0 ]
[ "two methods can done.\n1. use \"do-while\"\n2. use \"while(true) and if to break\"\n" ]
[ -3 ]
[ "loops", "python" ]
stackoverflow_0003553307_loops_python.txt
Q: Appengine datastore not updating multiple records votergroup = db.GqlQuery("SELECT * FROM Voter WHERE lastname = :1", 'AGEE') for voter in votergroup: voter.email = 'testemail@testemail.com' db.put(votergroup) The above code doesn't seem to be updating the records as it shows in the appen...
Appengine datastore not updating multiple records
votergroup = db.GqlQuery("SELECT * FROM Voter WHERE lastname = :1", 'AGEE') for voter in votergroup: voter.email = 'testemail@testemail.com' db.put(votergroup) The above code doesn't seem to be updating the records as it shows in the appengine documentation. I also tried using a query object ...
[ "You need to call fetch() on the query you create with db.Query() to have it return a list of entities. You can then call put(list_of_entities) to persist them all. That looks like this:\nvoters = db.GqlQuery(\"SELECT * FROM Voter WHERE lastname = :1\", 'AGEE').fetch(10)\n\nfor voter in voters:\n voter.email = ...
[ 3, 1 ]
[]
[]
[ "datastore", "google_app_engine", "python" ]
stackoverflow_0003553481_datastore_google_app_engine_python.txt
Q: I have a file > 1g, I want to split it into files with 100k lines each I want to do this in python but I'm stumped. I wont be able to load the whole file into ram without things becoming unstable, so I want to read it line by line... Any advice would be appreciated. A: If you do absolutely need to split the file...
I have a file > 1g, I want to split it into files with 100k lines each
I want to do this in python but I'm stumped. I wont be able to load the whole file into ram without things becoming unstable, so I want to read it line by line... Any advice would be appreciated.
[ "If you do absolutely need to split the file, why not just use the *nix split utility?\nhttp://ss64.com/bash/split.html\nsplit -l 100000 inputfile\n\n", "One idea could be the following:\nimport itertools\n\nwith open('the1gfile.txt') as inf:\n for i in itertools.count():\n with open('outfile%d.txt' % i, 'w')...
[ 16, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003553503_python.txt
Q: Get data into sqlite from yahoo finance I trying to get yahoo prices into sqlite... I have the code below, but cant get the data into ipull [] then into sqlite... from urllib import urlopen import win32com.client as win32 import sqlite3 RANGE = range(3, 8) COLS = ('TICKER', 'PRICE', 'Vol') URL = 'http:/...
Get data into sqlite from yahoo finance
I trying to get yahoo prices into sqlite... I have the code below, but cant get the data into ipull [] then into sqlite... from urllib import urlopen import win32com.client as win32 import sqlite3 RANGE = range(3, 8) COLS = ('TICKER', 'PRICE', 'Vol') URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1v' T...
[ "You declare ipull[], but never assign it.\n" ]
[ 1 ]
[]
[]
[ "python", "sqlite", "yahoo_finance" ]
stackoverflow_0003553421_python_sqlite_yahoo_finance.txt
Q: Why are the python.org OS X installers built with gcc-4.0? In answering SO question 3500638, Ned Deily states that the Apple-supplied Pythons (2.5.4 and 2.6.5) are both built with gcc-4.2. However, all three of the python.org OS X Pythons (2.6.5, 2.7, 3.1.2) are built using gcc-4.0. Questions Why are the python....
Why are the python.org OS X installers built with gcc-4.0?
In answering SO question 3500638, Ned Deily states that the Apple-supplied Pythons (2.5.4 and 2.6.5) are both built with gcc-4.2. However, all three of the python.org OS X Pythons (2.6.5, 2.7, 3.1.2) are built using gcc-4.0. Questions Why are the python.org Pythons (2.6.5, 2.7, 3.1.2) built using gcc-4.0? What are th...
[ "It may have to do with the fact that the Apple-supplied Python (2.5.1) for OS X 10.5 is built with gcc-4.0 -- after all, python.org's DMGs support both OS X 10.5 and 10.6 (not sure if they also support older versions of the OS).\n", "\nFor some time now, the python.org OS X installers have been built with the re...
[ 3, 2, 1 ]
[]
[]
[ "gcc", "macos", "python" ]
stackoverflow_0003552307_gcc_macos_python.txt
Q: Transform tuple to dict How can I transform tuple like this: ( ('a', 1), ('b', 2) ) to dict: { 'a': 1, 'b': 2 } A: Dict constructor can do this for you. dict(( ('a', 1), ('b', 2) ))
Transform tuple to dict
How can I transform tuple like this: ( ('a', 1), ('b', 2) ) to dict: { 'a': 1, 'b': 2 }
[ "Dict constructor can do this for you. \ndict((\n ('a', 1),\n ('b', 2)\n))\n\n" ]
[ 16 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0003553949_dictionary_python_tuples.txt