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: how can I get complete header info from urlib2 request? I am using the python urllib2 library for opening URL, and what I want is to get the complete header info of the request. When I use response.info I only get this: Date: Mon, 15 Aug 2011 12:00:42 GMT Server: Apache/2.2.0 (Unix) Last-Modified: Tue, 01 May 2001...
how can I get complete header info from urlib2 request?
I am using the python urllib2 library for opening URL, and what I want is to get the complete header info of the request. When I use response.info I only get this: Date: Mon, 15 Aug 2011 12:00:42 GMT Server: Apache/2.2.0 (Unix) Last-Modified: Tue, 01 May 2001 18:40:33 GMT ETag: "13ef600-141-897e4a40" Accept-Ranges: byt...
[ "Those are all of the headers the server is sending when you do the request with urllib2.\nFirefox is showing you the headers it's sending to the server as well.\nWhen the server gets those headers from Firefox, some of them may trigger it to send back additional headers, so you end up with more response headers as...
[ 7, 0 ]
[]
[]
[ "html", "python", "urllib2" ]
stackoverflow_0007064848_html_python_urllib2.txt
Q: Create property in class in __init__ How I'm can create a property for class in init? If I'm use this code: In [1]: import functools In [2]: def test(id, wrap): ...: return id*2 In [3]: class A(object): ...: def __init__(self, id): ...: self.id = id ...: setattr(s...
Create property in class in __init__
How I'm can create a property for class in init? If I'm use this code: In [1]: import functools In [2]: def test(id, wrap): ...: return id*2 In [3]: class A(object): ...: def __init__(self, id): ...: self.id = id ...: setattr(self.__class__, 'testing', property(functoo...
[ "You really shouldn't allow an instance to place a property in its class.\nWhat happens if you have many instances? Each instantiation overrides the previous definition of the property. (Indeed, that is why you got five 8's in the output you posted).\nBetter would be:\nclass A(object):\n @property\n def testi...
[ 2 ]
[]
[]
[ "class", "metaclass", "properties", "python" ]
stackoverflow_0007065100_class_metaclass_properties_python.txt
Q: How to prevent PyQt objects from garbage collecting from different thread? I am using Qt 4.7 and PyQt 4.7 to build a multi-threaded GUI program. I've been carefully managing PyQt objects so that they stay in one UI thread to avoid synchronization issues and there is no problem in general. But sometimes, at the mom...
How to prevent PyQt objects from garbage collecting from different thread?
I am using Qt 4.7 and PyQt 4.7 to build a multi-threaded GUI program. I've been carefully managing PyQt objects so that they stay in one UI thread to avoid synchronization issues and there is no problem in general. But sometimes, at the moment the python garbage collector is activated from other thread, the destructor ...
[ "This problem popped up on the PyQt mailing list in the thread\n\"subtle bug in PyQt in combination with Python garbage collector\"\nhttp://www.riverbankcomputing.com/pipermail/pyqt/2011-August/030376.html\nKovid Goyal proposed a workaround in\nhttp://www.riverbankcomputing.com/pipermail/pyqt/2011-August/030378.htm...
[ 6, 1 ]
[]
[]
[ "garbage_collection", "multithreading", "pyqt", "python", "qt" ]
stackoverflow_0003975343_garbage_collection_multithreading_pyqt_python_qt.txt
Q: Cannot use views.py file to dump a mysql database I seem to be having a problem. I want a view where I can allow staff users to download the MySQL database for that program. Unfortunately it is not working. I finding out the problem seems to be hard. Views.py @login_required def dbbackup(request): if not (requ...
Cannot use views.py file to dump a mysql database
I seem to be having a problem. I want a view where I can allow staff users to download the MySQL database for that program. Unfortunately it is not working. I finding out the problem seems to be hard. Views.py @login_required def dbbackup(request): if not (request.user.is_authenticated() and request.user.is_staff):...
[ "The webserver is probably running as a different user than root, so does not have permissions to create the file.\n" ]
[ 2 ]
[]
[]
[ "database", "django", "mysql", "mysqldump", "python" ]
stackoverflow_0007065276_database_django_mysql_mysqldump_python.txt
Q: GCC permission denied when trying to install Python module I'm trying to install this module http://pypi.python.org/pypi/winrandom/1.1. So I extract the content of the zip-file and try to install it with the command: python setup.py install And receives this output: running install running build running build_ext...
GCC permission denied when trying to install Python module
I'm trying to install this module http://pypi.python.org/pypi/winrandom/1.1. So I extract the content of the zip-file and try to install it with the command: python setup.py install And receives this output: running install running build running build_ext building 'winrandom' extension c:\cygwin\bin\gcc.exe -mno-cygwi...
[ "This problem may be caused by the fact that cygwin uses symlinks for gcc and g++, and windows doesn't understand how to handle this. A quick test to see if this is so is as follows:\nC:\\>g++\nAccess is denied.\n\nC:\\>bash\n\n$ ls -l /usr/bin/g++\nlrwxrwxrwx 1 nate Domain Users 21 Mar 22 2010 /usr/bin/g++ -> /e...
[ 9 ]
[]
[]
[ "cygwin", "gcc", "python" ]
stackoverflow_0007065416_cygwin_gcc_python.txt
Q: Python: Opening process on a certain screen I wrote a script for myself so when I login to the computer 4 IE windows auto start. I tried to use the webbrowser module but it would load the 4 links into 1 IE window with tabs. I could not get webbrowser to open 4 different windows so I used subprocess.Popen. I have ...
Python: Opening process on a certain screen
I wrote a script for myself so when I login to the computer 4 IE windows auto start. I tried to use the webbrowser module but it would load the 4 links into 1 IE window with tabs. I could not get webbrowser to open 4 different windows so I used subprocess.Popen. I have 4 monitors and I want each instance of IE to auto...
[ "I doubt you can do this with Python standard cross-platform functions alone. Using Windows API you can specify application window starting position and size with dwX, dwY, dwXSize, dwYSize members of the STARTUPINFO structure passed to the CreateProcess function. There are probably examples out there of using Crea...
[ 1 ]
[]
[]
[ "internet_explorer", "popen", "python" ]
stackoverflow_0007065235_internet_explorer_popen_python.txt
Q: Detecting broken stream in python when file is deleted My problem is that logging stops for a python program when the log is rotated. I have tracked it down to the stream itself. I don't see any way to tell if the stream is broken from python. After the file is deleted it still accepts writes without any issue. im...
Detecting broken stream in python when file is deleted
My problem is that logging stops for a python program when the log is rotated. I have tracked it down to the stream itself. I don't see any way to tell if the stream is broken from python. After the file is deleted it still accepts writes without any issue. import os FILE = 'testing.txt' fs = open(FILE, 'a') fs.write...
[ "Upon much more inspection, I found the solution. It is an OS specific problem. When the file is deleted in Linux (or Macintosh) it just unlinks it. (I was not aware of this)\nSo if you run lsof on the machine, it still shows the file as open.\n[user@machine]$ lsof | grep --color -i \"testing.txt\"\npython26 26495...
[ 2, 0, 0, 0 ]
[]
[]
[ "delete_file", "linux", "logrotate", "python", "stream" ]
stackoverflow_0005955169_delete_file_linux_logrotate_python_stream.txt
Q: How to sort dictionary by pseudo-compound key? I have a dictionary: test = {} test[(1,2)] = 1 test[(4,3)] = 1 test[(1,4)] = 1 How to sort by "pseudo compound key": first element of tuple and after second element of tuple ? A: test = {} test[(1,2)] = 1 test[(4,3)] = 2 test[(1,4)] = 3 print sorted(test.iteritems...
How to sort dictionary by pseudo-compound key?
I have a dictionary: test = {} test[(1,2)] = 1 test[(4,3)] = 1 test[(1,4)] = 1 How to sort by "pseudo compound key": first element of tuple and after second element of tuple ?
[ "test = {}\ntest[(1,2)] = 1\ntest[(4,3)] = 2\ntest[(1,4)] = 3\n\nprint sorted(test.iteritems())\n\nWill give you:\n[((1, 2), 1), ((1, 4), 3), ((4, 3), 2)]\n\nIf you want them back as a dictionary:\nimport OrderedDict\nsorted_test = OrderedDict(sorted(test.iteritems()))\n\nYou've got a dictionary sorted by it's keys...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007065956_python.txt
Q: Compile python AST to method I have been experimenting with ASTs in python. I want to modify methods by transforming the ASTs at runtime. I can get the source of an pre-compiled method using inspect.getsource(), and I can modify the AST as required by using AST visitors. This is probably quite naive, but I'd like ...
Compile python AST to method
I have been experimenting with ASTs in python. I want to modify methods by transforming the ASTs at runtime. I can get the source of an pre-compiled method using inspect.getsource(), and I can modify the AST as required by using AST visitors. This is probably quite naive, but I'd like to be able to compile the AST and ...
[ "You should not ask a new question in your own answer but create a separate question for that.\nNote that your first and second question also sort of contradict. First you want to do things at runtime and later you want to write them to a file so you don't have to do it over and over again. Please state your endgoa...
[ 1 ]
[]
[]
[ "abstract_syntax_tree", "methods", "python" ]
stackoverflow_0007061225_abstract_syntax_tree_methods_python.txt
Q: YAML on Textile Parsing I think this is my first question here. I've been lurking around on StackOverflow for quite some time now it has been a great resource to me. I'm writing a small static site generator that works like jekyll (The end-user writes his page content in textile and the header(meta-info) in YAML -...
YAML on Textile Parsing
I think this is my first question here. I've been lurking around on StackOverflow for quite some time now it has been a great resource to me. I'm writing a small static site generator that works like jekyll (The end-user writes his page content in textile and the header(meta-info) in YAML - a script mashes it up with t...
[ "Assuming all your file will have the same format and use YAML, one possibility would be to read the file into a single string and then do a string split on \"---\" to end up up with an array. \nI'm not a python guy, but I think this should create an array with the following:\n\nIndex 0 - Empty\nIndex 1 - Your YAML...
[ 1 ]
[]
[]
[ "jekyll", "parsing", "python", "textile", "yaml" ]
stackoverflow_0007056957_jekyll_parsing_python_textile_yaml.txt
Q: Unexpected result in Python class initialization I wrote following code: class node: def __init__(self, title, series, parent): self.series = series self.title = title self.checklist = [] if(parent != None): self.checklist = parent.checklist self.checklist.ap...
Unexpected result in Python class initialization
I wrote following code: class node: def __init__(self, title, series, parent): self.series = series self.title = title self.checklist = [] if(parent != None): self.checklist = parent.checklist self.checklist.append(self) When I create objects like this: a = node(...
[ "You do self.checklist = parent.checklist which means that both instances share the same list. They both add themselves to it, so when you print it you see both instances.\nMaybe you wanted to make a copy of the parent list? self.checklist = parent.checklist[:]\n", "Be careful of the slice notation [:]\nThis will...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007066181_python.txt
Q: Using Non-Standard Python Install I recently attempted to upgrade our Python install on a CentOS server from 2.4.3 to 2.7, however it lists 2.4.3 as the newest stable release. This is a problem because I have a Python program that requires at least 2.7 to run properly. After contacting support they installed Pyt...
Using Non-Standard Python Install
I recently attempted to upgrade our Python install on a CentOS server from 2.4.3 to 2.7, however it lists 2.4.3 as the newest stable release. This is a problem because I have a Python program that requires at least 2.7 to run properly. After contacting support they installed Python 2.7 in a separate directory, howeve...
[ "I'd suggest you ask your support team to build a separate RPM for Python2.7 and have it installed in a separate location and not conflicting with the OS version. I've done this before it was great to have a consistent Python released across my RHEL3, 4, and 5 systems.\nNext, I'd suggest you use the following for y...
[ 2, 1 ]
[]
[]
[ "centos", "python" ]
stackoverflow_0007066395_centos_python.txt
Q: Python appscript error: OSERROR: -1700, Can't make some data into the expected type from appscript import * ps = app("Adobe Photoshop CS5") s = ps.current_document.save s._labelledargterms Gives: {'appending': 'DcXt', 'as_': 'fltp', 'copying': 'SaCp', 'in_': 'kfil', 'with_options': 'FmOp'} I'm not exactly us...
Python appscript error: OSERROR: -1700, Can't make some data into the expected type
from appscript import * ps = app("Adobe Photoshop CS5") s = ps.current_document.save s._labelledargterms Gives: {'appending': 'DcXt', 'as_': 'fltp', 'copying': 'SaCp', 'in_': 'kfil', 'with_options': 'FmOp'} I'm not exactly use what the kfil means. Can someone explain? I was trying to do the following: import mact...
[ "Ok, seems I must avoid mactypes.File. Strangely, this works:\ns(in_=\"/Users/az/foo.jpg\", as_=k.JPEG,\n with_options={k.class_:k.JPEG_save_options, k.quality:12},\n copying=True, appending=k.no_extension)\n\nI don't fully understand why that works (and not the other way as in the question), so if someone could ...
[ 0 ]
[]
[]
[ "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0007066064_py_appscript_python_sourceforge_appscript.txt
Q: Translate AppleScript to Python appscript (`do javascript`) This is the AppleScript template: tell application "Adobe Photoshop CS5" set theFile to alias “Application:Documents:MyFile” open theFile do javascript (file <path to Emboss.jsx>) with arguments { 75,2,89 } end tell And I would like to translate that...
Translate AppleScript to Python appscript (`do javascript`)
This is the AppleScript template: tell application "Adobe Photoshop CS5" set theFile to alias “Application:Documents:MyFile” open theFile do javascript (file <path to Emboss.jsx>) with arguments { 75,2,89 } end tell And I would like to translate that to Python appscript. Unfortunately, I cannot figure out how to t...
[ "To translate generic AppleScript to appscript, use the ASTranslate tool available from the appscript web site here. It is not always able to successfully translate due to the quirks and bugs in the script definitions of some applications but it is a good place to start.\n", "I still don't exactly know how to t...
[ 2, 1 ]
[]
[]
[ "applescript", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0007065541_applescript_py_appscript_python_sourceforge_appscript.txt
Q: PyPy significantly slower than CPython I've been testing a cacheing system of my making. Its purpose is to speed up a Django web application. It stores everything in-memory. According to cProfile most of the time in my tests is spent inside QuerySet._clone() which turns out to be terribly inefficient (it's actuall...
PyPy significantly slower than CPython
I've been testing a cacheing system of my making. Its purpose is to speed up a Django web application. It stores everything in-memory. According to cProfile most of the time in my tests is spent inside QuerySet._clone() which turns out to be terribly inefficient (it's actually not that strange given the implementation)...
[ "Brushing aside the fact that PyPy might really be intrinsically slower for your case, there are some factors that could be making it unnecessarily slower:\n\nProfiling is known to slow PyPy a lot more than CPython.\nSome debugging/logging code can disable optimizations (by, e.g., forcing frames).\nThe server you'r...
[ 20 ]
[]
[]
[ "cprofile", "jit", "optimization", "pypy", "python" ]
stackoverflow_0007063508_cprofile_jit_optimization_pypy_python.txt
Q: Undocumented Exchange ActiveSync status while syncing I'm trying to build a simple Exchange ActiveSync client. I'm using a simple Python script that sends an initial sync email command, while connecting to an Exchange 2010 SP1 . In the request body I'm send the following XML encoded as WBXML (using pywbxml): <?xml...
Undocumented Exchange ActiveSync status while syncing
I'm trying to build a simple Exchange ActiveSync client. I'm using a simple Python script that sends an initial sync email command, while connecting to an Exchange 2010 SP1 . In the request body I'm send the following XML encoded as WBXML (using pywbxml): <?xml version="1.0"?> <!DOCTYPE AirSync PUBLIC "-//AIRSYNC//DTD ...
[ "The Sync status code value 4 represents a client protocol error. It is documented on this MSDN page.\nA correct Sync command would look more like the following, assuming that Inbox has an ID of 5 (converted from WBXML to a readable XML):\n<?xml version='1.0' ?>\n<Sync>\n <Collections>\n <Collection>\n <Sy...
[ 1 ]
[]
[]
[ "activesync", "exchange_server", "python", "wbxml" ]
stackoverflow_0007020815_activesync_exchange_server_python_wbxml.txt
Q: Why doesn't pdflatex work when called as a Python subprocess? I am trying to implement a function in my Python script to compile a TeX file automatically. I am trying with the subprocess module; this is what I'm doing: def createpdf(output): args = ['pdflatex', output, '-interaction=nonstopmode'] process ...
Why doesn't pdflatex work when called as a Python subprocess?
I am trying to implement a function in my Python script to compile a TeX file automatically. I am trying with the subprocess module; this is what I'm doing: def createpdf(output): args = ['pdflatex', output, '-interaction=nonstopmode'] process = subprocess.call(args, stdout = subprocess.PIP...
[ "When you set an output pipe to subprocess.PIPE, subprocess creates a buffer to hold the subprocess' output until it's read by your process. If you never read from process.stdout and process.stderr, pdflatex can fill up the buffer and block.\nYou need to either discard their output or just call subprocess.call(args...
[ 1 ]
[]
[]
[ "pdflatex", "python", "subprocess" ]
stackoverflow_0007067210_pdflatex_python_subprocess.txt
Q: Weirdness calling str() to convert integer to string in Python 3? Why is this giving me an error? >>> variable = str(21) Traceback (most recent call last): File "<pyshell#101>", line 1, in <module> variable = str(21) TypeError: 'str' object is not callable A: That code alone won't give you an error. For e...
Weirdness calling str() to convert integer to string in Python 3?
Why is this giving me an error? >>> variable = str(21) Traceback (most recent call last): File "<pyshell#101>", line 1, in <module> variable = str(21) TypeError: 'str' object is not callable
[ "That code alone won't give you an error. For example, I just tried this:\n~ $ python3.2\n>>> variable = str(21)\n>>> variable\n'21'\n\nSomewhere in your code you're defining that str = something else, masking the builtin definition of str. Remove that and your code will work fine.\n", "Because you've probably ov...
[ 41, 14 ]
[]
[]
[ "python", "python_3.x", "shadowing" ]
stackoverflow_0007067524_python_python_3.x_shadowing.txt
Q: Python appscript OSAX display_dialog: how to move it to foreground I am playing around with the example from here; esp. I have this code: from osax import * sa = OSAX() print sa.display_dialog("Python says hello!", buttons=["Hi!", "Howdy!", "Duuuude!"], default_but...
Python appscript OSAX display_dialog: how to move it to foreground
I am playing around with the example from here; esp. I have this code: from osax import * sa = OSAX() print sa.display_dialog("Python says hello!", buttons=["Hi!", "Howdy!", "Duuuude!"], default_button=3) The dialog always opens in the background. How can I open it in ...
[ "Add an activate command to give your Python process the window manager application focus.\nsa = OSAX()\nsa.activate()\nprint sa.display_dialog(...)\n\nYou can also choose to not GUIfy your Python process by targeting a faceless background app as described here.\n", "This works for now:\ndef go_foreground():\n ...
[ 1, 0 ]
[]
[]
[ "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0007067641_py_appscript_python_sourceforge_appscript.txt
Q: linked list in python there are huge number of data, there are various groups. i want to check whether the new data fits in any group and if it does i want to put that data into that group. If datum doesn't fit to any of the group, i want to create new group. So, i want to use linked list for the purpose or is the...
linked list in python
there are huge number of data, there are various groups. i want to check whether the new data fits in any group and if it does i want to put that data into that group. If datum doesn't fit to any of the group, i want to create new group. So, i want to use linked list for the purpose or is there any other way to doing s...
[ "This sounds like a perfect use for a dictionary.\n", "I would suggest using a dictionary (or defaultdict), where the key is the group and the value is a list of all data. Here is a simple example:\n>>> from collections import defaultdict\n>>> get_group = lambda x: x % 4\n>>> d = defaultdict(list)\n>>> for value...
[ 7, 2 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0007067726_linked_list_python.txt
Q: Problem with python-mode.el install I just installed python-mode.el (6.0.1) and when I start up Emacs.app it gives me the following error: File error: Cannot open load file, highlight-indentation Are there dependencies for python-mode.el that I have to install first? A: The python-mode 6.0.1 tar.gz bundle does ...
Problem with python-mode.el install
I just installed python-mode.el (6.0.1) and when I start up Emacs.app it gives me the following error: File error: Cannot open load file, highlight-indentation Are there dependencies for python-mode.el that I have to install first?
[ "The python-mode 6.0.1 tar.gz bundle does include highlight-indentation.el. It appears that this file was added in version 6.0. However, this is not mentioned in the README or NEWS files. \n" ]
[ 1 ]
[]
[]
[ "emacs", "python", "python_mode" ]
stackoverflow_0007058103_emacs_python_python_mode.txt
Q: Using MongoLab Database service vs Custom web service with MongoDB running on AWS I am looking for feasible solutions for my Application to be backed with MongoDB. I am looking to host the MongoDB on the cloud with a python based server to interact with the DB and my app (either mobile/web). I am trying to underst...
Using MongoLab Database service vs Custom web service with MongoDB running on AWS
I am looking for feasible solutions for my Application to be backed with MongoDB. I am looking to host the MongoDB on the cloud with a python based server to interact with the DB and my app (either mobile/web). I am trying to understand how the architecture should look like. Either i can host a mongoDB on the AWS clou...
[ "One thing to consider is that you don't need to use MongoLab's REST API. You can connect directly via a driver as well. \nSo, if you need to implement business logic (which it sounds like you do), it makes sense to have a three tier architecture with an app server connecting to your MongoLab database via one of th...
[ 0 ]
[]
[]
[ "amazon_web_services", "cloud_hosting", "mlab", "mongodb", "python" ]
stackoverflow_0007067909_amazon_web_services_cloud_hosting_mlab_mongodb_python.txt
Q: How to create a exe launcher using python in windows i need to launch a exe using a python script but also I need to kill it using the same script A start idea is: process = magicCommand( 'theExe.exe' ) #invoke exe kill = 'no' while kill == 'no': kill = raw_input() otherMagicCommand( process ) #kill EDIT th...
How to create a exe launcher using python in windows
i need to launch a exe using a python script but also I need to kill it using the same script A start idea is: process = magicCommand( 'theExe.exe' ) #invoke exe kill = 'no' while kill == 'no': kill = raw_input() otherMagicCommand( process ) #kill EDIT this works in windows for me process = subprocess.Popen( 'th...
[ "Python subprocess module and some good examples and explanation\n" ]
[ 2 ]
[]
[]
[ "launcher", "python", "windows" ]
stackoverflow_0007068173_launcher_python_windows.txt
Q: Python 2.4 Doesn't Load Home-Directory Packages I'm trying to get a Python package to install to my home directory because I don't have the privileges to install it system-wide. The package is PyProj, and I am trying to install it using python setup.py install --home=~ (with Python 2.4.3), as recommended in the Py...
Python 2.4 Doesn't Load Home-Directory Packages
I'm trying to get a Python package to install to my home directory because I don't have the privileges to install it system-wide. The package is PyProj, and I am trying to install it using python setup.py install --home=~ (with Python 2.4.3), as recommended in the Python documentation. The package compiles successfully...
[ "You'll need to set PYTHONPATH to tell Python where to locate your locally installed packages.\nFor example:\n[you@home]$ export PYTHONPATH=\"~/lib64/python\"\n\nOr, to do this within the interpreter (or script):\nimport sys, os\nsys.path.append(os.path.expanduser(\"~/lib64/python\")) \n\nFor more information on ho...
[ 4, 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0007068431_linux_python.txt
Q: Having problems defining variables outside a function (Python) I'm pretty new to python and I'm trying to make a simple program where you have text menus and I have to use functions to do most of the work (to get used to using functions inside a program). So I'm trying to use a function in this program to get the ...
Having problems defining variables outside a function (Python)
I'm pretty new to python and I'm trying to make a simple program where you have text menus and I have to use functions to do most of the work (to get used to using functions inside a program). So I'm trying to use a function in this program to get the first, second, and possibly a third number from the user. I need to ...
[ "Variables are local to the functions in which they are defined. You might try having your function return those values:\ndef getNum():\n firstNum = input(\"...\")\n secondNum = input(\"...\")\n thirdNum = input(\"...\")\n return firstNum, secondNum, thirdNum\n\nif option == 1:\n firstNum, secondNum...
[ 5, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007068360_function_python.txt
Q: Why does the print statement at the bottom of my main method not print anything? I'm working on the MIT open courseware for CS-600 and I can't figure out why the last print statement isn't printing anything. Here's the code I wrote: #!/usr/bin/env python # encoding: utf-8 # 6.00 Problem Set 9 # # Name: # Collabora...
Why does the print statement at the bottom of my main method not print anything?
I'm working on the MIT open courseware for CS-600 and I can't figure out why the last print statement isn't printing anything. Here's the code I wrote: #!/usr/bin/env python # encoding: utf-8 # 6.00 Problem Set 9 # # Name: # Collaborators: # Time: from string import * class Shape(object): def area(self): ...
[ "This line:\nself.allShapes = self.allCircles + self.allSquares + self.allTriangles\n\ndoesn't do what you think it does. It sets allShapes to an empty list, and then as you add shapes later, nothing updates allShapes.\nThen your __str__ function just loops over allShapes, which is still empty, so your __str__ ret...
[ 6, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007068654_python.txt
Q: Looping through a table in python reportlab I am creating a table using the python module reportlab. In this table, I would like to loop through and have a different background color depending on the values of any particular cell. To do this, I came up with the following: elements = [] table1 = [[34,27,35,35], ...
Looping through a table in python reportlab
I am creating a table using the python module reportlab. In this table, I would like to loop through and have a different background color depending on the values of any particular cell. To do this, I came up with the following: elements = [] table1 = [[34,27,35,35], [3,76,23,157], [13,137,15,75], ...
[ "I don't know enough about ReportLab to know for sure, but a common problem in this type of coding is that the axes are swapped. For example, indexing like this: table1[ii][jj] means that ii is the y axis (rows) and jj is the x axis (columns), so you'd have to supply x and y to ReportLab as jj, ii. Check if your ...
[ 3, 2 ]
[]
[]
[ "for_loop", "loops", "python", "reportlab" ]
stackoverflow_0007068650_for_loop_loops_python_reportlab.txt
Q: How to retrieve a picasa photo using Google api in Python I am trying to retrieve a photo (the .jpg file) from a Picasa album using the gdata Google API. However I did not find any method which does it, even though it is possible to upload a photo using methods like InsertPhoto and InsertPhotoSimple. I guess I mus...
How to retrieve a picasa photo using Google api in Python
I am trying to retrieve a photo (the .jpg file) from a Picasa album using the gdata Google API. However I did not find any method which does it, even though it is possible to upload a photo using methods like InsertPhoto and InsertPhotoSimple. I guess I must be missing something :-(. A simple example would help.
[ "Client API provides methods only for obtaining information on photos: http://code.google.com/apis/picasaweb/docs/1.0/developers_guide_python.html#Photos\nTo retrieve an image, use an HTTP GET with information previously obtained. Read the documentation.\nFor this purpose you may use a Python library:\n\nhttplib\nu...
[ 5 ]
[]
[]
[ "google_api", "picasa", "python" ]
stackoverflow_0007068630_google_api_picasa_python.txt
Q: CharField filenames into ImageFields in Django I have a model: class Photo(models.Model): filename = models.CharField(max_length=240) And a corresponding MySQL table, filled with filenames (copied from an existing table). In the future I may want to upload new photos to the model via admin. Is it possible to ...
CharField filenames into ImageFields in Django
I have a model: class Photo(models.Model): filename = models.CharField(max_length=240) And a corresponding MySQL table, filled with filenames (copied from an existing table). In the future I may want to upload new photos to the model via admin. Is it possible to evolve the current model into something with ImageFi...
[ "It is possible, assuming the current filename field in your model contains the full path to the actual file, you can add a new field (ImageField) to your model and migrate it using South, then write a script to update your data.\nA skeleton example,\nfrom django.core.files import File\n\n# assuming your updated mo...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007068444_django_django_models_python.txt
Q: module to create python object representation from xml I'm searching for an easy to handle python native module to create python object representation from xml. I found several modules via google (one of them is XMLObject) but didn't want to try out all of them. What do you think is the best way to do such things...
module to create python object representation from xml
I'm searching for an easy to handle python native module to create python object representation from xml. I found several modules via google (one of them is XMLObject) but didn't want to try out all of them. What do you think is the best way to do such things? EDIT: I missed to mention that the XML I'd like to read is...
[ "You say you want an object representation, which I would interpret to mean that nodes become objects, and the attributes and children of the node are represented as attributes of the object (possibly according to some Schema). This is what XMLObject does, I believe.\nThere are some packages that I know of. 4Suit...
[ 12, 5, 3, 3, 1, 1, 0 ]
[]
[]
[ "pickle", "python", "xml" ]
stackoverflow_0000306671_pickle_python_xml.txt
Q: Can you rename "table of contents" in the Sphinx sidebar? More generally how do you rename Sphinx default elements (e.g. Quick Search to Search)? Can you? A: Here is how you could change "Quick search" to something else by overriding a template: Create a folder called templates in the Sphinx project directory. ...
Can you rename "table of contents" in the Sphinx sidebar?
More generally how do you rename Sphinx default elements (e.g. Quick Search to Search)? Can you?
[ "Here is how you could change \"Quick search\" to something else by overriding a template:\n\nCreate a folder called templates in the Sphinx project directory.\nCopy <Sphinx install dir>/themes/basic/searchbox.html to templates.\nIn conf.py, add \ntemplates_path = [\"templates\"]\n\nRename 'Quick search' to whateve...
[ 8, 1 ]
[]
[]
[ "python", "python_sphinx", "sidebar" ]
stackoverflow_0006824052_python_python_sphinx_sidebar.txt
Q: Good way for a Revision Controllled Model? - Django here is my attempt: Example #1 class RevisionControlledValue(models.Model): created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User) value = models.TextField() class Meta: ordering = ('-created', ) class D...
Good way for a Revision Controllled Model? - Django
here is my attempt: Example #1 class RevisionControlledValue(models.Model): created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User) value = models.TextField() class Meta: ordering = ('-created', ) class DjangoPony(models.Model): names = models.ManyToManyFi...
[ "There is app for that django-reversion. If you really only want to have reversion control on one field break it off into its own table and make a 1-to-1 relationship.\n", "I think you forgot the word fields in your title. =) I guess I would use an approach that leaves the original model intact. Something star...
[ 2, 1, 1 ]
[]
[]
[ "django", "django_models", "python", "sql", "version_control" ]
stackoverflow_0005431396_django_django_models_python_sql_version_control.txt
Q: Analog of bash "echo $(cat file)" in python (one more time string interpolation) I have a file values.txt with hierarchical formatting like this: group1 subgroup1 value1 value2 group2 subgroup2 value3 value4 if in bash i execute echo $(cat values.txt) ...
Analog of bash "echo $(cat file)" in python (one more time string interpolation)
I have a file values.txt with hierarchical formatting like this: group1 subgroup1 value1 value2 group2 subgroup2 value3 value4 if in bash i execute echo $(cat values.txt) I will get the output: group1 subgroup1 value1 value2 group2 subgroup2 value3 value4 ...
[ "As Byron points out, split splits on whitespace by default, so you should be able to do just\ncontents = open(\"values.txt\", \"r\").read().split()\n\nand have the list you want, combining the two steps you described. If you have some other use for the intermediate \"string formatted the exact same way\", you can...
[ 3, 0 ]
[]
[]
[ "python", "string", "string_interpolation" ]
stackoverflow_0007069541_python_string_string_interpolation.txt
Q: Python Local Package Doesn't Load In Call From PHP So, I want to run a Python program with a home-directory install of PyProj from PHP. The PHP and Python are simple, but I include them below for completeness. I've tested running Python manually using both sys.path.append and PYTHONPATH to specify the location of ...
Python Local Package Doesn't Load In Call From PHP
So, I want to run a Python program with a home-directory install of PyProj from PHP. The PHP and Python are simple, but I include them below for completeness. I've tested running Python manually using both sys.path.append and PYTHONPATH to specify the location of the package. Both of these methods work. However, when I...
[ "A good way to solve a problem like this is to print the sys.path from a Python script in this environment and check what the current path is:\n #!/usr/bin/python\n import sys\n print sys.path\n\nMy guess is that it will containt '\"/home/userperson/public_html/lib64/python2.4/site-packages\"' (note the superfluous...
[ 3 ]
[]
[]
[ "linux", "php", "python" ]
stackoverflow_0007069448_linux_php_python.txt
Q: Explicit argument in signature does not work? Very odd I'm trying to understand why explicitly specifying the signature arguments doesn't work, but just blindly doing an *args, **kwargs works! I really don't see much difference between the two? Example that does not work: from django.db.models import CharField as ...
Explicit argument in signature does not work? Very odd
I'm trying to understand why explicitly specifying the signature arguments doesn't work, but just blindly doing an *args, **kwargs works! I really don't see much difference between the two? Example that does not work: from django.db.models import CharField as _CharField class CharField(_CharField): def get_db_prep...
[ "The thing is, the connection argument is supposed to be always passed in as a keyword argument. The code in django.db.models.fields.subclassing only checks whether it is present in the kwargs dictionary, if not, it issues a DeprecationWarning and adds it in there. The positional arguments are not checked, so what ...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007068057_django_django_models_python.txt
Q: JavaScript Glib.spawn_async stdout file descriptor I want to spawn a process using spawn_async in the GLib bindings in javascript in a gnome3 shell-extension. I need something like the "standard_output=True" parameter in the python doc http://developer.gnome.org/pygobject/stable/glib-functions.html which, when ena...
JavaScript Glib.spawn_async stdout file descriptor
I want to spawn a process using spawn_async in the GLib bindings in javascript in a gnome3 shell-extension. I need something like the "standard_output=True" parameter in the python doc http://developer.gnome.org/pygobject/stable/glib-functions.html which, when enabled, returns a filedescriptor to stdout of the process....
[ "The pygobject documentation you referenced is for the static libraries. Since Seed works through GObject introspection, you're safer trusting the C documentation. (Seed is the GObject introspecting Java Script library)\nPerhaps you can roll your own function that does what you want in C and expose it to Seed: http...
[ 1, 0 ]
[]
[]
[ "glib", "gnome_3", "gnome_shell", "javascript", "python" ]
stackoverflow_0007059252_glib_gnome_3_gnome_shell_javascript_python.txt
Q: Django: Saving old QuerySet for future comparison I'm new with django and I'm trying to make a unit test where I want to compare a QuerySet before and after a batch editing function call. def test_batchEditing_9(self): reset() #reset database for test query = Game.objects.all() query_ol...
Django: Saving old QuerySet for future comparison
I'm new with django and I'm trying to make a unit test where I want to compare a QuerySet before and after a batch editing function call. def test_batchEditing_9(self): reset() #reset database for test query = Game.objects.all() query_old = Game.objects.all() dict_value = {'game_cod...
[ "A Queryset is essentially just generating SQL and only on evaluating it, the database is hit. As far as I remember, that happens on iterating over the Queryset. For instance,\ngamescache = list(Game.objects.all())\n\nor\nfor g in Game.objects.all():\n ...\n\nhit the database.\n", "Following code should work:\...
[ 1, 0 ]
[]
[]
[ "database", "django", "django_queryset", "python", "unit_testing" ]
stackoverflow_0007067228_database_django_django_queryset_python_unit_testing.txt
Q: How do I authenticate my Python application with Google for the Google Contacts API? I'm building an application which uses the Python gdata library to access Google Contacts and I need to authenticate via that library in order to make my requests work. I'm kind of new to this, but basically I'm building a service...
How do I authenticate my Python application with Google for the Google Contacts API?
I'm building an application which uses the Python gdata library to access Google Contacts and I need to authenticate via that library in order to make my requests work. I'm kind of new to this, but basically I'm building a service that runs on a cron job to pull contacts from Google in order to back them up to a local ...
[ "This is for Google Docs, but i think the practice is the same?\nimport gdata.docs.service\n\n# Create a client class which will make HTTP requests with Google Docs server.\nclient = gdata.docs.service.DocsService()\n# Authenticate using your Google Docs email address and password.\nclient.ClientLogin('jo@gmail.com...
[ 1 ]
[]
[]
[ "gdata_api", "oauth", "python" ]
stackoverflow_0007070058_gdata_api_oauth_python.txt
Q: How do I repeatedly call an AppleScript droplet with different filenames? I have a lovely AppleScript droplet which performs OCR of a PDF file using Adobe Acrobat. I am a pretty good Python programmer but don't really understand AppleScript. I have a list of all the PDFs on my system that need to be OCRed. It woul...
How do I repeatedly call an AppleScript droplet with different filenames?
I have a lovely AppleScript droplet which performs OCR of a PDF file using Adobe Acrobat. I am a pretty good Python programmer but don't really understand AppleScript. I have a list of all the PDFs on my system that need to be OCRed. It would be really annoying to have to drag each on one top of the script. I'd like to...
[ "By calling alias you are essentially making a direct call to a file at that exact path, If the alias can't be found, then Applescript throws an error. If you are reading a list from a text file, then an error could occur in the generation of that list you aren't checking. At minimum, you need to use System Event...
[ 0, 0 ]
[]
[]
[ "applescript", "automation", "python" ]
stackoverflow_0007061763_applescript_automation_python.txt
Q: How do I read the output of the IPython %prun (profiler) command? I run this: In [303]: %prun my_function() 384707 function calls (378009 primitive calls) in 83.116 CPU seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 37706 41.693 0.00...
How do I read the output of the IPython %prun (profiler) command?
I run this: In [303]: %prun my_function() 384707 function calls (378009 primitive calls) in 83.116 CPU seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 37706 41.693 0.001 41.693 0.001 {max} 20039 36.000 0.002 36.000 0.002...
[ "It's just a convenient wrapper for Python's own profiler, the documentation for which is here:\nhttp://docs.python.org/library/profile.html#module-pstats\nQuoting:\n\nncalls\n for the number of calls,\ntottime for the total time spent in the given function (and excluding time made in calls to sub-functions),\nper...
[ 41 ]
[]
[]
[ "interpreter", "ipython", "profiler", "python" ]
stackoverflow_0007069733_interpreter_ipython_profiler_python.txt
Q: which is better for my project: Django, Plone, php, or ruby on rails I have a php video hosting site, not a typical video hosting site, but i think you put it in that category. I'm almost done with it, I'll launch it maybe next week, i created it in php because my partner wanted to get it done so fast, and the fas...
which is better for my project: Django, Plone, php, or ruby on rails
I have a php video hosting site, not a typical video hosting site, but i think you put it in that category. I'm almost done with it, I'll launch it maybe next week, i created it in php because my partner wanted to get it done so fast, and the fastest way for me to do it was php, because i know it could be done with php...
[ "It does not really matter in which language you would make it. If you are good programmer, the application will work fine in any of those environment. If you are not good programmer, it will sux always :) you can do it for example in Ruby on Rails, but what is the purpose if you will not be able to follow MVC stru...
[ 3, 2 ]
[]
[]
[ "django", "php", "plone", "python", "ruby_on_rails" ]
stackoverflow_0007070097_django_php_plone_python_ruby_on_rails.txt
Q: NameError: global name is not defined I know there are a bunch of similar questions, but they didn't help me to understand my problem. Also I have 3 modules: First one is model: from datetime import datetime from elixir import * from run_test import create_db from sqlalchemy.schema import UniqueConstraint class Va...
NameError: global name is not defined
I know there are a bunch of similar questions, but they didn't help me to understand my problem. Also I have 3 modules: First one is model: from datetime import datetime from elixir import * from run_test import create_db from sqlalchemy.schema import UniqueConstraint class ValueTest(Test): value = Field(Integer) ...
[ "When you import a module, you don't import the names it has imported; you only import the names it defines itself. You still need to do from model import ValueTest in the last script.\nIf from foo import * imported every name that foo imported into its own scope, a single import something might also import every ...
[ 6 ]
[ "The problem is you have circular imports happening. run_test is importing model, which in turn is importing run_test. Strange things happen when circular imports are used. If you can, put the common functions (create_db, in your example) into another module, then model can import it from there and not from run_...
[ -1 ]
[ "python" ]
stackoverflow_0007067916_python.txt
Q: python collections.defaultdict() compile error The following code, simple and clear enough, produces an error when compiled: import string import collections #create dictionary with alphabets as keys, and empty values list = ['aema', 'airplane', 'amend'] gen_dict = dict.fromkeys(string.ascii_lowercase, '') gen_...
python collections.defaultdict() compile error
The following code, simple and clear enough, produces an error when compiled: import string import collections #create dictionary with alphabets as keys, and empty values list = ['aema', 'airplane', 'amend'] gen_dict = dict.fromkeys(string.ascii_lowercase, '') gen_dict = collections.defaultdict(list) for x in list:...
[ "you overwrite the internal list, being the name of a type, with your list = ['aema', 'airplane', 'amend'] above. Rename your list to e.g. keys or keylist and all will be fine.\nSo replace\nlist = ['aema', 'airplane', 'amend']\n\nwith\nkeys = ['aema', 'airplane', 'amend']\n\nand \nfor x in list:\n\nwith\nfor x in k...
[ 12 ]
[]
[]
[ "defaultdict", "dictionary", "python" ]
stackoverflow_0007070296_defaultdict_dictionary_python.txt
Q: python grid control / spreadsheet I am designing a thick-client (i.e. non-browser) Python application that will communicate with a hosted database. One of the screens of this application needs to have a grid / spreadsheet area that allows presentation of many rows of data, filtering, sorting, and updating of mult...
python grid control / spreadsheet
I am designing a thick-client (i.e. non-browser) Python application that will communicate with a hosted database. One of the screens of this application needs to have a grid / spreadsheet area that allows presentation of many rows of data, filtering, sorting, and updating of multiple rows of information. Does anyone ...
[ "I've had good results with wxPython's CSheet, though I ended up modifying it somewhat so that it acted a little more \"Excel-like\" (arrow keys and context menu) as per a coworker's request. wxPython works on OS X but it's 32-bit only right now I believe (based on Carbon API).\n" ]
[ 2 ]
[]
[]
[ "gridview", "python", "spreadsheet" ]
stackoverflow_0007070098_gridview_python_spreadsheet.txt
Q: Python: Execute function if this is the only process, otherwise send a message to the other process Possible Duplicate: Only one python program running (like Firefox)? I'm trying to write a program in Python to unpack large RAR archives. This can easily be done using e.g. Chilkat's library for extracting. Howev...
Python: Execute function if this is the only process, otherwise send a message to the other process
Possible Duplicate: Only one python program running (like Firefox)? I'm trying to write a program in Python to unpack large RAR archives. This can easily be done using e.g. Chilkat's library for extracting. However, I want to run only one unpacking process at a time. So the first time the Python program is executed...
[ "A similiar question has been asked in Only one python program running (like Firefox)?. To adapt this to your needs, you should have the first process establish a FIFO, socket or something and then start its work. If the work is done, it has a look on the FIFO/socket/... to know if there is other stuff to do, and t...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007070637_multithreading_python.txt
Q: Retrieving a date from a complex string in Python I'm trying to get a single datetime out of two strings using datetime.strptime. The time is pretty easy (ex. 8:53PM), so I can do something like: theTime = datetime.strptime(givenTime, "%I:%M%p") However, the string has more than just a date, it's a link in a fo...
Retrieving a date from a complex string in Python
I'm trying to get a single datetime out of two strings using datetime.strptime. The time is pretty easy (ex. 8:53PM), so I can do something like: theTime = datetime.strptime(givenTime, "%I:%M%p") However, the string has more than just a date, it's a link in a format similar to http://site.com/?year=2011&month=10&day...
[ "Think that if you would like to simple skip time from the URL you can use split for example the following way:\ngivenURL = 'http://site.com/?year=2011&month=10&day=5&hour=11'\npattern = \"http://site.com/?year=%Y&month=%m&day=%d\"\ntheDate = datetime.strptime(givenURL.split('&hour=')[0], pattern)\n\nSo not sure th...
[ 2, 1, 0 ]
[]
[]
[ "datetime", "python", "string", "strptime" ]
stackoverflow_0007070175_datetime_python_string_strptime.txt
Q: Python nested objects unable to retrieve value in function I am trying to build a tree structure that represents a parsed configuration file (the configuration file has a hierarchical structure to it). I represented this as: class configContainer(): treeDict = {} instances = {} class configObject(): ...
Python nested objects unable to retrieve value in function
I am trying to build a tree structure that represents a parsed configuration file (the configuration file has a hierarchical structure to it). I represented this as: class configContainer(): treeDict = {} instances = {} class configObject(): def __init__(self, name, configLine, parent): self.nam...
[ "configContainer.instances is a class attribute, so if you modify it for any instance of a class it will change for all instances of that class. With your current code any time you create a new configObject with the same name it will overwrite the entry in configContainer.instances for that name. You should eithe...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007070944_python.txt
Q: Pythonic way to ID a mystery file, then call a filetype-specific parser for it? Class creation q's (note) I would appreciate help generalizing the title. I am sure that this is a class of problems in OO land, and probably has a reasonable pattern, I just don't know a better way to describe it. I'm considering the ...
Pythonic way to ID a mystery file, then call a filetype-specific parser for it? Class creation q's
(note) I would appreciate help generalizing the title. I am sure that this is a class of problems in OO land, and probably has a reasonable pattern, I just don't know a better way to describe it. I'm considering the following -- Our server script will be called by an outside program, and have a bunch of text dumped at ...
[ "You could use the Strategy pattern which would allow you to separate the logic for the different formats which need to be parsed into concrete strategies. Your code would typically parse a portion of the file in the interface and then decide on a concrete strategy.\n\nAs far as defining the grammar for your files ...
[ 2 ]
[]
[]
[ "object", "python" ]
stackoverflow_0007070994_object_python.txt
Q: Create a slice using a tuple Is there any way in python to use a tuple as the indices for a slice? The following is not valid: >>> a = range(20) >>> b = (5, 12) # my slice indices >>> a[b] # not valid >>> a[slice(b)] # not valid >>> a[b[0]:b[1]] # is an awkward syntax [5, 6, 7, 8, 9, 10, 11] >>> b1, b...
Create a slice using a tuple
Is there any way in python to use a tuple as the indices for a slice? The following is not valid: >>> a = range(20) >>> b = (5, 12) # my slice indices >>> a[b] # not valid >>> a[slice(b)] # not valid >>> a[b[0]:b[1]] # is an awkward syntax [5, 6, 7, 8, 9, 10, 11] >>> b1, b2 = b >>> a[b1:b2] # looks a ...
[ "You can use Python's *args syntax for this:\n>>> a = range(20)\n>>> b = (5, 12)\n>>> a[slice(*b)]\n[5, 6, 7, 8, 9, 10, 11]\n\nBasically, you're telling Python to unpack the tuple b into individual elements and pass each of those elements to the slice() function as individual arguments.\n", "How about a[slice(*b)...
[ 46, 13, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007071264_python.txt
Q: What is the meaning of this ImportError when importing a Cython generated .so file? I am walking through the Cython documentation and building each of the example apps. I'm a little stuck at Using C Libraries. After successfully building the .so file and attempting to import it in a python file called test.py the ...
What is the meaning of this ImportError when importing a Cython generated .so file?
I am walking through the Cython documentation and building each of the example apps. I'm a little stuck at Using C Libraries. After successfully building the .so file and attempting to import it in a python file called test.py the following error is thrown. $ python3.2 test.py Traceback (most recent call last): Fil...
[ "EDIT:\nAh, you didn't mention you had a dependency on the code in libcalg. That stuff needs to be compiled and included when you build the cextension.\nJust modify setup.py:\n# setup.py\n# ...\next_modules = [Extension(\"queue\", [\"queue.pyx\", \"libcalg/queue.c\"])]\n# ...\n\n\nWe could step back and see if you...
[ 7 ]
[]
[]
[ "cython", "python", "shared_libraries" ]
stackoverflow_0007068721_cython_python_shared_libraries.txt
Q: python regex groups I'm fairly new to python and I'm trying to understand I do I loop regex groups, ex: reobj = re.compile('<a href="(.*?)">(.*?)</a>', re.IGNORECASE) result = reobj.findall(body) how do I loop the 2 groups from the regex ? Thanks! A: Did you actually try this in the shell? >>> body = """<a href...
python regex groups
I'm fairly new to python and I'm trying to understand I do I loop regex groups, ex: reobj = re.compile('<a href="(.*?)">(.*?)</a>', re.IGNORECASE) result = reobj.findall(body) how do I loop the 2 groups from the regex ? Thanks!
[ "Did you actually try this in the shell?\n>>> body = \"\"\"<a href=\"http://foo.com\">Foo</a><br><a href=\"http://bar.com\">Bar</a>\"\"\"\n>>> reobj = re.compile('<a href=\"(.*?)\">(.*?)</a>', re.IGNORECASE)\n>>> result = reobj.findall(body)\n>>> result\n[('http://foo.com', 'Foo'), ('http://bar.com', 'Bar')]\n\nSo ...
[ 6, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006971827_python_regex.txt
Q: Jython naming conflict: java.lang.Runtime.exec and python's exec I am translating some java code into Jython and there is a point where I need to call java.lang.Runtime. The code in Java reads: Runtime.getRuntime().exec(cmd); I need this to translate to Jython, but it confuses "exec" with Python's built in exec f...
Jython naming conflict: java.lang.Runtime.exec and python's exec
I am translating some java code into Jython and there is a point where I need to call java.lang.Runtime. The code in Java reads: Runtime.getRuntime().exec(cmd); I need this to translate to Jython, but it confuses "exec" with Python's built in exec function. I searched and found suggestions to use something like - from...
[ "javaexec = getattr(Runtime.getRuntime(), \"exec\")\n\nThat should work. Even better:\nimport subprocess\nsubprocess.Popen(cmd)\n\n" ]
[ 3 ]
[]
[]
[ "jython", "naming", "python" ]
stackoverflow_0007071483_jython_naming_python.txt
Q: Python mechanize form submiting problem http://klepec.amebis.si/ A want to submit to this form, but the standard submit code from mechanize examples does not work. The "submit" event happens, but the data submitted is empty. This website consist of 2 frames (glavni.asp and vnos.htm) glavni-main vnos-input. Since m...
Python mechanize form submiting problem
http://klepec.amebis.si/ A want to submit to this form, but the standard submit code from mechanize examples does not work. The "submit" event happens, but the data submitted is empty. This website consist of 2 frames (glavni.asp and vnos.htm) glavni-main vnos-input. Since mechanize doesn't support frames I tried openi...
[ "Many people recommend using twill formfill module instead of raw mechanize.\nTry that and tell us if the submit still fails?\n" ]
[ 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0007067559_mechanize_python.txt
Q: python fabric won't allow me to pipe output to less? I'm setting up fabric for the first time, and having trouble piping the output from fabric to less. For example, if I run: fabric deploy |less (Where deploy is my deployment function) I get the following error back from fabric: IOError: [Errno 22] Invalid argu...
python fabric won't allow me to pipe output to less?
I'm setting up fabric for the first time, and having trouble piping the output from fabric to less. For example, if I run: fabric deploy |less (Where deploy is my deployment function) I get the following error back from fabric: IOError: [Errno 22] Invalid argument This comes from a run() command on the remote host. ...
[ "Just for future reference, I resolved this by applying a patch to operations.py, as seen here:\nhttp://code.fabfile.org/attachments/56/operations.patch\nOtherwise, the code that would reproduce this problem is as follows:\nfrom __future__ import with_statement\nfrom fabric.api import *\nfrom fabric.contrib.console...
[ 2 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0006976032_fabric_python.txt
Q: Tricky MySQL query instead of a Python script to achieve the result? Before I set out to write a Python script, I want to see if MySQL alone can produce the result. I have a list of products : PID Product ----------- 1 AAA 2 ABC 3 BAC 4 CAB 5 CBA I have a list of companies ordering these products sever...
Tricky MySQL query instead of a Python script to achieve the result?
Before I set out to write a Python script, I want to see if MySQL alone can produce the result. I have a list of products : PID Product ----------- 1 AAA 2 ABC 3 BAC 4 CAB 5 CBA I have a list of companies ordering these products several times : CID PID ------- 1 1 2 3 1 5 3 2 1 1 2 3 The des...
[ "select cid,\nmax(case when pid = 1 then 'Y' else '' end) as AAA,\nmax(case when pid = 2 then 'Y' else '' end) as ABC,\nmax(case when pid = 3 then 'Y' else '' end) as BAC,\nmax(case when pid = 4 then 'Y' else '' end) as CAB,\nmax(case when pid = 5 then 'Y' else '' end) as CBA\nfrom companies\ngroup by cid\n\n", "...
[ 3, 2, 0, 0 ]
[ "I'm not so sure about your desired result, but it is rather easy to create something similar in MySQL usind GROUP BY, which might make it easier to create the desired view in Python:\nSELECT orders.cid, products.product\nFROM orders, products\nWHERE orders.pid=products.pid\nGROUP BY products.product\n\n" ]
[ -1 ]
[ "mysql", "pivot", "python", "report", "transpose" ]
stackoverflow_0007069837_mysql_pivot_python_report_transpose.txt
Q: Running python command line interpreter inside PyDev In matlab, it is possible to execute a script (ie an m-file) and then manipulate the variables created by the script on the command line. Is it possible to run a .py file on PyDev and consequently, manipulate its variables inside eclipse as is possible in the ca...
Running python command line interpreter inside PyDev
In matlab, it is possible to execute a script (ie an m-file) and then manipulate the variables created by the script on the command line. Is it possible to run a .py file on PyDev and consequently, manipulate its variables inside eclipse as is possible in the case of matlab?
[ "That's available through the PyDev interactive console. See: http://pydev.org/manual_adv_interactive_console.html\nAnother way would be executing some program in debug mode and inspecting variables in the console: http://pydev.org/manual_adv_debug_console.html\n", "Yes, check the run configurations. You can add ...
[ 4, 2 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007067279_eclipse_pydev_python.txt
Q: Super-annoying indent error (Python) the classic unexpected indent error. Here's the relevant code. The question is how do I fix it? def getNum(): firstNum = input("Please state what number to start at: ") secondNum = input("Please state swhat number to end at: ") if countingSubmenu == ...
Super-annoying indent error (Python)
the classic unexpected indent error. Here's the relevant code. The question is how do I fix it? def getNum(): firstNum = input("Please state what number to start at: ") secondNum = input("Please state swhat number to end at: ") if countingSubmenu == 3 or countingSubmenu == 4: thi...
[ "These three lines are using tabs instead of spaces:\n return firstNum, secondNum, thirdNum\n else:\n return firstNum, secondNum\n\nYou can see this pretty easily by attempting to edit the question, the tabs show up with a width of 8 spaces.\n" ]
[ 3 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0007071777_indentation_python.txt
Q: Python indent error. I can't figure out what's wrong here I'm using notepad++ which shows the different indents, etc. I keep getting an error code on line 26: return firstNum, secondNum, thirdNum Here's the full code. If anyone can see what's going on here, that would be great. I've already killed myself too muc...
Python indent error. I can't figure out what's wrong here
I'm using notepad++ which shows the different indents, etc. I keep getting an error code on line 26: return firstNum, secondNum, thirdNum Here's the full code. If anyone can see what's going on here, that would be great. I've already killed myself too much over this. I'm sorry if my first question didn't have a speci...
[ "The following three lines use tabs instead of spaces:\n return firstNum, secondNum, thirdNum\n else:\n return firstNum, secondNum\n\nYou can see this fairly easily by attempting to edit the question, you will see tabs show up as 8 spaces and the indentation will be visibly ...
[ 2, 0 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0007071970_indentation_python.txt
Q: Weird network behaviors with UDP sockets and python I made some python script and ran it both on my computer and some distant shell (some website that provides shell access). I'm using threads, pipes and UDP sockets to transfer data in a P2P fashion, so each script can both receive and send through the same socket...
Weird network behaviors with UDP sockets and python
I made some python script and ran it both on my computer and some distant shell (some website that provides shell access). I'm using threads, pipes and UDP sockets to transfer data in a P2P fashion, so each script can both receive and send through the same socket. To test if this works, I open one terminal on my comput...
[ "User Datagram Protocol(UDP) could easily stand for Unreliable Datagram Protocol. UDP provides no guarantees regarding delivery so if you need reliability you have to implement it yourself by resending messages.\nThat said, threading and multiprocessing and remote machines and networks are a lot of variables to di...
[ 0 ]
[]
[]
[ "multithreading", "network_programming", "pipe", "python" ]
stackoverflow_0007072505_multithreading_network_programming_pipe_python.txt
Q: How to extract webdata with Python, BeautiflSoup and mechanize from table I would like to extract the data from the table on this site: http://www.pgatour.com/r/stats/info/xm.html?101 And then save it as .csv and bring it into iWorks Numbers sheet. I've been trying with Python, BeautifulSoup and mechanize. I've be...
How to extract webdata with Python, BeautiflSoup and mechanize from table
I would like to extract the data from the table on this site: http://www.pgatour.com/r/stats/info/xm.html?101 And then save it as .csv and bring it into iWorks Numbers sheet. I've been trying with Python, BeautifulSoup and mechanize. I've been trying without knowledge by looking at other examples, but without success. ...
[ "In the main page, the tour stats seems to be being populated by JavaScript <div class=\"tourViewData\"> ... populateDDs();\nBS does not parse Javascript, see the many other SO questions on that.\n(I don't know how to solve that part. At worst, select and save that HTML selection as a local html file, as a workarou...
[ 4 ]
[]
[]
[ "beautifulsoup", "mechanize", "python" ]
stackoverflow_0007072139_beautifulsoup_mechanize_python.txt
Q: How to use IBM_DB with older versions of DB2? I want to connect Python to DB2 version 9.1 using IBM DB2 ODBC Driver. Following is my code to connect Python to DB2. This program is working in the later versions of IBM DB2. import ibm_db conn = ibm_db.connect("DSN=PDB2;DRIVER={IBM DB2 ODBC DRIVER};DATABASE=MDBASIS;...
How to use IBM_DB with older versions of DB2?
I want to connect Python to DB2 version 9.1 using IBM DB2 ODBC Driver. Following is my code to connect Python to DB2. This program is working in the later versions of IBM DB2. import ibm_db conn = ibm_db.connect("DSN=PDB2;DRIVER={IBM DB2 ODBC DRIVER};DATABASE=MDBASIS;PORT=1234;PROTOCOL=TCPIP;UID=username;PWD=password"...
[ "I think the problem is in the client ibm_db driver. Basically you can connect to any older version from all the languages. Try to get another db2 driver. If I were you I would install the db2 client which comes with several drivers which are located in sqllib.\n", "What version of ibm_db are you using? I am abl...
[ 0, 0, 0, 0 ]
[]
[]
[ "database_connection", "db2", "odbc", "python" ]
stackoverflow_0006198465_database_connection_db2_odbc_python.txt
Q: Including a formatted iterable as part of a larger formatted string In writing a class recently, I initially included a __repr__ method along the following lines: return "{}({!r}, {!r}, {!r})".format( self.__class__.__name__, self.arg1, self.arg2, sel...
Including a formatted iterable as part of a larger formatted string
In writing a class recently, I initially included a __repr__ method along the following lines: return "{}({!r}, {!r}, {!r})".format( self.__class__.__name__, self.arg1, self.arg2, self.arg3) Repeating the '{!r}' snippet like that feels wrong and would be ...
[ "If this is a pattern you're going to repeat, I'd probably use:\n# This is a static method or module-level function\ndef argrepr(name, *args):\n return '{}({})'.format(name, ', '.join(repr(arg) for arg in args))\n\ndef __repr__(self):\n return argrepr(self.__name__, self.arg1, self.arg2, self.arg3)\n\nor\n# T...
[ 9, 8, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007072938_python_python_3.x.txt
Q: Downloading files in twisted using queue I want to download a many files from queue using twisted and (for example ) 20 clients-threads. Any example ? A: from twisted.internet.defer import inlineCallbacks, DeferredQueue @inlineCallbacks def worker(queue): while 1: url = yield queue.get() # wait for...
Downloading files in twisted using queue
I want to download a many files from queue using twisted and (for example ) 20 clients-threads. Any example ?
[ "from twisted.internet.defer import inlineCallbacks, DeferredQueue\n\n@inlineCallbacks\ndef worker(queue):\n while 1:\n url = yield queue.get() # wait for a url from the queue\n\n if url is None: # insert None into the queue to kill workers\n queue.put(None)\n return # done\n\...
[ 9, 2 ]
[ "Use the select module to do this with polling, or the threading module to this with threads.\n" ]
[ -2 ]
[ "python", "twisted" ]
stackoverflow_0006914018_python_twisted.txt
Q: What is the most efficient way to do a ONE:ONE relation on google app engine datastore Even with all I do know about the AppEngine datastore, I don't know the answer to this. I'm trying to avoid having to write and run all the code it would take to figure it out, hoping someone already knows the answer. I have co...
What is the most efficient way to do a ONE:ONE relation on google app engine datastore
Even with all I do know about the AppEngine datastore, I don't know the answer to this. I'm trying to avoid having to write and run all the code it would take to figure it out, hoping someone already knows the answer. I have code like: class AddlInfo(db.Model) user = db.ReferenceProperty(User) otherstuff = d...
[ "Between those 2 options, the second is marginally cheaper, because you're determining the key by inference rather than looking it up in a remote index.\nAs Wooble said, it's cheaper still to just keep everything on one entity. Consider an Expando if you just need a way to store a bunch of optional, ad-hoc properti...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007071508_google_app_engine_python.txt
Q: Is it possible to use Selenium/Python without spawning a visible window? Can I use lxml with it? I expect to be able to save a page and then use a lxml.html.parse() but I was wondering if I could do it directly off a opened page? I'm using Ubuntu if it makes any difference. Edit: There's a method to use xpath dire...
Is it possible to use Selenium/Python without spawning a visible window? Can I use lxml with it?
I expect to be able to save a page and then use a lxml.html.parse() but I was wondering if I could do it directly off a opened page? I'm using Ubuntu if it makes any difference. Edit: There's a method to use xpath directly(find_element_by_xpath), so I guess I don't need lxml. But to save the page all you have to do is ...
[ "To answer the 'use Selenium without spawning a visible window' question, yes you can use PyVirtualDisplay on Ubunutu easily.\nfrom pyvirtualdisplay import Display\nfrom selenium import webdriver\n\ndisplay = Display(visible=0, size=(800, 600))\ndisplay.start()\n\n# now Firefox will run in a virtual display. \n# yo...
[ 2 ]
[]
[]
[ "firefox", "linux", "lxml", "python", "selenium" ]
stackoverflow_0007020432_firefox_linux_lxml_python_selenium.txt
Q: Installing PyGST with Cygwin I've given up on the OSSBuild of PyGST (Gstreamer) due to several major bugs. Instead, I am building from source myself. However, I have hit a snag. I am running this build in Cygwin. After unpacking the tarball, I run ./configure in the unpacked folder. I get the following error after...
Installing PyGST with Cygwin
I've given up on the OSSBuild of PyGST (Gstreamer) due to several major bugs. Instead, I am building from source myself. However, I have hit a snag. I am running this build in Cygwin. After unpacking the tarball, I run ./configure in the unpacked folder. I get the following error after a little while: configure: error...
[ "You need to tell it where to look for the headers from that GStreamer build, or copy them to (the cygwin version of) /usr/include or /usr/local/incude.\nTry ./configure --help to see what option would let you pass the header dir. Also, back in the GStreamer dir, take a look in the makefile -- it may have already i...
[ 0 ]
[]
[]
[ "build", "compilation", "cygwin", "gstreamer", "python" ]
stackoverflow_0007073527_build_compilation_cygwin_gstreamer_python.txt
Q: comparing lists at a previous index I have got 2 lists for which I would like to compare to one index before : for (min,max) in zip(csv_parse(2010)['min'],csv_parse(2010)['max']): basically I would like something like this : if min > min(back one increment) and max < max (back on increment) then, do something . T...
comparing lists at a previous index
I have got 2 lists for which I would like to compare to one index before : for (min,max) in zip(csv_parse(2010)['min'],csv_parse(2010)['max']): basically I would like something like this : if min > min(back one increment) and max < max (back on increment) then, do something . Thanks !
[ "from itertools import izip\nprev_min, prev_max = float('inf'), float('-inf')\n\nfor new_min, new_max in izip(csv_parse(2010)['min'], csv_parse(2010)['max']):\n if (new_min > prev_min) and (new_max < prev_max):\n #do something\n prev_min, prev_max = new_min, new_max\n\nSwitch the values of prev_min and...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007073707_python.txt
Q: getaddrinfo unable to resolve host I'm having a weird problem. I have this Python application and when I try to open a url in the application, for instance urllib2.urlopen("http://google.com", None) I get the following error: IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known How...
getaddrinfo unable to resolve host
I'm having a weird problem. I have this Python application and when I try to open a url in the application, for instance urllib2.urlopen("http://google.com", None) I get the following error: IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known However when I do the same thing on the pyt...
[ "Just see that you don't have HTTP_PROXY environment variable set which is preventing this. (In which case, that would be a bad error message. Given the proper directory and try again, like \nimport urllib\nr = urlib.urlopen('http://www.google.com')\nprint r.read()\n\n" ]
[ 1 ]
[]
[]
[ "dns", "macos", "osx_snow_leopard", "python", "urllib2" ]
stackoverflow_0007073788_dns_macos_osx_snow_leopard_python_urllib2.txt
Q: Problems in the io module for python I am currently running python version 2.5.2 in my system and I am having some problems regarding io module. The system shows "No module named io" found. I wanted to ask if there is anyway I can get io module in my system. I couldn't install it using pip or easy_install. Any alt...
Problems in the io module for python
I am currently running python version 2.5.2 in my system and I am having some problems regarding io module. The system shows "No module named io" found. I wanted to ask if there is anyway I can get io module in my system. I couldn't install it using pip or easy_install. Any alternatives. I can't upgrade my python versi...
[ "If you can't do what you want with the builtin file object (or simply the builtin open function), the only analogs to functionality in the io library available in Python 2 are the StringIO and cStringIO modules.\nIf you give us more information about what features of io you need, or what package you're trying to u...
[ 2 ]
[ "Update your Python.\nIf you don't have the resources to build it from source yourself, then go to Activestate here http://www.activestate.com/activepython/downloads and download the AS version for Linux. It can be installed to your home directory and is entirely separate from the Python that is installed with the ...
[ -2 ]
[ "python" ]
stackoverflow_0007073645_python.txt
Q: What python based ajax push servers are good to work with I have a web application im currently working on in python. I'm using Django as my web framework currently. I intend to integrate real-time web features into the application using ajax push. However, I'm a bit confused as to what python based push server i ...
What python based ajax push servers are good to work with
I have a web application im currently working on in python. I'm using Django as my web framework currently. I intend to integrate real-time web features into the application using ajax push. However, I'm a bit confused as to what python based push server i should adopt. I've heard of a few of them, Orbited, Gevent, Tor...
[ "A lot of people choose gevent for webapps with real-time features because of the speed, ease of use and a number of supporting packages.\nTake a look at these packages:\n\ngevent-socketio\ndjango-socketio\n\nand these tutorials:\n\nEvented Django part one: Socket.IO and gevent\nNew and hot, part 4: Pyramid, Socket...
[ 2, 0, 0 ]
[]
[]
[ "ajax_push", "comet", "python", "real_time" ]
stackoverflow_0006493444_ajax_push_comet_python_real_time.txt
Q: Different color for different choices in tkinter option menu I am using Python and Tkinter. I have an option menu with three choices with "on" being one of them. I want to make "on" be green when I select it. I don't mean the font. I want the background of the option menu to be green when I select "on" while the o...
Different color for different choices in tkinter option menu
I am using Python and Tkinter. I have an option menu with three choices with "on" being one of them. I want to make "on" be green when I select it. I don't mean the font. I want the background of the option menu to be green when I select "on" while the other options will just be default gray. How can I do this? I've s...
[ "file this under U, for ugly:\nfrom Tkinter import *\n\nOPTIONS = (\n \"egg\",\n \"go\",\n \"spam\"\n)\n\ncontrolsMap = {}\n\nroot = Tk()\n\ndef callbackFunc(name, index, mode):\n value = root.getvar(name) #getvar: return the value of Tcl variable NAME\n widget = controlsMap[name]\n if value == 'g...
[ 1, 0, 0 ]
[]
[]
[ "colors", "optionmenu", "python", "tkinter" ]
stackoverflow_0007002657_colors_optionmenu_python_tkinter.txt
Q: How do you use a python decorator on a function whose definition you cannot access? Suppose that for administrative reasons I do not have write access to module xxx. I want to do something like: from xxx import yyy @myDeco yyy which of course fails. I think I can do yyy = myDeco(yyy) but is there a way to use ...
How do you use a python decorator on a function whose definition you cannot access?
Suppose that for administrative reasons I do not have write access to module xxx. I want to do something like: from xxx import yyy @myDeco yyy which of course fails. I think I can do yyy = myDeco(yyy) but is there a way to use the @myDeco" notation ? Or is this only permitted immediately before a def?
[ "The @ syntax is only allowed before a def or class.\n", "In the Python reference documentation, Compound Statements section, it says:\ndecorated ::= decorators (classdef | funcdef)\ndecorators ::= decorator+\ndecorator ::= \"@\" dotted_name [\"(\" [argument_list [\",\"]] \")\"] NEWLINE\nfuncdef ...
[ 7, 4 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0007073738_decorator_python.txt
Q: Best way to override a installed packge method I am using django-compress for compression. According to need I want to change on of the functions in ..../dist-packages/compress/utils.py. How can I override this function. A: import compress.utils utils.compress.function_to_override = overriding_function Monkey p...
Best way to override a installed packge method
I am using django-compress for compression. According to need I want to change on of the functions in ..../dist-packages/compress/utils.py. How can I override this function.
[ "import compress.utils\nutils.compress.function_to_override = overriding_function\n\nMonkey patch it. You'll need to do this before utils is imported anywhere else.\nAlternatively, you could create a new Python module, like this:\n# fakeutils.py\nfrom compress.utils import *\n\n# make the following line match exact...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007074829_python.txt
Q: How to access member function as member variable in python classes? I've got a class: class Foo(): def bar(name): return something and i want to have foo = Foo() foo.name returning the same as foo.bar('name'). Is it possible? A: This will automatically use bar if the attribute doesn't exist: clas...
How to access member function as member variable in python classes?
I've got a class: class Foo(): def bar(name): return something and i want to have foo = Foo() foo.name returning the same as foo.bar('name'). Is it possible?
[ "This will automatically use bar if the attribute doesn't exist:\nclass Foo(object):\n def bar(self, name):\n return name\n def bar2(self, attr, value):\n print attr, value\n def __getattr__(self, attr):\n return self.bar(attr)\n def __setattr__(self, attr, value):\n self.bar...
[ 3, 1, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007075189_class_python.txt
Q: Python subprocess killing I have problem killing sub processes. The following piece of code is used for creating the sub process- while(not myQueue.empty()): p=Popen(myQueue.get(),shell=True,stdin=PIPE,stderr=PIPE) I'm creating processes by iterating until the queue(which has commands in it) is empty. ...
Python subprocess killing
I have problem killing sub processes. The following piece of code is used for creating the sub process- while(not myQueue.empty()): p=Popen(myQueue.get(),shell=True,stdin=PIPE,stderr=PIPE) I'm creating processes by iterating until the queue(which has commands in it) is empty. The variable p is global and is...
[ "I suspect you may be having issues as you're not declaring stopPressed inside your stopAll() function as global, by example,\n>>> fred = '20'\n>>> def updateFred(age):\n... fred=age\n>>> updateFred(40)\n>>> fred\n'20'\n>>> def updateFred(age):\n... global fred\n... fred=age\n>>> updateFred(40)\n>>> fre...
[ 1, 0, 0, 0 ]
[]
[]
[ "button", "kill_process", "python", "tk_toolkit", "user_interface" ]
stackoverflow_0007055503_button_kill_process_python_tk_toolkit_user_interface.txt
Q: python method variables and Objects created in method So I know that in Python variables declared in a method are not visible outside of it. But what is their life cycle? I would expect that a variable declared inside a method is created each time that method is called. I'm asking because of the following situati...
python method variables and Objects created in method
So I know that in Python variables declared in a method are not visible outside of it. But what is their life cycle? I would expect that a variable declared inside a method is created each time that method is called. I'm asking because of the following situation. I have a method as follows(this is used with cherrypy, ...
[ "def __init__(self, display_name= \"\", fields= [], values= [], operations= [])\n\nThe lists are created only once. So if you modify them the next call will have the modified lists. If you do not want this behaviour, simply use None as the default value and add something like this:\nif fields is None:\n fields =...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007075533_python.txt
Q: What is the second argument in the code used to convert from string to int in Python? I have found some strange syntax in python: int(array[0], 32) array[0] is some string, but what exactly is the second parameter for? And can somebody please explain this int() syntax, is it function or casting? A: Help on cl...
What is the second argument in the code used to convert from string to int in Python?
I have found some strange syntax in python: int(array[0], 32) array[0] is some string, but what exactly is the second parameter for? And can somebody please explain this int() syntax, is it function or casting?
[ "Help on class int in module __builtin__:\n\nclass int(object)\n | int(x[, base]) -> integer\n |\n | Convert a string or number to an integer, if possible. A floating point\n | argument will be truncated towards zero (this does not include a string\n | representation of a floating point number!) When converti...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007075179_python.txt
Q: How do I debug HTTPS post requests from my commandline program? I am trying to write a Python program that POSTs a build request to a Jenkins server over HTTPS. I have tried PycURL, which works well, but am now trying to replace that with standard library facilities. The revised program receives a 404 response fro...
How do I debug HTTPS post requests from my commandline program?
I am trying to write a Python program that POSTs a build request to a Jenkins server over HTTPS. I have tried PycURL, which works well, but am now trying to replace that with standard library facilities. The revised program receives a 404 response from the server however, so I would like to inspect both versions of the...
[ "If you can specify a proxy with your application then take a look at Fiddler. It will man in the middle HTTPS requests and give you a good overview of exactly whats going in and out. As also mentioned WireShark may be of use to you if you cannot use a proxy as it will capture the raw traffic but it can be fiddly t...
[ 1, 0, 0 ]
[]
[]
[ "http", "http_post", "networking", "python" ]
stackoverflow_0007075312_http_http_post_networking_python.txt
Q: Twitter Auth with Django What is the best twitter auth plugin for Django. I do not understand why django-social-auth and django socialregistration suck so badly, but authentication to both facebook + twitter is not that hard and there seems to be no good django packages for either. Please prove me wrong. Thanks A...
Twitter Auth with Django
What is the best twitter auth plugin for Django. I do not understand why django-social-auth and django socialregistration suck so badly, but authentication to both facebook + twitter is not that hard and there seems to be no good django packages for either. Please prove me wrong. Thanks
[ "I've attempted using allauth, but haven't gotten it to work.\nThis post lead me to it:\nhttp://hackerluddite.wordpress.com/2011/05/17/review-of-4-django-social-auth-apps/\nLet us know what you find that works.\n", "I've also tested django-social-auth and django-socialregistration and they sucked. Things like eas...
[ 1, 1 ]
[]
[]
[ "authentication", "django", "facebook", "python", "twitter" ]
stackoverflow_0007073088_authentication_django_facebook_python_twitter.txt
Q: Why "m2m_changed" signals never gets fired from the admin site? Well, dont know if this is a bug or if I've a concept error. But try to test it: A simple generic test: from django.dispatch import receiver from django.db.models.signals import m2m_changed @receiver(m2m_changed) def test_handler(sender, instance, ac...
Why "m2m_changed" signals never gets fired from the admin site?
Well, dont know if this is a bug or if I've a concept error. But try to test it: A simple generic test: from django.dispatch import receiver from django.db.models.signals import m2m_changed @receiver(m2m_changed) def test_handler(sender, instance, action, reverse, model, pk_set, **kwargs): import sys print>>...
[ "I tried it on one of my models it was working perfectly. It would me much useful if you post all the contents of the model file code.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "signals" ]
stackoverflow_0007059285_django_python_signals.txt
Q: HTTP framework for a python based server serving mobile applications I am working on building a python powered back-end server for a mobile application. I am using MongoDB hosted on the Cloud for storage. The communication between the Application and the server will be mostly JSON. There wont be any HTML involved ...
HTTP framework for a python based server serving mobile applications
I am working on building a python powered back-end server for a mobile application. I am using MongoDB hosted on the Cloud for storage. The communication between the Application and the server will be mostly JSON. There wont be any HTML involved in this transfer as such. I am looking for a framework to build my server...
[ "I'd recommend bottle or flask, both of which are very minimal and impose no constraints on you whatsoever. In the case of bottle, it's particularly easy to build a simple RESTful server since it will automatically return JSON from a route that returns a dict:\nfrom bottle import route, run\n\n@route('/user_info/:i...
[ 3, 0, 0 ]
[]
[]
[ "cherrypy", "mongodb", "python", "web.py", "web_frameworks" ]
stackoverflow_0007070801_cherrypy_mongodb_python_web.py_web_frameworks.txt
Q: Sorting the content of a dictionary by the value and by the key Sorting the content of a dictonary by the value has been throughly described already, so it can be acheived by something like this: d={'d':1,'b':2,'c':2,'a':3} sorted_res_1= sorted(d.items(), key=lambda x: x[1]) # or from operator import itemgetter ...
Sorting the content of a dictionary by the value and by the key
Sorting the content of a dictonary by the value has been throughly described already, so it can be acheived by something like this: d={'d':1,'b':2,'c':2,'a':3} sorted_res_1= sorted(d.items(), key=lambda x: x[1]) # or from operator import itemgetter sorted_res_2 = sorted(d.items(), key=itemgetter(1)) My question is,...
[ "The sorted key parameter can return a tuple. In that case, the first item in the tuple is used to sort the items, and the second is used to break ties, and the third for those still tied, and so on...\nIn [1]: import operator\n\nIn [2]: d={'d':1,'b':2,'c':2,'a':3}\n\nIn [3]: sorted(d.items(),key=operator.itemgette...
[ 4, 2, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0007076108_dictionary_python_sorting.txt
Q: How can I get the main window's handle in Python? In python, I enumerate top-level windows through EnumWindows, and also I enumerate the processes through EnumProcesses. Then in the python script, I put all the window handles which belongs to the same pid into one list (I did this through GetWindowThreadProcessId)...
How can I get the main window's handle in Python?
In python, I enumerate top-level windows through EnumWindows, and also I enumerate the processes through EnumProcesses. Then in the python script, I put all the window handles which belongs to the same pid into one list (I did this through GetWindowThreadProcessId). Later I found out something: there are 3 window handl...
[ "Processes sometimes create invisible windows for their own purposes. You should ignore them (use IsWindowVisible function).\n", "To investigate this kind of things your best friend is Spy++, that comes with several versions of Visual Studio, if you can get it.\nAccording to it, notepad.exe creates three top-leve...
[ 5, 4 ]
[]
[]
[ "handle", "python", "windows" ]
stackoverflow_0007076056_handle_python_windows.txt
Q: Algorithm for generating list of unique tuples with specific properties I need to label N objects with unique tuples (A, B, C), where A < B < C and the maximal number of identical As is M. The same for Bs and Cs each. Among all solutions one with the lowest highest value of C is searched for. (This last sentence m...
Algorithm for generating list of unique tuples with specific properties
I need to label N objects with unique tuples (A, B, C), where A < B < C and the maximal number of identical As is M. The same for Bs and Cs each. Among all solutions one with the lowest highest value of C is searched for. (This last sentence means: if one of two solutions has a highest C of 4 and the other of 5, then t...
[ "I think this code meets your requirements and always generates the solution with the lowest possible C. Not quite using itertools however.\ndef generateTuples(N, M):\n done = 0\n counters = {}\n for C in range(3, N + 3):\n for B in range(2, C):\n for A in range(1, B):\n if (counters.get('A%i' % A...
[ 3 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0007076153_algorithm_python.txt
Q: Python 3.[12] urllib i am working on a little script grabbing some files from a website. First i create a list of potential urls within the website. This worked fine with Python 3.1 but not with Python 3.2. I guess it is a question on encoding but i am not sure how to realise it in an elegant way. Can you help me?...
Python 3.[12] urllib
i am working on a little script grabbing some files from a website. First i create a list of potential urls within the website. This worked fine with Python 3.1 but not with Python 3.2. I guess it is a question on encoding but i am not sure how to realise it in an elegant way. Can you help me? def get_urls(username, pa...
[ "The problem should be here:\n\nlogin_data = urllib.parse.urlencode({'login' : username, 'password' : password})\nopener.open(BASE_URL+\"/bg/login\", login_data)\n\nurllib.parse.urlencode outputs string not an iterable.\n" ]
[ 0 ]
[]
[]
[ "encoding", "python", "python_3.x", "urllib" ]
stackoverflow_0007076026_encoding_python_python_3.x_urllib.txt
Q: Global variable not working in Amazon Web Service I got two handlers in Amazon Web Service. I want to share some data in both so i used global variable. where one is used to fetch some value and put it to the global variable when another handler called so is can use same value what is set in global variable, but i...
Global variable not working in Amazon Web Service
I got two handlers in Amazon Web Service. I want to share some data in both so i used global variable. where one is used to fetch some value and put it to the global variable when another handler called so is can use same value what is set in global variable, but it is giving default value in another handler and i have...
[ "Never do this.\nIn production, Django (I presume this is Django, although you don't say so - I've added it to the tags) runs in a multi-process environment. Each process has its own copy of the global variables. There is no way to ensure that subsequent requests are served by the same process.\nIf you need to keep...
[ 1 ]
[]
[]
[ "amazon_web_services", "apache2", "django", "python", "webfaction" ]
stackoverflow_0007075276_amazon_web_services_apache2_django_python_webfaction.txt
Q: Can a Django ModelForm display a custom representation of stored values? In my model, percentage data is stored as fractional values in the 0.0-1.0 range. Because they are percentages, I want the user to view and edit the values in the 0.0-100.0 range. What is the preferred way of transforming data between its sto...
Can a Django ModelForm display a custom representation of stored values?
In my model, percentage data is stored as fractional values in the 0.0-1.0 range. Because they are percentages, I want the user to view and edit the values in the 0.0-100.0 range. What is the preferred way of transforming data between its stored value and the displayed value? Note that the format depends on another ins...
[ "Personally, I'd probably try to create a django.forms.FloatField subclass and a django.forms.TextInput subclass, kind of like this:\nclass PercentageInput(TextInput):\n def render(self, name, value, attrs=None):\n try:\n value = float(value)\n value *= 100\n except ValueError...
[ 5 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0007076329_django_forms_python.txt
Q: Rounding decimals in nested data structures in Python I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} Is there a simple pythonic way to print such a variable but round...
Rounding decimals in nested data structures in Python
I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a particular c...
[ "This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone.\nimport collections\nimport numbers\ndef pformat(thing, formatfunc):\n if isinstance(thing, dict):\n return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems())\n if...
[ 5, 1, 0 ]
[]
[]
[ "printing", "python", "rounding", "string_formatting" ]
stackoverflow_0007076254_printing_python_rounding_string_formatting.txt
Q: Tornado http server's bind method In httpserver.py, there is a bind method, at the end of this method is the code like this: sock.bind(sockaddr) sock.listen(128) self._sockets[sock.fileno()] = sock if self._started: self.io_loop.add_handler(sock.fileno(), self._handle_events, ioloop.I...
Tornado http server's bind method
In httpserver.py, there is a bind method, at the end of this method is the code like this: sock.bind(sockaddr) sock.listen(128) self._sockets[sock.fileno()] = sock if self._started: self.io_loop.add_handler(sock.fileno(), self._handle_events, ioloop.IOLoop.READ) It means when a socket co...
[ "I just had a quick look at the source, and it seems to work like this:\nTornado doesn't monitor the sockets itself, it passes this job onto the operating system, using epoll (Linux) or select. The call to self.io_loop.add_handler just adds a callback for when a new connection is available.\nClient connections are ...
[ 0 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0007073328_python_tornado.txt
Q: Want to timestamp two files I have two lines in my views.py file. views.py os.popen3("mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup.sql") os.popen3("gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup.gz" I want to be able to do is...
Want to timestamp two files
I have two lines in my views.py file. views.py os.popen3("mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup.sql") os.popen3("gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup.gz" I want to be able to do is in each of these files backup.sq...
[ "from subprocess import Popen, PIPE\nfrom datetime import datetime\n\n# yes, this is me being lazy and not wanting to write a format string.\ndate = datetime.today().isoformat().split('T')[0]\n\nmysql = \"mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup-{}.sql\".format(date)\...
[ 2 ]
[]
[]
[ "django", "gzip", "mysql", "python", "timestamp" ]
stackoverflow_0007077091_django_gzip_mysql_python_timestamp.txt
Q: Python-compatible distributed messaging/task system (like Celery) that uses domain sockets Is there anything like Celery that works with unix domain sockets? My current host (dreamhost) forbids the running of servers that listen on IP sockets, so I need something that will work with domain sockets. Obviously, easi...
Python-compatible distributed messaging/task system (like Celery) that uses domain sockets
Is there anything like Celery that works with unix domain sockets? My current host (dreamhost) forbids the running of servers that listen on IP sockets, so I need something that will work with domain sockets. Obviously, easier solutions are preferred, but any message queuing software with a python client library and do...
[ "You should definitely have a look at zeromq python bindings, which are compatible with domain sockets.\n" ]
[ 2 ]
[]
[]
[ "celery", "message_queue", "python", "task_queue", "unix_socket" ]
stackoverflow_0007076944_celery_message_queue_python_task_queue_unix_socket.txt
Q: Converting non-english characters in Python I'm working on a Google App Engine project. When I user jQuery to send a serialized form as a html post, I get some encoded charcters instead of non-english characters. Using pure HTML is not a problem. In the serialized result, I get: ".... defaultgroupcity=Lang%C3%A5 ....
Converting non-english characters in Python
I'm working on a Google App Engine project. When I user jQuery to send a serialized form as a html post, I get some encoded charcters instead of non-english characters. Using pure HTML is not a problem. In the serialized result, I get: ".... defaultgroupcity=Lang%C3%A5 ...", but I should get: "defaultgroupcity=Langå". ...
[ "You need urllib.unquote() and certainly The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) and the Python Unicode HOWTO.\nYour first temptation will be to think “this is way to complicated for å”, and it is, but blame humanity for the gener...
[ 2, 0 ]
[]
[]
[ "character_encoding", "google_app_engine", "jquery", "python" ]
stackoverflow_0007064583_character_encoding_google_app_engine_jquery_python.txt
Q: Why Tkinter function inserts text at text widget only after the function is finished? I have a question to make.If i have a function inserting an item from a list in a text widget and then doing something with that item,it first finishes processing all the items and then does the insert on the text widget. Here is...
Why Tkinter function inserts text at text widget only after the function is finished?
I have a question to make.If i have a function inserting an item from a list in a text widget and then doing something with that item,it first finishes processing all the items and then does the insert on the text widget. Here is a simple code demonstrating what I say: from Tkinter import* import Tkinter as tk list = ...
[ "The text widget (and all widgets) are only refreshed when the event loop is entered. While your code is in a loop, no paint events are processed. The simplest solution is to call update_idletasks to update the screen -- refreshing the screen is considered an \"idle\" task.\nFor a little more information, see the a...
[ 1 ]
[]
[]
[ "function", "python", "tkinter" ]
stackoverflow_0007075852_function_python_tkinter.txt
Q: [python]: problem about python string literals code goes below: line = r'abc\def\n' rline = re.sub('\\\\', '+', line) # then rline should be r'abc+def+n' Apparently, I just want to replace the backslashes in line with '+'. What I thought was that a backslash in line can be expressed as '\', then why should I use ...
[python]: problem about python string literals
code goes below: line = r'abc\def\n' rline = re.sub('\\\\', '+', line) # then rline should be r'abc+def+n' Apparently, I just want to replace the backslashes in line with '+'. What I thought was that a backslash in line can be expressed as '\', then why should I use '\\' to get the re.sub work right. I'm confused.
[ "It's a good habit to always use raw strings when dealing with regex patterns:\nIn [45]: re.sub(r'\\\\', r'+', line)\nOut[45]: 'abc+def+n'\n\nTo answer your question though, Python interprets '\\\\\\\\' as two backslash characters:\nIn [44]: list('\\\\\\\\')\nOut[44]: ['\\\\', '\\\\']\n\nAnd the rules of regex inte...
[ 7, 4, 2 ]
[]
[]
[ "backslash", "python" ]
stackoverflow_0007077419_backslash_python.txt
Q: sys.argv as bytes in Python 3k As Python 3k introduces strict distinction between strings and bytes, command line arguments in the array sys.argv are presented as strings. Sometimes it is necessary to treat the arguments as bytes, e.g. when passing a path that needn't to be in any particular character encoding in ...
sys.argv as bytes in Python 3k
As Python 3k introduces strict distinction between strings and bytes, command line arguments in the array sys.argv are presented as strings. Sometimes it is necessary to treat the arguments as bytes, e.g. when passing a path that needn't to be in any particular character encoding in Unix. Let's see an example. A brief ...
[ "Note that the error is a UnicodeEncodeError rather than a UnicodeDecodeError. Python is preserving the exact bytes passed on the command line (via the PEP 383 surrogateescape error handler), but those bytes are not valid UTF-8 and hence can't be encoded as such for writing to the console.\nThe best way to deal wit...
[ 9, 1 ]
[]
[]
[ "python", "python_3.x", "string", "unicode" ]
stackoverflow_0006981594_python_python_3.x_string_unicode.txt
Q: pylint balks on reference to __package__ I'm using __package__ in setup.py to refer to the top-level name of the package it's supposed to test, build, install, etc.. However, pylint objects: Module 'mian.mian' has no '__package__' member This works fine in ipython: from mian import mian as package package.__dict_...
pylint balks on reference to __package__
I'm using __package__ in setup.py to refer to the top-level name of the package it's supposed to test, build, install, etc.. However, pylint objects: Module 'mian.mian' has no '__package__' member This works fine in ipython: from mian import mian as package package.__dict__ ... '__package__': 'mian', Is pylint doing...
[ "This is now a ticket on Pylint's tracker: http://www.logilab.org/ticket/73668\n" ]
[ 2 ]
[]
[]
[ "import", "pylint", "python" ]
stackoverflow_0004979150_import_pylint_python.txt
Q: Generating dynamic graphs I'm building a web application in Django and I'm looking to generate dynamic graphs based on the data. Previously I was using the Google Image Charts, but I ran into significant limitations with the api, including the URL length constraint. I've switched to using matplotlib to create my c...
Generating dynamic graphs
I'm building a web application in Django and I'm looking to generate dynamic graphs based on the data. Previously I was using the Google Image Charts, but I ran into significant limitations with the api, including the URL length constraint. I've switched to using matplotlib to create my charts. I'm wondering if this w...
[ "You may be able to scale matplotlib for charting if you can render the charts outside the request/response cycle with something like Celery. You would have to manage the storage of the rendered chart as well as invaliding it when the data changes. This would really depend on how often the data changes and how ofte...
[ 1, 0, 0 ]
[]
[]
[ "graphics", "python" ]
stackoverflow_0007078010_graphics_python.txt
Q: what's the tornado ioloop, and tornado's workflow? i want to know tornado's internal workflow, and have seen this article, it's great, but something i just can't figure out within the ioloop.py, there is such a function def add_handler(self, fd, handler, events): """Registers the given handler to receive the g...
what's the tornado ioloop, and tornado's workflow?
i want to know tornado's internal workflow, and have seen this article, it's great, but something i just can't figure out within the ioloop.py, there is such a function def add_handler(self, fd, handler, events): """Registers the given handler to receive the given events for fd.""" self._handlers[fd] = handler ...
[ "I'll see if I can answer your questions in order:\n\nHere _impl is whichever socket polling mechanism is available, epoll on Linux, select on Windows. So self._impl.register(fd, events | self.ERROR) passes the \"wait for some event\" request to the underlying operating system, also specifically including error eve...
[ 31 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0007072701_python_tornado.txt
Q: Using TCL extensions to set native window style in Tkinter pythonware.com/library/tkinter/introduction/… documents a overrideredirect method that will remove thetitlebar and borders, if that is not enough you must set the native window style, I'm not sure if Tkinter gives you that kind of low-level acc...
Using TCL extensions to set native window style in Tkinter
pythonware.com/library/tkinter/introduction/… documents a overrideredirect method that will remove thetitlebar and borders, if that is not enough you must set the native window style, I'm not sure if Tkinter gives you that kind of low-level access, if not, try the something like twapi.magicsplat.com/ui...
[ "You can do this using a combination of the Python win32 api packages and Tkinter. What you need to know is that a Tk window is the client section of a Win32 window. The window manager interactions are handled using a wrapper that is the parent of Tk window itself. If you have a Tkinter window 'w' then you can crea...
[ 4, 2 ]
[]
[]
[ "python", "tcl", "tkinter" ]
stackoverflow_0003306189_python_tcl_tkinter.txt
Q: Inheritance : transform a base class instance to a child class instance I have an instance of a base class, and then I want to make it an instance of a child class of this base class. Maybe I'm taking the problem in a wrong way and there's something important I didn't understand in OOP. Code is only there to illus...
Inheritance : transform a base class instance to a child class instance
I have an instance of a base class, and then I want to make it an instance of a child class of this base class. Maybe I'm taking the problem in a wrong way and there's something important I didn't understand in OOP. Code is only there to illustrate and a very different approach can be suggested. Any help appreciated. c...
[ "class FastCar(Car):\n def __init__(self, color, max_speed=100):\n Car.__init__(self, color)\n self.max_speed = max_speed\n\n def drive_fast(self):\n print \"Driving at %s mph\" %self.max_speed\n\n @staticmethod\n def fromOtherCar(car):\n return FastCar(car.color)\n\nactually...
[ 3, 0, 0, 0 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0007078134_inheritance_oop_python.txt