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: Printing a line by updating an already outputted line Forgive me if the title is not lucid, but I could not better describe it in a single sentence. Consider I have the following in a loop, which increments counter each time it runs. output_string = 'Enter the number [{0}]'.format(counter) When I do a print outpu...
Printing a line by updating an already outputted line
Forgive me if the title is not lucid, but I could not better describe it in a single sentence. Consider I have the following in a loop, which increments counter each time it runs. output_string = 'Enter the number [{0}]'.format(counter) When I do a print output_string, the output goes like: Enter the number [1]: Whe...
[ "If your script will be running on Unix/Linux you could use the curses module.\n", "Try this\nprint('enter the number[1]', end='\\r' )\n\nIf you're using Python 2.7, don't forget from __future__ import print_function.\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003677758_python.txt
Q: How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python (version 2.1)? Couple months ago I have asked the same question but in the context of older version of ZSI (How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python?). Now, in the new version of ZSI 2.1 there...
How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python (version 2.1)?
Couple months ago I have asked the same question but in the context of older version of ZSI (How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python?). Now, in the new version of ZSI 2.1 there is no tacefile parameter). I tried to find a documentation for the new version but I faild. Does anyo...
[ "For debugging I have found less interfering solution using wireshark to trace the TCP packages. It looks like that:\n\n", "I had this same problem. My workaround was to modify the dispatch.py file that comes with ZSI.\nI created a logging function (logmessage) for my app that would store SOAP messages into a dat...
[ 3, 1 ]
[]
[]
[ "python", "soap", "zsi" ]
stackoverflow_0003676409_python_soap_zsi.txt
Q: Static library (.lib) to Python project is it possible to import modules from .lib library to Python program (as simple as .dll)? A: In theory, yes; in practice, probably not -- and certainly not as simply as a DLL. Static libraries are essentially just collections of object files, and need a full linker to cor...
Static library (.lib) to Python project
is it possible to import modules from .lib library to Python program (as simple as .dll)?
[ "In theory, yes; in practice, probably not -- and certainly not as simply as a DLL. Static libraries are essentially just collections of object files, and need a full linker to correctly resolve all relocation references they may contain. It might be possible to take your static library and simply link its conten...
[ 4, 2, 0, 0 ]
[]
[]
[ "dll", "python", "static_libraries" ]
stackoverflow_0003668373_dll_python_static_libraries.txt
Q: Why does the tkinter progress bar makes things so much slower? I have the following code for extracting a tar.gz file whilst keeping tabs on the progress: from __future__ import division import tarfile import os theArchive = "/Users/Dennis/Instances/atlassian-jira-enterprise-4.1.2-standalone.tar.gz" a = tarfile....
Why does the tkinter progress bar makes things so much slower?
I have the following code for extracting a tar.gz file whilst keeping tabs on the progress: from __future__ import division import tarfile import os theArchive = "/Users/Dennis/Instances/atlassian-jira-enterprise-4.1.2-standalone.tar.gz" a = tarfile.open(theArchive) tarsize = 0 print "Computing total size" for tari...
[ "How big are the files in your archive? You are almost certainly updating the progress bar a lot more than you need to -- it's common to include a check in your set() function so that it just returns without updating if the change from the last value is too small. With a 300px canvas there's definitely no point i...
[ 5 ]
[]
[]
[ "python", "tar", "tkinter" ]
stackoverflow_0003677971_python_tar_tkinter.txt
Q: How to require a key_name when creating model classes with App Engine? I want to require that one of my model classes specify my own custom key as the key_name, that way I can always rely on it being there. How can I require this? For example, I may have a model class such as: class Account(db.Model): user ...
How to require a key_name when creating model classes with App Engine?
I want to require that one of my model classes specify my own custom key as the key_name, that way I can always rely on it being there. How can I require this? For example, I may have a model class such as: class Account(db.Model): user = db.UserProperty(required=True) email = db.EmailProperty() And I want ...
[ "You can make all instantiation of the Account model go through a simple factory function (maybe name the class itself _Account to clarify to other coders on the project that the class itself is meant to be private):\ndef make_account(key_name=None, **k):\n if key_name is None:\n raise ValueError('Must sp...
[ 2, 2, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003673721_google_app_engine_python_web_applications.txt
Q: Using Python, getting the name of files in a zip archive I have several very large zip files available to download on a website. I am using Flask microframework (based on Werkzeug) which uses Python. Is there a way to show the contents of a zip file (i.e. file and folder names) - to someone on a webpage - without ...
Using Python, getting the name of files in a zip archive
I have several very large zip files available to download on a website. I am using Flask microframework (based on Werkzeug) which uses Python. Is there a way to show the contents of a zip file (i.e. file and folder names) - to someone on a webpage - without actually downloading it? As in doing the working out server si...
[ "Sure, have a look at zipfile.ZipFile.namelist(). Usage is pretty simple, as you'd expect: you just create a ZipFile object for the file you want, and then namelist() gives you a list of the paths of files stored in the archive.\nwith ZipFile('foo.zip', 'r') as f:\n names = f.namelist()\nprint names\n# ['file1',...
[ 18, 4 ]
[]
[]
[ "flask", "python", "werkzeug", "zip" ]
stackoverflow_0003678842_flask_python_werkzeug_zip.txt
Q: Install two python modules with same name What's the best way to install two python modules with the same name? I currently depend on two different facebook libraries: pyfacebook and Facebook's new python-sdk. Both of these libraries install themselves as the module 'facebook'. I can think of a bunch of hacky solu...
Install two python modules with same name
What's the best way to install two python modules with the same name? I currently depend on two different facebook libraries: pyfacebook and Facebook's new python-sdk. Both of these libraries install themselves as the module 'facebook'. I can think of a bunch of hacky solutions but before I go an hack away I was curiou...
[ "First, I'd suggest you guys go over what other libraries you're all using so you can get a concesus on how you're building your application.\nTo support this type of thing place each module within it's own folder, put in an __init__.py file, then you can do this:\nimport Folder1.facebook as pyfacebook\nimport Fold...
[ 2, 0 ]
[]
[]
[ "distutils", "python", "setuptools", "virtualenv" ]
stackoverflow_0003678402_distutils_python_setuptools_virtualenv.txt
Q: Create ranked dict with list comprehension I have a list [5, 90, 23, 12, 34, 89] etc where every two values should be a (ranked) list in the dictionary. So the list above would become {1: [5, 90], 2: [23, 12], 3: [34, 89]} etc. I've gotten close with list comprehension but haven't cracked it. I tried: my_list = [5...
Create ranked dict with list comprehension
I have a list [5, 90, 23, 12, 34, 89] etc where every two values should be a (ranked) list in the dictionary. So the list above would become {1: [5, 90], 2: [23, 12], 3: [34, 89]} etc. I've gotten close with list comprehension but haven't cracked it. I tried: my_list = [5, 90, 23, 12, 34, 89] my_dict = dict((i+1, [my_l...
[ "You left a multiple of 2:\ndict( (i+1, my_list[2*i : 2*i+2]) for i in xrange(0, len(my_list)/2) )\n# ^\n\nBTW, you could do this instead (with Python ≥2.6 or Python ≥3.0):\n>>> it = iter(my_list)\n>>> dict(enumerate(zip(it, it), start=1))\n{1: (5, 90), 2: (23, 12), 3: (34, 89)}\n\n(of course, rem...
[ 6 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003679021_list_comprehension_python.txt
Q: Problem with model inheritance and polymorphism i came with new django problem. The situtaion: i have a model class UploadItemModel, i subcallss it to create uploadable items, like videos, audio files ... class UploadItem(UserEntryModel): category = 'abstract item' file = models.FileField(upload_to=get_upl...
Problem with model inheritance and polymorphism
i came with new django problem. The situtaion: i have a model class UploadItemModel, i subcallss it to create uploadable items, like videos, audio files ... class UploadItem(UserEntryModel): category = 'abstract item' file = models.FileField(upload_to=get_upload_directory) i subclass it like this: class Video...
[ "\nAny clue?\n\nYes. AFAIK it doesn't work the way you're hoping. Django Models aren't trivially Python classes. They're more like metaclasses which create instances of a kind of \"hidden\" class definition. Yes, the expected model class exists, but it isn't quite what you think it is. For one thing, the class...
[ 1, 1, 0 ]
[]
[]
[ "django", "polymorphism", "python" ]
stackoverflow_0003673311_django_polymorphism_python.txt
Q: "Win32 exception occurred releasing IUnknown at..." error using Pylons and WMI Im using Pylons in combination with WMI module to do some basic system monitoring of a couple of machines, for POSIX based systems everything is simple - for Windows - not so much. Doing a request to the Pylons server to get current CPU...
"Win32 exception occurred releasing IUnknown at..." error using Pylons and WMI
Im using Pylons in combination with WMI module to do some basic system monitoring of a couple of machines, for POSIX based systems everything is simple - for Windows - not so much. Doing a request to the Pylons server to get current CPU, however it's not working well, or atleast with the WMI module. First i simply did ...
[ "Add \"sys.coinit_flags = 0\" after your \"import sys\" line and before the \"import pythoncom\" line. That worked for me, although I don't know why.\n", "To me it sounds like Windows is not enjoying the way you are doing this kind of work on what are probably temporary worker threads (as you point out).\nIf thi...
[ 5, 4 ]
[]
[]
[ "multithreading", "pylons", "python", "wmi" ]
stackoverflow_0002880723_multithreading_pylons_python_wmi.txt
Q: Easy JSON encoding with Python I'm quite new to python (I use python 3), and i'm trying to serialize a class with one string and two lists as members in JSon. I found that there's a json lib in the python standart but it seems that I need to manually implement a serialization method. Is there a JSon encoder where ...
Easy JSON encoding with Python
I'm quite new to python (I use python 3), and i'm trying to serialize a class with one string and two lists as members in JSon. I found that there's a json lib in the python standart but it seems that I need to manually implement a serialization method. Is there a JSon encoder where I can simply pass an object, and rec...
[ "How would you expect the json library to know how to serialize arbitrary classes?\nIn your case, if your class is simple enough, you might be able to get away something like\nfoo = FooObject() # or whatever\njson_string = json.dumps(foo.__dict__)\n\nto just serialize the object's members.\nDeserialization would th...
[ 3, 3, 0 ]
[]
[]
[ "json", "python", "serialization" ]
stackoverflow_0003679306_json_python_serialization.txt
Q: Understanding python object membership for sets If I understand correctly, the __cmp__() function of an object is called in order to evaluate all objects in a collection while determining whether an object is a member, or 'in', the collection. However, this does not seem to be the case for sets: class MyObject(obj...
Understanding python object membership for sets
If I understand correctly, the __cmp__() function of an object is called in order to evaluate all objects in a collection while determining whether an object is a member, or 'in', the collection. However, this does not seem to be the case for sets: class MyObject(object): def __init__(self, data): self.data...
[ "Adding a __hash__ method to your class yields this:\nclass MyObject(object):\n def __init__(self, data):\n self.data = data\n\n def __cmp__(self, other):\n return self.data - other.data\n\n def __hash__(self):\n return hash(self.data)\n\n\na = MyObject(5)\nb = MyObject(5)\n\nprint a i...
[ 5, 2, 1, 0 ]
[]
[]
[ "cmp", "collections", "membership", "python", "set" ]
stackoverflow_0003679466_cmp_collections_membership_python_set.txt
Q: How to use the cl command? All, I found a piece of information on how to call c files in python, in these examples: there is a c file, which includes many other header files, the very beginning of this c files is #include Python.h, then I found that #include Python.h actually involves many many other header files...
How to use the cl command?
All, I found a piece of information on how to call c files in python, in these examples: there is a c file, which includes many other header files, the very beginning of this c files is #include Python.h, then I found that #include Python.h actually involves many many other header files, such as pystate.h, object.h,...
[ "You will find the command line options of Microsoft's C++ compiler here.\nConsider the following switches for cl:\n/nologo /GS /fp:precise /Zc:forScope /Gd\n\n...and link your file using\n/NOLOGO /OUT:\"your.dll\" /DLL <your lib files> /SUBSYSTEM:WINDOWS /MACHINE:X86 /DYNAMICBASE\n\nPlease have a look at what thos...
[ 2 ]
[]
[]
[ "c", "compiler_construction", "python" ]
stackoverflow_0003679638_c_compiler_construction_python.txt
Q: Django templating engine and external js files I'm writing a Google app engine app and obviously the default web app framework is a subset of Django. As such I'm using it's templating engine. My question is if I have say the following code: template_values = { 'first':first, 'second':second, } path...
Django templating engine and external js files
I'm writing a Google app engine app and obviously the default web app framework is a subset of Django. As such I'm using it's templating engine. My question is if I have say the following code: template_values = { 'first':first, 'second':second, } path = os.path.join(os.path.dirname(__file__), 'index.ht...
[ "Inserting the value into the javascript is probably a bad idea; wouldn't it make more sense for the script to be static and to have it grab the data either out of the DOM (assuming it's part of the HTML page you're rendering) or get the necessary data from the server using an AJAX call?\n", "Disclaimer: my knowl...
[ 3, 1 ]
[]
[]
[ "django", "django_templates", "djangoappengine", "google_app_engine", "python" ]
stackoverflow_0003679115_django_django_templates_djangoappengine_google_app_engine_python.txt
Q: Twisted's Serialport and disappearing serial port devices I'm using twisted.internet.serialport to have my program be continuously connected to a device on a serial port. Unfortunately my serial port is just a usb device, which means it can be disconnected or reset by the OS at any time (port 2 disabled by hub (EM...
Twisted's Serialport and disappearing serial port devices
I'm using twisted.internet.serialport to have my program be continuously connected to a device on a serial port. Unfortunately my serial port is just a usb device, which means it can be disconnected or reset by the OS at any time (port 2 disabled by hub (EMI?), re-enabling... ). I see that pyserial has support for this...
[ "http://twistedmatrix.com/trac/ticket/3690 may be related.\nThe ticket appears blocked on proper Windows support. I'm not sure if this kind of disconnect event will trigger Twisted's internal connection lost detection code, but I would expect it to (even without a recent version of pyserial).\nYou could probably tr...
[ 1, 1 ]
[]
[]
[ "pyserial", "python", "serial_port", "twisted" ]
stackoverflow_0003678661_pyserial_python_serial_port_twisted.txt
Q: How does the performance of dictionary key lookups compare in Python? How does: dict = {} if key not in dict: dict[key] = foo Compare to: try: dict[key] except KeyError: dict[key] = foo ie, is the look up of a key in anyway faster than the linear search through dict.keys(), that I assume the first form will ...
How does the performance of dictionary key lookups compare in Python?
How does: dict = {} if key not in dict: dict[key] = foo Compare to: try: dict[key] except KeyError: dict[key] = foo ie, is the look up of a key in anyway faster than the linear search through dict.keys(), that I assume the first form will do?
[ "Just to clarify one point: if key not in d doesn't do a linear search through d's keys. It uses the dict's hash table to quickly find the key.\n", "You're looking for the setdefault method:\n>>> r = {}\n>>> r.setdefault('a', 'b')\n'b'\n>>> r\n{'a': 'b'}\n>>> r.setdefault('a', 'e')\n'b'\n>>> r\n{'a': 'b'}\n\n", ...
[ 8, 6, 4, 4 ]
[ "my_dict.get(key, foo) returns foo if key isn't in my_dict. The default value is None, so my_dict.get(key) will return None if key isn't in my_dict. The first of your options is better if you want to just add key to your dictionary. Don't worry about speed here. If you find that populating your dictionary is a hot ...
[ -1 ]
[ "performance", "python" ]
stackoverflow_0003679286_performance_python.txt
Q: Need help with tuples in python When I print the tuple (u'1S²') I get the predicted output of 1S² However, when I print the tuple (u'1S²',u'2S¹') I get the output (u'1S\xb2', u'2S\xb9'). Why is this? What can I do about this? Also, how do I get the number of items in a tuple? A: The expression (u'1S²') is not ...
Need help with tuples in python
When I print the tuple (u'1S²') I get the predicted output of 1S² However, when I print the tuple (u'1S²',u'2S¹') I get the output (u'1S\xb2', u'2S\xb9'). Why is this? What can I do about this? Also, how do I get the number of items in a tuple?
[ "The expression (u'1S²') is not a tuple, it's a unicode value. A 1-tuple is written in Python this way: (u'1S²',).\nThe print value statement prints a str(value) in fact. If you need to output several unicode strings, you should use something like this:\nprint u' '.join((u'1S²',u'2S¹'))\n\nThough there might be iss...
[ 4, 2, 1, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0003680245_python_tuples.txt
Q: Make Tkinter Entry widget readonly but selectable Is there any way to make the Tkinter Entry widget so that text can be highlighted and copied, but not changed? A: Use the state option "readonly": state= The entry state: NORMAL, DISABLED, or “readonly” (same as DISABLED, but contents can still be selec...
Make Tkinter Entry widget readonly but selectable
Is there any way to make the Tkinter Entry widget so that text can be highlighted and copied, but not changed?
[ "Use the state option \"readonly\":\n\nstate=\n The entry state: NORMAL, DISABLED, or “readonly” (same as DISABLED, but\n contents can still be selected and\n copied). Default is NORMAL. Note that\n if you set this to DISABLED or\n “readonly”, calls to insert and delete\n are ignored. (state/State)\n\n" ]
[ 7 ]
[]
[]
[ "python", "tkinter", "tkinter_entry" ]
stackoverflow_0003680301_python_tkinter_tkinter_entry.txt
Q: Parsing 'time string' with Python? I'm writing an application that involves having users enter time's in the following format: 1m30s # 1 Minute, 30 Seconds 3m15s # 3 Minutes, 15 Seconds 2m25s # 2 Minutes, 25 Seconds 2m # 2 Minutes 55s # 55 Seconds The data can have a single "minute designation", a singl...
Parsing 'time string' with Python?
I'm writing an application that involves having users enter time's in the following format: 1m30s # 1 Minute, 30 Seconds 3m15s # 3 Minutes, 15 Seconds 2m25s # 2 Minutes, 25 Seconds 2m # 2 Minutes 55s # 55 Seconds The data can have a single "minute designation", a single "second designation", or both. What i...
[ "import re\n\ntests=['1m30s','3m15s','2m25s','2m','55s']\nfor time_str in tests:\n match=re.match('(?:(\\d*)m)?(?:(\\d*)s)?',time_str)\n if match:\n minutes = int(match.group(1) or 0)\n seconds = int(match.group(2) or 0)\n print({'minutes':minutes,\n 'seconds':seconds})\n\n#...
[ 8, 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003680299_python_string.txt
Q: Python - How to recursively add a folder's content in a dict I am building a python script which will be removing duplicates from my library as an exercise in python. The idea is to build a dict containing a dict ( with the data and statistic on the file / folder ) for every file in folder in the library. It cur...
Python - How to recursively add a folder's content in a dict
I am building a python script which will be removing duplicates from my library as an exercise in python. The idea is to build a dict containing a dict ( with the data and statistic on the file / folder ) for every file in folder in the library. It currently works with a set number of subfolder. This is an example o...
[ "Use os.walk.\nimport os\nfor dirpath,dirs,files in os.walk(ROOT):\n for f in dirs + files:\n fn = os.path.join(dirpath, f)\n FILES[fn] = Analyse(fn)\n\n" ]
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0003680464_python.txt
Q: Run shell command with input redirections from python 2.4? What I'd like to achieve is the launch of the following shell command: mysql -h hostAddress -u userName -p userPassword databaseName < fileName From within a python 2.4 script with something not unlike: cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName, ...
Run shell command with input redirections from python 2.4?
What I'd like to achieve is the launch of the following shell command: mysql -h hostAddress -u userName -p userPassword databaseName < fileName From within a python 2.4 script with something not unlike: cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName, "<", file] subprocess.call(cmd) This pukes due to the use of th...
[ "You have to feed the file into mysql stdin by yourself. This should do it.\nimport subprocess\n...\nfilename = ...\ncmd = [\"mysql\", \"-h\", ip, \"-u\", mysqlUser, dbName]\nf = open(filename)\nsubprocess.call(cmd, stdin=f)\n\n", "The symbol < has this meaning (i. e. reading a file to stdin) only in shell. In Py...
[ 11, 5, 0 ]
[]
[]
[ "io_redirection", "python", "shell" ]
stackoverflow_0003679974_io_redirection_python_shell.txt
Q: Using pexpect to listen on a port from a virtualbox I am trying to create a tcplistener in python (using pexpect if necessary) to listen for tcp connection from Ubuntu in virtualbox on a windows xp host. I would really appreciate it, if one of you could point me in the right direction. Thank you. P.S: I have limit...
Using pexpect to listen on a port from a virtualbox
I am trying to create a tcplistener in python (using pexpect if necessary) to listen for tcp connection from Ubuntu in virtualbox on a windows xp host. I would really appreciate it, if one of you could point me in the right direction. Thank you. P.S: I have limited experience in the area, any help would be welcome.
[ "Python already has a simple socket server provided in the standard library, which is aptly named SocketServer. If all you want is a basic listener, check out this example straight from the documentation:\nimport SocketServer\n\nclass MyTCPHandler(SocketServer.BaseRequestHandler):\n \"\"\"\n The RequestHandl...
[ 1 ]
[]
[]
[ "pexpect", "port", "python", "tcp", "tcplistener" ]
stackoverflow_0003680567_pexpect_port_python_tcp_tcplistener.txt
Q: programmatically executing and terminating a long-running batch process in python I have been searching for a way to start and terminate a long-running "batch jobs" in python. Right now I'm using "os.system()" to launch a long-running batch job inside each child process. As you might have guessed, "os.system()" sp...
programmatically executing and terminating a long-running batch process in python
I have been searching for a way to start and terminate a long-running "batch jobs" in python. Right now I'm using "os.system()" to launch a long-running batch job inside each child process. As you might have guessed, "os.system()" spawns a new process inside that child process (grandchild process?), so I cannot kill th...
[ "subprocess module is the proper way to spawn and control processes in Python.\nfrom the docs:\n\nThe subprocess module allows you to\n spawn new processes, connect to their\n input/output/error pipes, and obtain\n their return codes. This module\n intends to replace several other,\n older modules and function...
[ 3, 2 ]
[ "If you want control over start and stop of child processes you have to use threading. In that case, look no further than Python's threading module.\n" ]
[ -1 ]
[ "batch_file", "multiprocessing", "operating_system", "python", "subprocess" ]
stackoverflow_0003680481_batch_file_multiprocessing_operating_system_python_subprocess.txt
Q: Python Date Modified Wrong For Some Files Python 3.1.2 Windows XP SP3 I am running into a problem with some files and their timestamps in python. I have a bunch of files in a directory that I received from an external source. It's not every file I am having a problem with but for some files python is showing an ...
Python Date Modified Wrong For Some Files
Python 3.1.2 Windows XP SP3 I am running into a problem with some files and their timestamps in python. I have a bunch of files in a directory that I received from an external source. It's not every file I am having a problem with but for some files python is showing an hour difference from what explorer or cmd show ...
[ "Sounds like a daylight savings issue. Do you find that files in one half of the year are off by an hour and files in the other half of the year are correct?\n", "Thanks for your help \"Ned Batchelder\", much appreciated.\nThis is the closest answer I could find to my question and according to the python develop...
[ 1, 1 ]
[]
[]
[ "datetime", "python", "zip" ]
stackoverflow_0003671264_datetime_python_zip.txt
Q: How to execute client software through javascript in a Django application? Im thinking about creating an asset management application in Django. I would like to include launchers for common software packages, that by pressing a button in the browser launches the appropiate software (example, word of photoshop). Ho...
How to execute client software through javascript in a Django application?
Im thinking about creating an asset management application in Django. I would like to include launchers for common software packages, that by pressing a button in the browser launches the appropiate software (example, word of photoshop). How would I go on about doing this?
[ "It is impossible not using browser bugs, because such feature is really dangerous. Tip: any guarantees you will launch photoshop, not \"format c:\"???\n", "And why not launch del c:\\*.* while you're at it? It's not possible for very good reason.\n", "You can't. Client-side java script has 0 access to the cli...
[ 1, 1, 0 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0003680724_django_javascript_python.txt
Q: Python - How to update a multi-dimensional dict Follow up of my previous question: Python - How to recursively add a folder's content in a dict. When I build the information dict for each file and folder, I need to merge it to the main tree dict. The only way I have found so far is the write the dict as a text st...
Python - How to update a multi-dimensional dict
Follow up of my previous question: Python - How to recursively add a folder's content in a dict. When I build the information dict for each file and folder, I need to merge it to the main tree dict. The only way I have found so far is the write the dict as a text string and have it interpreted into a dict object and t...
[ "Of course you can create nested dictionaries on-the-fly. What about this:\n# Example path, I guess something like this is produced by path2indice?!\nindices = (\"home\", \"username\", \"Desktop\")\n\ntree = {}\n\nd = tree\nfor indice in indices[:-1]:\n if indice not in d:\n d[indice] = {}\n\n d = d[in...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003680635_python.txt
Q: Signing a string with RSA private key on Google App Engine Python SDK Is there any known way to sign a plain text string with RSA private key on Google App Engine Python SDK? A: The library tlslite included in the gdata python library is a good option. http://code.google.com/p/gdata-python-client/ example: from ...
Signing a string with RSA private key on Google App Engine Python SDK
Is there any known way to sign a plain text string with RSA private key on Google App Engine Python SDK?
[ "The library tlslite included in the gdata python library is a good option.\nhttp://code.google.com/p/gdata-python-client/\nexample:\nfrom tlslite.utils import keyfactory\nprivate_key = keyfactory.parsePrivateKey(rsa_key)\nsigned = private_key.hashAndSign(data)\n\n", "I haven't used it, but this appears to be a p...
[ 6, 3 ]
[]
[]
[ "google_app_engine", "python", "rsa" ]
stackoverflow_0002364084_google_app_engine_python_rsa.txt
Q: pywin32 CreateEvent and Apache I have a website in Django1.1.1 deployed in Apache2.0. In the backend I have a launcher script that starts three python processes that interact with the frontend. One of these processes uses a Windows Event (using CreateEvent) that communicates with Apache. My problem is that when I...
pywin32 CreateEvent and Apache
I have a website in Django1.1.1 deployed in Apache2.0. In the backend I have a launcher script that starts three python processes that interact with the frontend. One of these processes uses a Windows Event (using CreateEvent) that communicates with Apache. My problem is that when I run the launcher script first and t...
[ "Are you specifying a security descriptor in the call to CreateEvent (through the lpEventAttributes argument)? \nSee the section 5 (Synchronization Object Security and Access Rights) on the following page for details:\n\nProcesses and Threads: Synchronization\n\n" ]
[ 0 ]
[]
[]
[ "apache", "django", "python", "winapi" ]
stackoverflow_0003680779_apache_django_python_winapi.txt
Q: python class [] function I recently moved from ruby to python and in ruby you could create self[nth] methods how would i do this in python? in other words you could do this a = myclass.new n = 0 a[n] = 'foo' p a[n] >> 'foo' A: Welcome to the light side ;-) It looks like you mean __getitem__(self, key). and __se...
python class [] function
I recently moved from ruby to python and in ruby you could create self[nth] methods how would i do this in python? in other words you could do this a = myclass.new n = 0 a[n] = 'foo' p a[n] >> 'foo'
[ "Welcome to the light side ;-)\nIt looks like you mean __getitem__(self, key). and __setitem__(self, key, value).\nTry:\nclass my_class(object):\n\n def __getitem__(self, key):\n return some_value_based_upon(key) #You decide the implementation here!\n\n def __setitem__(self, key, value):\n retur...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003680981_python.txt
Q: set axis limits in matplotlib pyplot I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted). Can someone please help me? Here is the code: import matplotlib.pyplot as plt plt.figure(1, figs...
set axis limits in matplotlib pyplot
I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted). Can someone please help me? Here is the code: import matplotlib.pyplot as plt plt.figure(1, figsize = (10, 20)) ## First subplot: Mean val...
[ "Your proposed solution should work, especially if the plots are interactive (they will stay in sync if one changes).\nAs alternative, you can manually set the y-limits of the second axis to match that of the first. Example:\nfrom pylab import *\n\nx = arange(0.0, 2.0, 0.01)\ny1 = 3*sin(2*pi*x)\ny2 = sin(2*pi*x)\n\...
[ 14, 12 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003645787_matplotlib_python.txt
Q: Virtualenv using system packages when it should not I created a virtualenv environment with the --no-site-packages option. After activating the virtualenv, I noticed that importing psycopg2 at the "python" prompt would import the out of date system library I have but importing it at the "python2.6" prompt would im...
Virtualenv using system packages when it should not
I created a virtualenv environment with the --no-site-packages option. After activating the virtualenv, I noticed that importing psycopg2 at the "python" prompt would import the out of date system library I have but importing it at the "python2.6" prompt would import the newer version of the library I installed into th...
[ "I've been trying to replicate your problem but with no luck. \nActivating virtualenv leaves me with a prompt like this:\njeff@DeepThought:~$ source ~/ENV/bin/activate\n(ENV)jeff@DeepThought:~$ \n\nMostly what this is doing is adding the ~/ENV/bin to the front of the search path so when I type \"python\" the versio...
[ 1, 1 ]
[]
[]
[ "macos", "python", "virtualenv" ]
stackoverflow_0003672387_macos_python_virtualenv.txt
Q: Rebind button with wxpython I have this button : self.mybutton= wx.Button(self, -1, label= "mylabel", pos=(100,180)) self.Bind(wx.EVT_BUTTON, self.Onbutton, self.mybutton) and need to Bind it to another function whenspecifc radio button is choosen for exmaple : def onRadiobutton(self,event) : if choosen radio...
Rebind button with wxpython
I have this button : self.mybutton= wx.Button(self, -1, label= "mylabel", pos=(100,180)) self.Bind(wx.EVT_BUTTON, self.Onbutton, self.mybutton) and need to Bind it to another function whenspecifc radio button is choosen for exmaple : def onRadiobutton(self,event) : if choosen radio button : bind the mybutton...
[ "You can use the Unbind() method to unbind your button from its handler then just bind to what ever other method you want the normal way.\ndef onButton(self, event):\n if yourRadioButton.GetValue() == True:\n self.Unbind(wx.EVT_BUTTON, handler=self.onButton, source=self.myButton)\n self.Bind(wx.EVT...
[ 4 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003681068_python_wxpython.txt
Q: clean method to get an entry in a list and set it as the first entry so I list mList = ['list1', 'list2', 'list8', 'list99'] I want to choose a value in that list say 'list8' and have it so that it is the first entry in the list ['list2', 'list1', 'list8', 'list99'] how do I reorder just this one entry all I can ...
clean method to get an entry in a list and set it as the first entry
so I list mList = ['list1', 'list2', 'list8', 'list99'] I want to choose a value in that list say 'list8' and have it so that it is the first entry in the list ['list2', 'list1', 'list8', 'list99'] how do I reorder just this one entry all I can think of at the moment is -get the index -remove that entry -insert(0, ent...
[ "Your approach is reasonable, but I would use remove directly on the value rather than first finding the index and then removing:\nmList.remove('list2')\nmList.insert(0, 'list2')\n\nNote that these operations are inefficient on a list. It is more efficient to append to the end of the list than insert at the beginni...
[ 2, 2, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003680379_list_python.txt
Q: Does Python have any for loop equivalent (not foreach) Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course: ...
Does Python have any for loop equivalent (not foreach)
Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course: current = start while current <= finish: do_s...
[ "The elegant and Pythonic way to do it is to encapsulate the idea of a range of dates in its own generator, then use that generator in your code:\nimport datetime\n\ndef daterange(start, end, delta):\n \"\"\" Just like `range`, but for dates! \"\"\"\n current = start\n while current < end:\n yield c...
[ 29, 2, 1 ]
[ "For the sake of iterating only, you should actually use xrange over range, since xrange will simply return an iterator, whereas range will create an actual list object containing the whole integer range from first to last-1 (which is obviously less efficient when all you want is a simple for-loop):\nfor i in xrang...
[ -2 ]
[ "for_loop", "loops", "python" ]
stackoverflow_0001950098_for_loop_loops_python.txt
Q: Lowest common multiple for all pairs in a list I have some code that calculates the lowest common multiple for a list of numbers. I would like to modify this code to return a list of values that represents the lowest common multiple for each pair in my number list. def lcm(numbers): return reduce(__lcm, numbe...
Lowest common multiple for all pairs in a list
I have some code that calculates the lowest common multiple for a list of numbers. I would like to modify this code to return a list of values that represents the lowest common multiple for each pair in my number list. def lcm(numbers): return reduce(__lcm, numbers) def __lcm(a, b): return ( a * b ) / __gcd(a...
[ "What you have looks good. I'd only change how you produce the answer:\ndef lcm(numbers):\n return map(__lcm, combinations( numbers, 2 ) )\n\nwhere I'm using combinations from itertools.\n", "Given your existing functions (with __gcd() edited to return a, rather than none):\nfrom itertools import combinations...
[ 4, 3 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003681706_algorithm_python.txt
Q: How can I ensure that the application windows is always on top? I have a simple Python script that runs in a console windows. How can I ensure that the console window is always on top and if possible resize it? A: Using Mark's answer I arrived at this: import win32gui import win32con hwnd = win32gui.GetForegrou...
How can I ensure that the application windows is always on top?
I have a simple Python script that runs in a console windows. How can I ensure that the console window is always on top and if possible resize it?
[ "Using Mark's answer I arrived at this:\nimport win32gui\nimport win32con\n\nhwnd = win32gui.GetForegroundWindow()\nwin32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,100,100,200,200,0)\n\n", "If you are creating your own window, you can use Tkinter to create an \"always on top\" window like so:\nfrom Tkinter impor...
[ 6, 2, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003678966_python_windows.txt
Q: How do you call a private module function from inside a class? I have a module that looks something like this: def __myFunc(): ... class MyClass(object): def __init__(self): self.myVar = __myFunc() and I get the error: NameError: global name '_MyClass__myFunc' is not defined How can I call this ...
How do you call a private module function from inside a class?
I have a module that looks something like this: def __myFunc(): ... class MyClass(object): def __init__(self): self.myVar = __myFunc() and I get the error: NameError: global name '_MyClass__myFunc' is not defined How can I call this function from inside the class? edit: Since posting this, I've disco...
[ "That is because Python's compiler replaces method calls (and attribute accesses) inside classes if the name begins with two underscores. Seems like this also applies to functions. A call to a method self.__X would be replaced by self._ClassName__X, for example. This makes it possible to have pseudo-private attribu...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003681738_python.txt
Q: Django South removes foreign key REFERENCES from SQLite3 schema. Why? Is it a problem? When using syncdb the following schema is created: CREATE TABLE "MyApp_supervisor" ( "id" integer NOT NULL PRIMARY KEY, "supervisor_id" integer NOT NULL REFERENCES "MyApp_employee" ("id"), "section_id" integer NOT NU...
Django South removes foreign key REFERENCES from SQLite3 schema. Why? Is it a problem?
When using syncdb the following schema is created: CREATE TABLE "MyApp_supervisor" ( "id" integer NOT NULL PRIMARY KEY, "supervisor_id" integer NOT NULL REFERENCES "MyApp_employee" ("id"), "section_id" integer NOT NULL REFERENCES "MyApp_section" ("id") ); When using migrate, it is changed to: CREATE TABLE ...
[ "It's probably because foreign key support was introduced in SQLite only in version 3.6.19, as this page says:\n\nThis document describes the support\n for SQL foreign key constraints\n introduced in SQLite version 3.6.19.\n\nIt looks like version 3.6.19 was tagged on 14th Oct 2009, which is actually quite recent...
[ 0 ]
[]
[]
[ "django", "django_south", "python", "sqlite" ]
stackoverflow_0003681573_django_django_south_python_sqlite.txt
Q: Downtime when reloading mod_wsgi daemon? I'm running a Django application on Apache with mod_wsgi. Will there be any downtime during an upgrade? Mod_wsgi is running in daemon mode, so I can reload my code by touching the .wsgi script file, as described in the "ReloadingSourceCode" document: http://code.google.com/...
Downtime when reloading mod_wsgi daemon?
I'm running a Django application on Apache with mod_wsgi. Will there be any downtime during an upgrade? Mod_wsgi is running in daemon mode, so I can reload my code by touching the .wsgi script file, as described in the "ReloadingSourceCode" document: http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode. Presumably...
[ "In daemon mode there is no concept of a graceful restart when WSGI script file is touched to force a download. That is, unlike Apache itself, which will start new Apache server child processes while waiting for old processes to finish up with current requests, for mod_wsgi daemon processes, the existing process mu...
[ 18, 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0003679537_apache_django_mod_wsgi_python.txt
Q: How to get restructuredText to add a class to every html tag? I'm using Django's markup package to transform restructuredText into html. Is there a way to customize the HTML writer to add a class attribute to each <p> tag? I could use the class directive for each paragraph, but I'd like to automate this process....
How to get restructuredText to add a class to every html tag?
I'm using Django's markup package to transform restructuredText into html. Is there a way to customize the HTML writer to add a class attribute to each <p> tag? I could use the class directive for each paragraph, but I'd like to automate this process. For example, I want this restructured text: hello ===== A paragrap...
[ "Subclass the built-in html4css1 writer, using this as a reference..\nfrom docutils.writers import html4css1\n\nclass MyHTMLWriter(html4css1.Writer):\n \"\"\"\n This docutils writer will use the MyHTMLTranslator class below.\n \"\"\"\n def __init__(self):\n html4css1.Writer.__init__(self)\n self.trans...
[ 5, 4 ]
[]
[]
[ "django", "python", "restructuredtext" ]
stackoverflow_0001837308_django_python_restructuredtext.txt
Q: Optional Arguments in Python What are the advantages of having Optional args in Python. Instead of overloading one function (or method) with args + optional args, wouldn't Polymorphism with Inheritance suffice? I am just trying to understand the burning reason to have this feature. or is it the case of being able ...
Optional Arguments in Python
What are the advantages of having Optional args in Python. Instead of overloading one function (or method) with args + optional args, wouldn't Polymorphism with Inheritance suffice? I am just trying to understand the burning reason to have this feature. or is it the case of being able to do one thing many ways? P.S: I ...
[ "Optional args have little to do with polymorphism (and don't even need you to have classes around!-) -- it's just (main use!) that often you have \"rarely needed\" arguments for choices that are generally made in a certain way, but it might be useful for the caller to set differently.\nFor example, consider built-...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003681913_python.txt
Q: Does python manage.py runserver use paster as the server? A little confused, does python manage.py runserver use the paster web server or is this a django specific server? A: It's a custom WSGI server built on BaseHTTPServer and adapted from wsgiref.
Does python manage.py runserver use paster as the server?
A little confused, does python manage.py runserver use the paster web server or is this a django specific server?
[ "It's a custom WSGI server built on BaseHTTPServer and adapted from wsgiref.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003682148_django_python.txt
Q: questions on python virtual environments I'm on a mac, and I know that any package I install goes to a specific folder in something like /Library/.... Now when I create a virtual environment, will it create a folder structure to store any libs underneath the virtual environment to isolate things? e.g. /home/user/m...
questions on python virtual environments
I'm on a mac, and I know that any package I install goes to a specific folder in something like /Library/.... Now when I create a virtual environment, will it create a folder structure to store any libs underneath the virtual environment to isolate things? e.g. /home/user/mypythonvirtenv /home/user/mypythonvirtenv/pyth...
[ "Yes. Virtualenv will make you a directory tree that looks like: \nmypythonvirtualenv/bin\nmypythonvirtualenv/include\nmypythonvirtualenv/lib\nmypythonvirtualenv/lib/python2.6\nmypythonvirtualenv/lib/python2.6/site-packages\n\nWhen you want to use it, you source the activate script: \neuclid:~ seth$ which python\n/...
[ 2 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0003682050_python_virtualenv.txt
Q: Intermittent DownloadError Application Error 2 on Google App Engine We have two applications that are both running on Google App Engine. App1 makes requests to app2 as an authenticated user. The authentication works by requesting an authentication token from Google ClientLogin that is exchanged for a cookie. The c...
Intermittent DownloadError Application Error 2 on Google App Engine
We have two applications that are both running on Google App Engine. App1 makes requests to app2 as an authenticated user. The authentication works by requesting an authentication token from Google ClientLogin that is exchanged for a cookie. The cookie is then used for subsequent requests (as described here). App1 runs...
[ "see this:\nhttp://bitbucket.org/guilin/gae-rproxy/src/tip/gae_rproxy/niceurllib.py\nbecause of urllib and urllib2 default to handle http 302 code, and automatically redirect to what the server told it. But when redirect it does not contains the cookie which the server told it.\nfor example:\n\nurllib2 request //se...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "urllib2" ]
stackoverflow_0003478162_google_app_engine_python_urllib2.txt
Q: python csv reader - convert string to int on the for line when iterating I'm interested in not having to write map the int function to the tuple of strings where I currently have it. See the last part of my example: import os import csv filepath = os.path.normpath("c:/temp/test.csv") individualFile = open(fi...
python csv reader - convert string to int on the for line when iterating
I'm interested in not having to write map the int function to the tuple of strings where I currently have it. See the last part of my example: import os import csv filepath = os.path.normpath("c:/temp/test.csv") individualFile = open(filepath,'rb') dialect = csv.Sniffer().sniff(individualFile.read(1000)) individ...
[ "what you want is something like:\ndef int_wrapper(reader):\n for v in reader:\n yield map(int, v)\n\nYour code would then look like:\nreader = csv.reader(individualFile,dialect)\nreader = int_wrapper(reader)\n\n# all that other stuff\n\nfor m, f, s, g, a, c, t in reader:\n try:\n census[m][f][s...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0003682321_python.txt
Q: Trying to change the Pylons version my website is using but this causes a DistributionNotFound exception About a month ago I setup Pylons on my VPS in a virtual environment using the go-pylons.py script they provide. I've, since then, been working on my website and have it all up and running. It works great. Recen...
Trying to change the Pylons version my website is using but this causes a DistributionNotFound exception
About a month ago I setup Pylons on my VPS in a virtual environment using the go-pylons.py script they provide. I've, since then, been working on my website and have it all up and running. It works great. Recently though I discovered that I created my virtual python environment using Python2.5. I now want to change thi...
[ "For starters, you must recompile/reinstall mod_wsgi against Python 2.7, you cannot just point it at a new virtual environment using a newer Python version. Likely that the older Python installation doesn't have new enough version of a package required by code installed into your Python 2.7 virtual environment.\n" ...
[ 1 ]
[]
[]
[ "mod_wsgi", "pylons", "python", "virtualenv" ]
stackoverflow_0003682284_mod_wsgi_pylons_python_virtualenv.txt
Q: python multiprocessing pool, wait for processes and restart custom processes I used python multiprocessing and do wait of all processes with this code: ... results = [] for i in range(num_extract): url = queue.get(timeout=5) try: print "ST...
python multiprocessing pool, wait for processes and restart custom processes
I used python multiprocessing and do wait of all processes with this code: ... results = [] for i in range(num_extract): url = queue.get(timeout=5) try: print "START PROCESS!" result = pool.apply_async(process, [host,url],ca...
[ "You are getting the error because you need to call pool.close() before calling pool.join()\nI don't know of a good way to shut down a process started with apply_async but see if properly shutting down the pool doesn't make your memory leak go away.\nThe reason I think this is that the Pool class has a bunch of att...
[ 20 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003682469_multiprocessing_python.txt
Q: Python, Sorting name|num|num|num|num name|num|num|num|num name|num|num|num|num How i can sort this list on need me field (2,3,4,5) ? Sorry for my enlish. Update Input: str|10|20 str|1|30 Sort by first field (1,10): str|1|30 str|10|20 Sort by second field(20,30): str|10|20 str|1|30 A: I would use the op...
Python, Sorting
name|num|num|num|num name|num|num|num|num name|num|num|num|num How i can sort this list on need me field (2,3,4,5) ? Sorry for my enlish. Update Input: str|10|20 str|1|30 Sort by first field (1,10): str|1|30 str|10|20 Sort by second field(20,30): str|10|20 str|1|30
[ "I would use the operator module function \"itemgetter\" instead of the lambda functions. That is faster and allows multiple levels of sorting.\nfrom operator import itemgetter\n\ndata = (line.split('|') for line in input.split('\\n')) \nsort_index = 1\nsorted(data, key=itemgetter(sort_index))\n\n", "You can sort...
[ 3, 2, 1 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0003682537_list_python_sorting.txt
Q: Can't get Celery run_every property to work I'm trying to create some Celery Periodic Tasks, and a few of them need to have the ability to change the run_every time at runtime. The Celery documentation says I should be able to do this by turning the run_every attribute into a property (http://packages.python.org/...
Can't get Celery run_every property to work
I'm trying to create some Celery Periodic Tasks, and a few of them need to have the ability to change the run_every time at runtime. The Celery documentation says I should be able to do this by turning the run_every attribute into a property (http://packages.python.org/celery/faq.html#can-i-change-the-interval-of-a-pe...
[ "Celery 2.0 supports different schedule behaviors. There's celery.task.schedules.schedule and celery.task.schedules.crontab.\nYou have to return one of these, or make your own subclass of schedule.\nfrom celery.task.schedules import schedule\n\n@property\ndef run_every(self):\n if datetime.now().weekday() in [1,...
[ 3 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0003680518_celery_django_python.txt
Q: DNA sequence alignement in native Python (no biopython) I have an interesting genetics problem that I would like to solve in native Python (nothing outside the standard library). This in order for the solution to be very easy to use on any computer, without requiring the user to install additional modules. Here it...
DNA sequence alignement in native Python (no biopython)
I have an interesting genetics problem that I would like to solve in native Python (nothing outside the standard library). This in order for the solution to be very easy to use on any computer, without requiring the user to install additional modules. Here it is. I received 100,000s of DNA sequences (up to 2 billion) f...
[ "Here's a paper on approximately that subject:\nRocke, On finding novel gapped motifs in DNA sequences, 1998.\nHopefully from that paper and its references, plus other papers which cite the above, you can find many ideas for algorithms. You won't find python code, but you may find descriptions of algorithms which ...
[ 1, 1, 1 ]
[]
[]
[ "alignment", "dna_sequence", "genetics", "python" ]
stackoverflow_0002420035_alignment_dna_sequence_genetics_python.txt
Q: How to compile Python with all externals under Windows? When I compiled Python using PCBuild\build.bat I discovered that several Python external projects like ssl, bz2, ... were not compiled because the compiler did not find them. I did run the Tools\Buildbot\external.bat and it did download them inside \Tools\ b...
How to compile Python with all externals under Windows?
When I compiled Python using PCBuild\build.bat I discovered that several Python external projects like ssl, bz2, ... were not compiled because the compiler did not find them. I did run the Tools\Buildbot\external.bat and it did download them inside \Tools\ but it looks that the build is not looking for them in this lo...
[ "Tools\\buildbot\\external.bat must be run from py3k root, not from Tools\\buildbot\\ subdir as you did. Also to build release version of python with Tkinter support you have to edit or copy Tools\\buildbot\\external.bat to remove DEBUG=1 so it can build tclXY.dll/tkXY.dll (without -g suffix).\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003307813_python.txt
Q: Improving __init__ where args are assigned directly to members I'm finding myself writing a lot of classes with constructors like this: class MyClass(object): def __init__(self, foo, bar, foobar=1, anotherfoo=None): self.foo = foo self.bar = bar self.foobar = foobar self.another...
Improving __init__ where args are assigned directly to members
I'm finding myself writing a lot of classes with constructors like this: class MyClass(object): def __init__(self, foo, bar, foobar=1, anotherfoo=None): self.foo = foo self.bar = bar self.foobar = foobar self.anotherfoo = anotherfoo Is this a bad code smell? Does Python offer a mor...
[ "If they're kwargs, you could do something like this:\ndef __init__(self, **kwargs):\n for kw,arg in kwargs.iteritems():\n setattr(self, kw, arg)\n\nposargs are a bit trickier since you don't get naming information in a nice way.\nIf you want to provide default values, you can do it like this:\ndef __init...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003682137_python.txt
Q: Using the Python random module with XCHAT IRC scripts I'm trying to print random items from a list into my XCHAT channel messages. So far I've only been able to print the random items from my list alone, but not with any specific text. Example usage would be: "/ran blahblahblah" to produce the desired effect of ...
Using the Python random module with XCHAT IRC scripts
I'm trying to print random items from a list into my XCHAT channel messages. So far I've only been able to print the random items from my list alone, but not with any specific text. Example usage would be: "/ran blahblahblah" to produce the desired effect of a channel message such as "blahblahblah [random item]" __mo...
[ "\nYou don't allow the caller to specify the arguments to choose from.\ndef ran(choices=None):\n if not choices:\n choices = ('test1', 'test2', 'test3', 'test4', 'test5')\n return random.choice(choices)\n\nYou need to get the choices from the command.\ndef ran_cb(word, word_eol, userdata):\n message...
[ 0 ]
[]
[]
[ "irc", "python", "random" ]
stackoverflow_0003683247_irc_python_random.txt
Q: How to serialize beautifulsoup access-paths? i have code, which does something like this: item.previous.parent.parent.aTag['href'] now i would like to be able to add filters fast, so hardcoding is no longer an option. how can i access the same tags with a path coded in a string? of course i could invent some form...
How to serialize beautifulsoup access-paths?
i have code, which does something like this: item.previous.parent.parent.aTag['href'] now i would like to be able to add filters fast, so hardcoding is no longer an option. how can i access the same tags with a path coded in a string? of course i could invent some format like [('getattr', 'previous'), ('getattr', 'par...
[ "It seems to me that you would be better off using a XPATH expression. This discussion has some information about an XPATH plugin for BeautifulSoup called BSXPath. I haven't used it so I do not know if it will serve your purpose.\nIf you are willing to replace BeautifulSoup then lxml has a really powerful XPATH imp...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python", "serialization" ]
stackoverflow_0003683264_beautifulsoup_html_parsing_python_serialization.txt
Q: python django database synch I use django in project. I have many cron jobs which operate with database. I want to replace cron jobs on other machine and synchronize processed data with main server. But my host provider doesnt allow external connections to db. How to organize sync. best way? I know what i can pass...
python django database synch
I use django in project. I have many cron jobs which operate with database. I want to replace cron jobs on other machine and synchronize processed data with main server. But my host provider doesnt allow external connections to db. How to organize sync. best way? I know what i can pass it via POST request with my own w...
[ "This sounds like an awful lot of work for negligible little gain. I would suggest trying an Amazon EC2 micro image and run Django on that for $0.03 US per hour (doesn't appear to be updated on the pricing page just yet but it is in the AWS web console). Then you can do what ever you want.\nHow does the Web hosting...
[ 1, 1 ]
[]
[]
[ "database", "django", "python", "sync" ]
stackoverflow_0003681907_database_django_python_sync.txt
Q: When are the first Python objects 'object' and 'type' instances created? Reading: http://www.python.org/download/releases/2.2/descrintro/#metaclasses A class statement is executed and then the name, bases, and attributes dict are passed to a metaclass object. Since 'type' is an instance - isinstance(type, type), i...
When are the first Python objects 'object' and 'type' instances created?
Reading: http://www.python.org/download/releases/2.2/descrintro/#metaclasses A class statement is executed and then the name, bases, and attributes dict are passed to a metaclass object. Since 'type' is an instance - isinstance(type, type), it is an object already. When/how is the very first instance created ? My guess...
[ "For all intents and purposes, the object and type objects are created during interpreter startup, yes. In practice, in CPython, parts of the two objects are allocated statically, and parts are allocated during Python startup.\n" ]
[ 1 ]
[]
[]
[ "object", "python", "types" ]
stackoverflow_0003684082_object_python_types.txt
Q: pisa to generate a table of content via html convert Does anyone have any idea how to use the tag so the table of content comes onto the 1st page and all text is coming behind. This is what i've got so far, it generates the table of content behind my text... pdf.html <htmL> <body> <div> <pdf:toc /> </div> <pdf...
pisa to generate a table of content via html convert
Does anyone have any idea how to use the tag so the table of content comes onto the 1st page and all text is coming behind. This is what i've got so far, it generates the table of content behind my text... pdf.html <htmL> <body> <div> <pdf:toc /> </div> <pdf:nextpage> <br/> <h1> test </h1> <h2> second </h2> ...
[ "I found I couldn't get that pagebreak to work for me, so I used inline CSS and, specifically, the page-break property to fix it. \nIn your case, this should do the trick:\n<div style=\"page-break-after:always;>\n <pdf:toc />\n</div>\n<h1> test </h1> ...etc...\n\n", "As far as the links are concerned, there may...
[ 2, 1 ]
[]
[]
[ "django", "pisa", "python" ]
stackoverflow_0003684488_django_pisa_python.txt
Q: python update class instance to reflect change in a class method As I work and update a class, I want a class instance that is already created to be updated. How do I go about doing that? class MyClass: """ """ def __init__(self): def myMethod(self, case): print 'hello' classInstance = MyClass() I run Pyth...
python update class instance to reflect change in a class method
As I work and update a class, I want a class instance that is already created to be updated. How do I go about doing that? class MyClass: """ """ def __init__(self): def myMethod(self, case): print 'hello' classInstance = MyClass() I run Python inside of Maya and on software start the instance is created. When ...
[ "Alright, trying again, but with a new understanding of the question:\nclass Foo(object):\n def method(self):\n print \"Before\"\n\nf = Foo()\nf.method()\ndef new_method(self):\n print \"After\"\n\nFoo.method = new_method\nf.method()\n\nwill print\nBefore\nAfter\n\nThis will work with old style classes...
[ 1, 0, 0 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0003679592_maya_python.txt
Q: How to replace "\" with "\\" I've a path from wx.FileDialog (getpath()) shows "c:\test.jpg" which doesn't works with opencv cv.LoadImage() which needs "\\" or "/" So, I've tried to use replace function for example: s.replace("\","\\"[0:2]),s.replace("\\","\\\"[0:2]) but none those works. And, this command s.repl...
How to replace "\" with "\\"
I've a path from wx.FileDialog (getpath()) shows "c:\test.jpg" which doesn't works with opencv cv.LoadImage() which needs "\\" or "/" So, I've tried to use replace function for example: s.replace("\","\\"[0:2]),s.replace("\\","\\\"[0:2]) but none those works. And, this command s.replace("\\","/"[0:1]) returns the sam...
[ "\\ escapes the next character. To actually get a backslash, you must escape it. Use \\\\:\n s.replace(\"\\\\\",\"/\")\n\n", "I think your looking for s.replace(\"\\\\\",\"/\")\nLooking at the docs, and im not a Python programmer but its like so:\nstr.replace(old, new[, count])\n\nSo your do not need the 3rd para...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003684980_python.txt
Q: Pythonic way to convert a list of integers into a string of comma-separated ranges I have a list of integers which I need to parse into a string of ranges. For example: [0, 1, 2, 3] -> "0-3" [0, 1, 2, 4, 8] -> "0-2,4,8" And so on. I'm still learning more pythonic ways of handling lists, and this one is a bit di...
Pythonic way to convert a list of integers into a string of comma-separated ranges
I have a list of integers which I need to parse into a string of ranges. For example: [0, 1, 2, 3] -> "0-3" [0, 1, 2, 4, 8] -> "0-2,4,8" And so on. I'm still learning more pythonic ways of handling lists, and this one is a bit difficult for me. My latest thought was to create a list of lists which keeps track of pa...
[ ">>> from itertools import count, groupby\n>>> L=[1, 2, 3, 4, 6, 7, 8, 9, 12, 13, 19, 20, 22, 23, 40, 44]\n>>> G=(list(x) for _,x in groupby(L, lambda x,c=count(): next(c)-x))\n>>> print \",\".join(\"-\".join(map(str,(g[0],g[-1])[:len(g)])) for g in G)\n1-4,6-9,12-13,19-20,22-23,40,44\n\nThe idea here is to pair ea...
[ 22, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003429510_list_python.txt
Q: Given a list of words, make a subset of phrases with them What is the best way performance wise to take a list of words and turn them into phrases in python. words = ["hey","there","stack","overflow"] print magicFunction(words) >>> ["hey","there","stack","overflow", "hey there stack","hey there", "there stack ove...
Given a list of words, make a subset of phrases with them
What is the best way performance wise to take a list of words and turn them into phrases in python. words = ["hey","there","stack","overflow"] print magicFunction(words) >>> ["hey","there","stack","overflow", "hey there stack","hey there", "there stack overflow","there stack", "stack overflow", "hey there stack overfl...
[ "I think something like this will work, although I don't have access to python at the moment.\ndef magic_function(words):\n for start in range(len(words)):\n for end in range(start + 1, len(words) + 1):\n yield \" \".join(words[start:end])\n\n", "import itertools\n\n# Adapted from Python Cookbook 2nd Ed....
[ 2, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0003685805_list_python_string.txt
Q: how to set a namespace prefix in an attribute value using the lxml? I'm trying to create XML Schema using lxml. For the begining something like this: <xs:schema xmlns="http://www.goo.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.goo.com"> <xs:...
how to set a namespace prefix in an attribute value using the lxml?
I'm trying to create XML Schema using lxml. For the begining something like this: <xs:schema xmlns="http://www.goo.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.goo.com"> <xs:element type="xs:string" name="name"/> <xs:element type="xs:positiveInt...
[ "Somewhat as an aside, you need to include \"xs\": SCHEMA_NAMESPACE or such in your NSMAP -- otherwise nothing in your generated XML actually maps the 'xs' prefix to correct namespace. That will also allow you to just specify your element names with prefixes; e.g. \"xs:element\".\nAs far as your main question, I t...
[ 2 ]
[]
[]
[ "lxml", "namespaces", "prefix", "python" ]
stackoverflow_0003685374_lxml_namespaces_prefix_python.txt
Q: Python compatability issue - 'in ' requires character as left operand I make no claims to know anything at all about writing Python scripts or programming in general, but I've been tasked with writing one anyway that will have to operate on a wide variety of Python versions. I wrote, and did my testing on version...
Python compatability issue - 'in ' requires character as left operand
I make no claims to know anything at all about writing Python scripts or programming in general, but I've been tasked with writing one anyway that will have to operate on a wide variety of Python versions. I wrote, and did my testing on versions 2.3, 2.4 and all went well. Version 2.2 though is giving me fits and my ...
[ "Try using str.find, which returns -1 if the substring cannot be found.\n>>> s = \"The quick brown fox\"\n>>> s.find(\"The\")\n0\n>>> s.find(\"brown\")\n10\n>>> s.find(\"waffles\")\n-1\n\n", "You can always match using regular expressions. It's been a while since I used 2.2, so I can't recall if re is available, ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003686125_python.txt
Q: Python bytecode compiler; removes unnecessary variables? Given the following: def foo(): x = a_method_returning_a_long_list() y = a_method_which_filters_a_list(x) return y will Python's bytecode compiler keep x & y in memory, or is it clever enough to reduce it to the following? def foo(): return a...
Python bytecode compiler; removes unnecessary variables?
Given the following: def foo(): x = a_method_returning_a_long_list() y = a_method_which_filters_a_list(x) return y will Python's bytecode compiler keep x & y in memory, or is it clever enough to reduce it to the following? def foo(): return a_method_which_filters_a_list(a_method_returning_a_long_list())...
[ "It keeps x and y in memory:\nimport dis\ndis.dis(foo)\n 2 0 LOAD_GLOBAL 0 (a_method_returning_a_long_list)\n 3 CALL_FUNCTION 0\n 6 STORE_FAST 0 (x)\n\n 3 9 LOAD_GLOBAL 1 (a_method_which_filters_a_list)\n ...
[ 3, 2, 0 ]
[]
[]
[ "bytecode", "python" ]
stackoverflow_0003686101_bytecode_python.txt
Q: Couldn't close file in functional way in python3.1? I wrote a line of code using lambda to close a list of file objects in python2.6: map(lambda f: f.close(), files) It works, but doesn't in python3.1. Why? Here is my test code: import sys files = [sys.stdin, sys.stderr] for f in files: print(f.closed) # Fals...
Couldn't close file in functional way in python3.1?
I wrote a line of code using lambda to close a list of file objects in python2.6: map(lambda f: f.close(), files) It works, but doesn't in python3.1. Why? Here is my test code: import sys files = [sys.stdin, sys.stderr] for f in files: print(f.closed) # False in 2.6 & 3.1 map(lambda o : o.close(), files) for f i...
[ "map returns a list in Python 2, but an iterator in Python 3. So the files will be closed only if you iterate over the result.\nNever apply map or similar \"functional\" functions to functions with side effects. Python is not a functional language, and will never be. Use a for loop:\nfor o in files:\n o.close()\...
[ 6, 4 ]
[]
[]
[ "functional_programming", "python", "python_3.x" ]
stackoverflow_0003686244_functional_programming_python_python_3.x.txt
Q: Compensate for Auto White Balance with OpenCV I'm working on an app that takes in webcam data, applies various transformations, blurs and then does a background subtraction and threshold filter. It's a type of optical touch screen retrofitting system (the design is so different that tbeta/touchlib can't be used). ...
Compensate for Auto White Balance with OpenCV
I'm working on an app that takes in webcam data, applies various transformations, blurs and then does a background subtraction and threshold filter. It's a type of optical touch screen retrofitting system (the design is so different that tbeta/touchlib can't be used). The camera's white balance is screwing up the thres...
[ "You could try interfacing your camera through DirectShow and turn off Auto White Balance through your code or you could try first with the camera software deployed with it. It often gives you ability to do certain modifications as white balance and similar stuff.\n" ]
[ 1 ]
[]
[]
[ "background_subtraction", "opencv", "python", "touchscreen", "webcam" ]
stackoverflow_0003680829_background_subtraction_opencv_python_touchscreen_webcam.txt
Q: Why can't django load multiple pages simultaneously? I have a django aplication with an admin panel. When i add some item (it takes about 10 seconds to add it), i can't load any other page. The page is waiting for the first page to load, and then it load itself. A: Are you using the development server? It's sing...
Why can't django load multiple pages simultaneously?
I have a django aplication with an admin panel. When i add some item (it takes about 10 seconds to add it), i can't load any other page. The page is waiting for the first page to load, and then it load itself.
[ "Are you using the development server? It's single-threaded by design. You'll need to run your Django app in a real web server (like Apache) to load pages simultaneously.\n", "As Bob points out, the devserver/runserver is single-threaded, but if you want to, there is a multi-threaded local dev server option\n" ]
[ 5, 2 ]
[]
[]
[ "django", "load", "python", "simultaneous" ]
stackoverflow_0003686209_django_load_python_simultaneous.txt
Q: Including mercurial extensions from eggs Is there some way to import an extension from an .egg file? For example hggit installs itself as hg_git-0.2.4-py2.5.egg, which cannot be listed under [extensions] directly, or it's interpreted as a standard .py file. Is there some way to include that file as an extension? A...
Including mercurial extensions from eggs
Is there some way to import an extension from an .egg file? For example hggit installs itself as hg_git-0.2.4-py2.5.egg, which cannot be listed under [extensions] directly, or it's interpreted as a standard .py file. Is there some way to include that file as an extension? Alternatively, is there some way to install hg-...
[ "if the egg is installed on your Python module path (aka: you easy_installed it), just do:\nname_of_extension=\n\nin the extensions part of your .hgrc\n" ]
[ 1 ]
[]
[]
[ "distutils", "egg", "hgrc", "mercurial", "python" ]
stackoverflow_0003686256_distutils_egg_hgrc_mercurial_python.txt
Q: How can textmate make my python (pylons) development easier? I have textmate, but honestly the only thing I can do with it is simply edit a file. The handy little file browser is aslo useful. (how can I show/hide that file browser anyhow!) But I have no other knowledge/tricks up my sleeve, care to help me out? A:...
How can textmate make my python (pylons) development easier?
I have textmate, but honestly the only thing I can do with it is simply edit a file. The handy little file browser is aslo useful. (how can I show/hide that file browser anyhow!) But I have no other knowledge/tricks up my sleeve, care to help me out?
[ "If you look under the Bundles menu in TextMate there is a Python-specific sub-menu that exposes a bunch of helpful things like syntax checking, script debugging, insertion of oft used code blocks, manual look ups and so on. Most of them are bound to keyboard shortcuts (or can be bound if they are not).\nAlso, unde...
[ 2, 0 ]
[]
[]
[ "pylons", "python", "textmate" ]
stackoverflow_0003678221_pylons_python_textmate.txt
Q: how to connect HAL using dbus I'm using python and dbus. What i really need is a way to get the input from my microphone into my python program and then play it back from the program. I googled a lot and it seems pyaudio might do the trick but pyaudio does not work with my ubuntu 10.04. The next option i saw was ...
how to connect HAL using dbus
I'm using python and dbus. What i really need is a way to get the input from my microphone into my python program and then play it back from the program. I googled a lot and it seems pyaudio might do the trick but pyaudio does not work with my ubuntu 10.04. The next option i saw was telepathy. But i don't need somethi...
[ "This is really not related to HAL or D-Bus at all. Telepathy's definitely not the answer: it's an IM framework. :) If I were you, I'd look at GStreamer, which is the standard multimedia framework on the Linux desktop, via the pygst binding.\nYou'll want to use the gconfaudiosrc element to pull audio from the defau...
[ 1 ]
[]
[]
[ "dbus", "linux", "microphone", "python", "ubuntu" ]
stackoverflow_0003665490_dbus_linux_microphone_python_ubuntu.txt
Q: Is there good planning GUI component (widget) for python? I'm working on a scheduling app and looking for a calendar, timeline or other planning related GUI component for Python. Are you aware of any ? A: Have a look at PyQt. It has a calendar widget and the wrapper allows you to modify the rendering of the cale...
Is there good planning GUI component (widget) for python?
I'm working on a scheduling app and looking for a calendar, timeline or other planning related GUI component for Python. Are you aware of any ?
[ "Have a look at PyQt. It has a calendar widget and the wrapper allows you to modify the rendering of the calendar.\n", "Your question is not really clear so I can't know your needs but, maybe, you should check faces, a powerful and free project management tool that you \"program\" in python.\n", "wxPython has t...
[ 2, 1, 0 ]
[]
[]
[ "components", "python", "user_interface", "widget" ]
stackoverflow_0003684908_components_python_user_interface_widget.txt
Q: Creating restricted permutations of a list of items by category I am trying to create a number of restricted permutations of a list of items. Each item has a category, and I need to find combinations of items such that each combination does not have multiple items from the same category. To illustrate, here's some...
Creating restricted permutations of a list of items by category
I am trying to create a number of restricted permutations of a list of items. Each item has a category, and I need to find combinations of items such that each combination does not have multiple items from the same category. To illustrate, here's some sample data: Name | Category ==========|========== 1. Ora...
[ "Naive approach:\n#!/usr/bin/env python\n\nimport itertools\n\nitems = {\n 'fruits' : ('Orange', 'Apple'),\n 'toys' : ('GI-Joe', ),\n 'electronics' : ('VCR', ),\n 'sporting_goods' : ('Racquet', )\n}\n\ndef combinate(items, size=3):\n if size > len(items):\n raise Exception(\"Lower the `size` o...
[ 2, 1 ]
[]
[]
[ "combinatorics", "python", "set" ]
stackoverflow_0003686521_combinatorics_python_set.txt
Q: Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden? I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the clie...
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden?
I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reactor...
[ "Well, as the twisted docs say:\n\nDeferreds do not make the code\n magically not block\n\nWhenever you're using blocking code, such as sleep, you have to defer it to a new thread.\n#!/usr/bin/env python\nfrom twisted.internet import reactor,defer, threads\nfrom twisted.internet.task import LoopingCall\nimport tim...
[ 12, 3, 0 ]
[]
[]
[ "multithreading", "python", "redis", "twisted" ]
stackoverflow_0002466000_multithreading_python_redis_twisted.txt
Q: twisted: difference between `defer.execute` and `threads.deferToThread` What is the difference between defer.execute() and threads.deferToThread() in twisted? Both take the same arguments - a function, and parameters to call it with - and return a deferred which will be fired with the result of calling the functio...
twisted: difference between `defer.execute` and `threads.deferToThread`
What is the difference between defer.execute() and threads.deferToThread() in twisted? Both take the same arguments - a function, and parameters to call it with - and return a deferred which will be fired with the result of calling the function. The threads version explicitly states that it will be run in a thread. Ho...
[ "defer.execute does indeed execute the function in a blocking manner, in the same thread and you are correct in that defer.execute(f, args, kwargs) does the same as defer.succeed(f(*args, **kwargs)) except that defer.execute will return a callback that has had the errback fired if function f throws an exception. M...
[ 9 ]
[]
[]
[ "deferred_execution", "multithreading", "python", "twisted" ]
stackoverflow_0003686608_deferred_execution_multithreading_python_twisted.txt
Q: Fresh solr instance for every hudson test build I'm building a test suite for a python site, powered by hudson. Currently, the workflow for a test run looks like: Pull down the latest version from the repository. Create a new mysql db and import schema file and some fixture data. Run tests, largely powered by we...
Fresh solr instance for every hudson test build
I'm building a test suite for a python site, powered by hudson. Currently, the workflow for a test run looks like: Pull down the latest version from the repository. Create a new mysql db and import schema file and some fixture data. Run tests, largely powered by webtest, which means not needing to run a web server. D...
[ "Use the Solr Admin API to create a new core.\n" ]
[ 0 ]
[]
[]
[ "hudson", "python", "solr", "webob" ]
stackoverflow_0003686798_hudson_python_solr_webob.txt
Q: What does data="@/some/path" mean in Python? This is from some code I'm looking at... I think it's some sort of special format string that loads the file at the path into a binary string assigned to data, but I'm not sure as when I try to replicate it all I get is a standard string. Or is it actually a standard st...
What does data="@/some/path" mean in Python?
This is from some code I'm looking at... I think it's some sort of special format string that loads the file at the path into a binary string assigned to data, but I'm not sure as when I try to replicate it all I get is a standard string. Or is it actually a standard string and I'm reading too much into it?
[ "It's actually just a string.\n" ]
[ 4 ]
[]
[]
[ "binary", "format_string", "python", "string" ]
stackoverflow_0003686920_binary_format_string_python_string.txt
Q: How to connect to Cassandra inside a Pylons app? I created a new Pylons project, and would like to use Cassandra as my database server. I plan on using Pycassa to be able to use cassandra 0.7beta. Unfortunately, I don't know where to instantiate the connection to make it available in my application. The goal woul...
How to connect to Cassandra inside a Pylons app?
I created a new Pylons project, and would like to use Cassandra as my database server. I plan on using Pycassa to be able to use cassandra 0.7beta. Unfortunately, I don't know where to instantiate the connection to make it available in my application. The goal would be to : Create a pool when the application is launc...
[ "Well. I worked a little more. In fact, using a connection manager was probably not a good idea as this should be the template context. Additionally, opening a connection for each thread is not really a big deal. Opening a connection per request would be.\nI ended up with just pycassa.connect_thread_local() in app_...
[ 2, 1 ]
[]
[]
[ "cassandra", "pylons", "python" ]
stackoverflow_0003671535_cassandra_pylons_python.txt
Q: Convert DD/MM/YYYY HH:MM:SS into MySQL TIMESTAMP I would like a simple way to find and reformat text of the format 'DD/MM/YYYY' into 'YYYY/MM/DD' to be compatible with MySQL TIMESTAMPs, in a list of text items that may or may not contain a date atall, under python. (I'm thinking RegEx?) Basically i am looking for ...
Convert DD/MM/YYYY HH:MM:SS into MySQL TIMESTAMP
I would like a simple way to find and reformat text of the format 'DD/MM/YYYY' into 'YYYY/MM/DD' to be compatible with MySQL TIMESTAMPs, in a list of text items that may or may not contain a date atall, under python. (I'm thinking RegEx?) Basically i am looking for a way to inspect a list of items and correct any times...
[ "If you're using the MySQLdb (also known as \"mysql-python\") module, for any datetime or timestamp field you can provide a datetime type instead of a string. This is the type that is returned, also and is the preferred way to provide the value.\nFor Python 2.5 and above, you can do:\nfrom datetime import datetime\...
[ 1, 1 ]
[]
[]
[ "datetime", "mysql", "python", "regex", "timestamp" ]
stackoverflow_0003687223_datetime_mysql_python_regex_timestamp.txt
Q: How do I cascade deletes to multiple tables in SqlAlchemy? I have a table with several dependent tables that I want cascade delete. I'm having problems with it cascading too far. Some code will help explain. class Map(Base): .... #One to many relationship between the Map and Tile. #Each Map is made up ...
How do I cascade deletes to multiple tables in SqlAlchemy?
I have a table with several dependent tables that I want cascade delete. I'm having problems with it cascading too far. Some code will help explain. class Map(Base): .... #One to many relationship between the Map and Tile. #Each Map is made up of many tiles tiles = relationship('Tile', lazy='joined', ba...
[ "Your code (unless some details were omitted) should work as you expect it to:\nGraphics should not be deleted. As can be seen in relationship, the default cascade parameter is save-update, merge, which should not trigger the delete if you were to delete a Map.\nTo test, please create a routine that creates a Map, ...
[ 0, 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0003679601_orm_python_sqlalchemy.txt
Q: Reading Text with Accent - Python I did some script in python that connects to GMAIL and print a email text... But, often my emails has words with "accent". And there is my problem... For example a text that I got: "PLANO DE S=C3=9ADE" should be printed as "PLANO DE SAÚDE". How can I turn legible my email text? Wh...
Reading Text with Accent - Python
I did some script in python that connects to GMAIL and print a email text... But, often my emails has words with "accent". And there is my problem... For example a text that I got: "PLANO DE S=C3=9ADE" should be printed as "PLANO DE SAÚDE". How can I turn legible my email text? What can I use to convert theses letters ...
[ "This encoding is called Quoted-printable. In your example, you have a string (Python's unicode) encoded in UTF-8 bytes (Python's str) encoded in quoted printable bytes. So the right way to get a string value is:\n>>> b = 'PLANO DE S=C3=9ADE'\n>>> s = b.decode('quopri').decode('utf-8')\n>>> print s\nPLANO DE SÚDE\n...
[ 4, 0 ]
[]
[]
[ "diacritics", "linux", "python", "quoted_printable", "utf_8" ]
stackoverflow_0003680352_diacritics_linux_python_quoted_printable_utf_8.txt
Q: PHP or Python for creating webcharts after calculations? Is it a good idea to code such a script in Python and in which language is handy for fast performance and useful libraries/frameworks for charts?(charts would be created after calculating an expression which is input from the user) EDIT:It's a web server-sid...
PHP or Python for creating webcharts after calculations?
Is it a good idea to code such a script in Python and in which language is handy for fast performance and useful libraries/frameworks for charts?(charts would be created after calculating an expression which is input from the user) EDIT:It's a web server-side script
[ "I'm not exactly sure what you mean by \"charts\", but if you mean plotting/creating graphs, perhaps you should look at R, a free software environment for statistical computing and graphics. It has good graphics capabilities, and can connect to many environments, including Python.\n", "For Python - check matplot...
[ 1, 1, 0 ]
[]
[]
[ "charts", "php", "python" ]
stackoverflow_0003687252_charts_php_python.txt
Q: How to change a tuple into array in Python? Let's say I have a tuple t = (1,2,3,4). What's the simple way to change it into Array? I can do something like this, array = [] for i in t: array.append(i) But I prefer something like x.toArray() or something. A: If you want to convert a tuple to a list (as you se...
How to change a tuple into array in Python?
Let's say I have a tuple t = (1,2,3,4). What's the simple way to change it into Array? I can do something like this, array = [] for i in t: array.append(i) But I prefer something like x.toArray() or something.
[ "If you want to convert a tuple to a list (as you seem to want) use this:\n>>> t = (1, 2, 3, 4) # t is the tuple (1, 2, 3, 4)\n>>> l = list(t) # l is the list [1, 2, 3, 4]\n\nIn addition I would advise against using tupleas the name of a variable.\n" ]
[ 64 ]
[]
[]
[ "arrays", "python", "tuples" ]
stackoverflow_0003687702_arrays_python_tuples.txt
Q: Is there anything wrong with creating a Python Pickle powered website? I have been toying with this idea for quite awhile now, but haven't seen any information on people doing it. I have a small website project where I need to load and modify 1 object. This object is pretty simple, and shouldn't be more than a few...
Is there anything wrong with creating a Python Pickle powered website?
I have been toying with this idea for quite awhile now, but haven't seen any information on people doing it. I have a small website project where I need to load and modify 1 object. This object is pretty simple, and shouldn't be more than a few kb. Instead of running a DB for this small amount of data, why not just use...
[ "I wouldn't write a pickled string to a file directly. There are too many low-level details to worry about. Check out Durus, ZODB, or this post from FriendFeed about storing Python objects in MySQL.\nDon't discard relational databases, though, they give you a lot of bang right out of the box (even for simple proj...
[ 3, 2, 1 ]
[]
[]
[ "flask", "pickle", "python", "shelve" ]
stackoverflow_0003681922_flask_pickle_python_shelve.txt
Q: Why do we need connector.commit() after execution? I have a SQLite/Python code that runs the query command as follows. def queryDB(self, command_):_ self.cursor.execute(command_) self.connector.commit() # <---- ??? ... it works pretty well, but I have some questions. Why connector.commit() is needed...
Why do we need connector.commit() after execution?
I have a SQLite/Python code that runs the query command as follows. def queryDB(self, command_):_ self.cursor.execute(command_) self.connector.commit() # <---- ??? ... it works pretty well, but I have some questions. Why connector.commit() is needed? What does it do? What does cursor.execute() do?
[ "Per this website: http://www.amk.ca/python/writing/DB-API.html\n\"For databases that support transactions, the Python interface silently starts a transaction when the cursor is created. The commit() method commits the updates made using that cursor, and the rollback() method discards them. Each method then starts ...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003687370_python_sqlite.txt
Q: IExplorerBrowser control in python I'm try to embed a IExplorerBrowser (Windows Explorer) in a wxpython application but I cannot seem to get the IExplorerBrowser module opened in python I have the CLSID of IExplorerBrowser from the registry but when I try and open it with: from win32com import client client.genca...
IExplorerBrowser control in python
I'm try to embed a IExplorerBrowser (Windows Explorer) in a wxpython application but I cannot seem to get the IExplorerBrowser module opened in python I have the CLSID of IExplorerBrowser from the registry but when I try and open it with: from win32com import client client.gencache.GetModuleForCLSID(id) Nothing is re...
[ "Most of the windows shell interfaces can be accessed from win32com.shell. Also take a look at the sample explorer_browser.py, which should be in your site-packages/win32comext/shell/demos directory.\n" ]
[ 1 ]
[]
[]
[ "com", "python", "win32com" ]
stackoverflow_0003686122_com_python_win32com.txt
Q: Python logging objects I'm trying to reformat the output data sent to the logger based on it's class. For example: strings will be printed as they are dictionaries/lists will be automatically indented/beautified into html my custom classes will be handled on an individual basis and converted to html My problem i...
Python logging objects
I'm trying to reformat the output data sent to the logger based on it's class. For example: strings will be printed as they are dictionaries/lists will be automatically indented/beautified into html my custom classes will be handled on an individual basis and converted to html My problem is that the message sent to t...
[ "Ok, I've figured it out.\nThe documentation in the official docs is a little bit unclear, but basically, there are two attributes\nLogRecord.message -> a string representation of the message\nand \nLogRecord.msg -> the message itself.\nTo get the actual object, you must reference the .msg for it to work.\nI hope t...
[ 4, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003687864_logging_python.txt
Q: Profiling Python generators I'm adapting an application that makes heavy use of generators to produce its results to provide a web.py web interface. So far, I could wrap the call to the for-loop and the output-producing statements in a function and call that using cProfile.run() or runctx(). Conceptually: def outp...
Profiling Python generators
I'm adapting an application that makes heavy use of generators to produce its results to provide a web.py web interface. So far, I could wrap the call to the for-loop and the output-producing statements in a function and call that using cProfile.run() or runctx(). Conceptually: def output(): for value in generator(...
[ "I finally found a solution. Return value of profiling via here.\nimport cProfile\nimport pstats\nimport glob\nimport math\n\ndef gen():\n for i in range(1, 10):\n yield math.factorial(i)\n\nclass index(object):\n def GET(self):\n p = cProfile.Profile()\n\n it = gen()\n while True:...
[ 7, 2, 0 ]
[]
[]
[ "profiler", "profiling", "python", "web.py" ]
stackoverflow_0003570335_profiler_profiling_python_web.py.txt
Q: How would I go about downloading a file from a submitted link then reuploading to my server for streaming? I'm working on a project where a user can submit a link to a sound file hosted on another site through a form. I'd like to download that file to my server and make it available for streaming. I might have to ...
How would I go about downloading a file from a submitted link then reuploading to my server for streaming?
I'm working on a project where a user can submit a link to a sound file hosted on another site through a form. I'd like to download that file to my server and make it available for streaming. I might have to upload it to Amazon S3. I'm doing this in Django but I'm new to Python. Can anyone point me in the right directi...
[ "Here's how I would do it:\n\nCreate a model like SoundUpload like:\nclass SoundUpload(models.Model):\n STATUS_CHOICES = (\n (0, 'Unprocessed'),\n (1, 'Ready'),\n (2, 'Bad File'),\n )\n uploaded_by = models.ForeignKey(User)\n original_url = models.URLField(verify_true=False)\n do...
[ 0 ]
[]
[]
[ "amazon_s3", "django", "download", "file_upload", "python" ]
stackoverflow_0003688160_amazon_s3_django_download_file_upload_python.txt
Q: GUIs vs TUIs in Python I'm interested in doing rapid app development in Python. Since this is mainly for prototyping purposes, I'm looking for a way of creating "rough" user interfaces. By this, I mean that they don't have to look professional, they just have to be flexible enough to make it look the way I want. O...
GUIs vs TUIs in Python
I'm interested in doing rapid app development in Python. Since this is mainly for prototyping purposes, I'm looking for a way of creating "rough" user interfaces. By this, I mean that they don't have to look professional, they just have to be flexible enough to make it look the way I want. Originally I was going to do ...
[ "pyGTK is a lot more than curses. It includes an event loop, for one. If you're going to create TUIs, at least use something comparable, like urwid.\n", "If you are looking for a simple way to mockup a simple GUI, you might consider using a lightweight web framework like flask. You'll have access to a range of st...
[ 0, 0 ]
[]
[]
[ "gtk", "ncurses", "python", "tui", "user_interface" ]
stackoverflow_0003687922_gtk_ncurses_python_tui_user_interface.txt
Q: CherryPy - saving checkboxes selection to variables I'm trying to build a simple webpage with multiple checkboxes, a Textbox and a submit buttom. I've just bumped into web programing in Python and am trying to figure out out to do it with CherryPy. I need to associate each checkbox to a variable so my .py file kno...
CherryPy - saving checkboxes selection to variables
I'm trying to build a simple webpage with multiple checkboxes, a Textbox and a submit buttom. I've just bumped into web programing in Python and am trying to figure out out to do it with CherryPy. I need to associate each checkbox to a variable so my .py file knows which ones were selected when clicking the 'Start butt...
[ "Here's a minimal example:\nimport cherrypy\n\nclass Root(object):\n @cherrypy.expose\n def default(self, **kwargs):\n print kwargs\n return '''<form action=\"\" method=\"POST\">\nHost Availability:\n<input type=\"checkbox\" name=\"goal\" value=\"cpu\" /> CPU idle\n<input type=\"checkbox\" name=...
[ 10 ]
[]
[]
[ "checkbox", "cherrypy", "python" ]
stackoverflow_0003686773_checkbox_cherrypy_python.txt
Q: web.py on Google App Engine I'm trying to get a web.py application running on GAE. I hoped that sth like the following might work import web from google.appengine.ext.webapp.util import run_wsgi_app [...] def main(): app = web.application(urls, globals()) run_wsgi_app(app) But obviously the app object d...
web.py on Google App Engine
I'm trying to get a web.py application running on GAE. I hoped that sth like the following might work import web from google.appengine.ext.webapp.util import run_wsgi_app [...] def main(): app = web.application(urls, globals()) run_wsgi_app(app) But obviously the app object doesn't conform with the run_wsgi_...
[ "Here is a snippet of StackPrinter, a webpy application that runs on top of Google App Engine.\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nimport web\n...\napp = web.application(urls, globals())\n\ndef main():\n\n application = app.wsgifunc()\n run_wsgi_app(application)\n\nif __name__ == '__ma...
[ 11, 0 ]
[]
[]
[ "google_app_engine", "python", "web.py" ]
stackoverflow_0003665292_google_app_engine_python_web.py.txt
Q: Convert function to single line list comprehension Is it possible to convert this function, list comprehension combination into a single list comprehension (so that keep is not needed)? def keep(list, i, big): for small in list[i+1:]: if 0 == big % small: return False return True multi...
Convert function to single line list comprehension
Is it possible to convert this function, list comprehension combination into a single list comprehension (so that keep is not needed)? def keep(list, i, big): for small in list[i+1:]: if 0 == big % small: return False return True multiples[:] = [n for i,n in enumerate(multiples) if keep(mul...
[ "I think this is it:\nmultiples[:] = [n for i,n in enumerate(multiples) \n if all(n % small for small in multiples[i+1:])] \n\n", "multiples[:] = [n for i, n in enumerate(multiples) if 0 not in [n % other for other in multiples[i+1:]]\nAdvisible? Probably not.\n", "First thing is to learn ...
[ 6, 2, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003688468_list_comprehension_python.txt
Q: Django - Multiple columns primary key I would like to implement multicolumns primary keys in django. I've tried to implement an AutoSlugField() which concatenate my columns values(foreignkey/dates) ... models.py : class ProductProduction(models.Model): enterprise = models.ForeignKey('Enterprise') product =...
Django - Multiple columns primary key
I would like to implement multicolumns primary keys in django. I've tried to implement an AutoSlugField() which concatenate my columns values(foreignkey/dates) ... models.py : class ProductProduction(models.Model): enterprise = models.ForeignKey('Enterprise') product = models.ForeignKey('Product') date = mo...
[ "Here is the explanation of the autoslugfield I used.\nhttp://packages.python.org/django-autoslug/fields.html\nRegards,\nYoan\n" ]
[ 0 ]
[]
[]
[ "composite_primary_key", "django", "django_models", "foreign_keys", "python" ]
stackoverflow_0003684011_composite_primary_key_django_django_models_foreign_keys_python.txt
Q: Method vs. function in case of simple function I have original class (DownloadPage) and I need to add just one simple functionality (get_info). What is better approach in OOP? def get_info(page): # make simple function ... result = get_info(DownloadPage()) or class MyDownloadPage(DownloadPage): # make new ...
Method vs. function in case of simple function
I have original class (DownloadPage) and I need to add just one simple functionality (get_info). What is better approach in OOP? def get_info(page): # make simple function ... result = get_info(DownloadPage()) or class MyDownloadPage(DownloadPage): # make new class with inheritance def get_info(self): ...
[ "The answer truly depends on whether or not you want that get_info function/method can function on things other than a MyDownloadPage. At present, I'd go with the free function but when requirements solidify one way or the other it should be easy enough to transform your solution either way.\n(I prefer the free fu...
[ 3, 2, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003686535_oop_python.txt
Q: Change enclosing quotes in Vim In Vim, it's a quick 3-character command to change what's inside the current quoted string (e.g., ci"), but is there a simple way to change what type of quotes are currently surrounding the cursor? Sometimes I need to go from "blah" to """blah""" or "blah" to 'blah' (in Python sour...
Change enclosing quotes in Vim
In Vim, it's a quick 3-character command to change what's inside the current quoted string (e.g., ci"), but is there a simple way to change what type of quotes are currently surrounding the cursor? Sometimes I need to go from "blah" to """blah""" or "blah" to 'blah' (in Python source code) and I'd ideally like to do ...
[ "Try the surround.vim plugin. I find it an essential addition to any vim installation.\n", "Surround.vim is great, but I don't think it'll handle your triple-quoted needs directly.\nThe way I've done stuff along these lines (when surround wasn't appropriate) was to use %, make the change, then double-backtick to ...
[ 18, 2 ]
[]
[]
[ "python", "surround", "vim" ]
stackoverflow_0003687260_python_surround_vim.txt
Q: QGraphicsView not displaying QGraphicsItems Using PyQt4. My goal is to load in "parts" of a .png, assign them to QGraphicsItems, add them to the scene, and have the QGraphicsView display them. (Right now I don't care about their coordinates, all I care about is getting the darn thing to work). Currently nothing is...
QGraphicsView not displaying QGraphicsItems
Using PyQt4. My goal is to load in "parts" of a .png, assign them to QGraphicsItems, add them to the scene, and have the QGraphicsView display them. (Right now I don't care about their coordinates, all I care about is getting the darn thing to work). Currently nothing is displayed. At first I thought it was a problem w...
[ "It's quite hard to tell what's wrong with your code as it's not complete and missing some parts to get it compiled. Though there are couple of places which could potentially cause the problem:\n\nYour Title class constructor; I believe you should be calling the base class constructor there by executing: QtGui.QGra...
[ 2 ]
[]
[]
[ "pyqt", "python", "qgraphicsitem", "qgraphicsview" ]
stackoverflow_0003682282_pyqt_python_qgraphicsitem_qgraphicsview.txt
Q: Schedule a cron job for execution every hour on certain days on App Engine I would like to schedule a cron task to run every hour, but only from Thursday through Monday. Is a schedule like this possible? From the documentation, it looks like I can schedule a cron task to run at an hourly interval or on specific ...
Schedule a cron job for execution every hour on certain days on App Engine
I would like to schedule a cron task to run every hour, but only from Thursday through Monday. Is a schedule like this possible? From the documentation, it looks like I can schedule a cron task to run at an hourly interval or on specific days at a single specific time, but I cannot figure out how to schedule a cron t...
[ "Like you noticed in the documentation for cronjobs, the source also seems to indicate that the interval schedule format doesn't let you restrict the interval to particular day(s) of the week.\nThough you can't schedule your task with a single cronjob, you could schedule it with multiple cronjobs:\nevery thu,fri,sa...
[ 2 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0003688487_cron_google_app_engine_python.txt
Q: when converting a python list to json and back, do you cast? When you convert a list of user objects into json, and then convert it back to its original state, do you have to cast? Are there any security issues of taking a javascript json object and converting it into a python list object? A: json.dumps(somepyth...
when converting a python list to json and back, do you cast?
When you convert a list of user objects into json, and then convert it back to its original state, do you have to cast? Are there any security issues of taking a javascript json object and converting it into a python list object?
[ "json.dumps(somepython) gives you a valid JSON string representing the Python object somepython (which may perfectly well be a list) and json.loads(ajsonstring) goes the other way 'round -- both without any security issue nor \"cast\" (?). That's with Python 2.6 or better, using the json module in the standard lib...
[ 2, 1 ]
[]
[]
[ "json", "python", "security" ]
stackoverflow_0003689468_json_python_security.txt
Q: Flask/Werkzeug, how to return previous page after login I am using the Flask micro-framework which is based on Werkzeug, which uses Python. Before each restricted page there is a decorator to ensure the user is logged in, currently returning them to the login page if they are not logged in, like so: # Decorator de...
Flask/Werkzeug, how to return previous page after login
I am using the Flask micro-framework which is based on Werkzeug, which uses Python. Before each restricted page there is a decorator to ensure the user is logged in, currently returning them to the login page if they are not logged in, like so: # Decorator def logged_in(f): @wraps(f) def decorated_function(*arg...
[ "I think standard practice is to append the URL to which the user needs to be redirected after a successful login to the end of the login URL's querystring.\nYou'd change your decorator to something like this (with redundancies in your decorator function also removed):\ndef logged_in(f):\n @wraps(f)\n def dec...
[ 25, 12 ]
[]
[]
[ "authentication", "flask", "python", "werkzeug" ]
stackoverflow_0003686465_authentication_flask_python_werkzeug.txt
Q: Merge SQLite files into one db file, and 'begin/commit' question This post refers to this page for merging SQLite databases. The sequence is as follows. Let's say I want to merge a.db and b.db. In command line I do the following. sqlite3 a.db attach 'b.db' as toM; begin; <-- insert into benchmark select * from ...
Merge SQLite files into one db file, and 'begin/commit' question
This post refers to this page for merging SQLite databases. The sequence is as follows. Let's say I want to merge a.db and b.db. In command line I do the following. sqlite3 a.db attach 'b.db' as toM; begin; <-- insert into benchmark select * from toM.benchmark; commit; <-- detach database toM; It works well, but in...
[ "Apparently, Cursor.execute doesn't support the 'commit' command. It does support the 'begin' command but this is redundant because sqlite3 begins them for you anway:\n>>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> cur = conn.cursor()\n>>> cur.execute('begin')\n<sqlite3.Cursor object at 0x0104B020>...
[ 13 ]
[]
[]
[ "merge", "python", "sqlite" ]
stackoverflow_0003689694_merge_python_sqlite.txt