content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I make xml.sax use a HTTP proxy for its DTD requests? It is a known problem that XML parsers often send out HTTP requests for fetching DTDs referenced in the documents. Specifically, Python's one does this. This causes excessive traffic for www.w3.org, which hosts a lot of these DTDs. In turn, this makes t...
How can I make xml.sax use a HTTP proxy for its DTD requests?
It is a known problem that XML parsers often send out HTTP requests for fetching DTDs referenced in the documents. Specifically, Python's one does this. This causes excessive traffic for www.w3.org, which hosts a lot of these DTDs. In turn, this makes the XML parsing take a very long time and in some cases time out. Th...
[ "One quick and dirty way to do this would be to monkey patch saxutils.prepare_input_source. You can pretty much just copy+paste it and tweak the branch that calls urllib.urlopen so that it gets a UrlOpener from urllib2 with your proxy installed. \nUnfortunately, I think that this is the only way that you're going t...
[ 2 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0004254767_python_sax_xml.txt
Q: Python Cookbook is for Python 2.4 Python Cookbook 2nd edition is updated for Python 2.4. Is it still ok to study the book using Python version 2.5 or 2.6? A: Python 2.4 is too old. In my opinion it will worth the time and money to find a more recent resource, especially if your time is limited. More recent books...
Python Cookbook is for Python 2.4
Python Cookbook 2nd edition is updated for Python 2.4. Is it still ok to study the book using Python version 2.5 or 2.6?
[ "Python 2.4 is too old. In my opinion it will worth the time and money to find a more recent resource, especially if your time is limited. More recent books will also cover changes in the libraries, including advances in python web app development, which I don't expect to find in aged resources. Especially for a co...
[ 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004253903_python.txt
Q: How do I make Django ManyToMany 'through' queries more efficient? I'm using a ManyToManyField with a 'through' class and this results in a lot of queries when fetching a list of things. I'm wondering if there's a more efficient way. For example here are some simplified classes describing Books and their several au...
How do I make Django ManyToMany 'through' queries more efficient?
I'm using a ManyToManyField with a 'through' class and this results in a lot of queries when fetching a list of things. I'm wondering if there's a more efficient way. For example here are some simplified classes describing Books and their several authors, which goes through a Role class (to define roles like "Editor", ...
[ "This is a pattern I come across often in Django. It's really easy to create properties such as your author_name, and they work great when you display one book, but the number of queries explodes when you want to use the property for many books on a page.\nFirstly, you can use select_related to prevent the lookup f...
[ 8, 1 ]
[]
[]
[ "django", "many_to_many", "python" ]
stackoverflow_0004255700_django_many_to_many_python.txt
Q: Django: can't bind an uploaded image to a form ImageField() here's my problem, I've created this form: class SettingsForm(forms.Form): ... logo = forms.ImageField() ... The upload works fine and I managed to display the image but I can't bind it to the form. Here's what I've done: data = ... f...
Django: can't bind an uploaded image to a form ImageField()
here's my problem, I've created this form: class SettingsForm(forms.Form): ... logo = forms.ImageField() ... The upload works fine and I managed to display the image but I can't bind it to the form. Here's what I've done: data = ... files = {'logo': SimpleUploadedFile('logo.jpg', logo.read())} fo...
[ "Im not sure about this, but according to the django documentation, on binding forms, the data and files are not kwargs, but are args, so try this:\nform = SettingsForm(data, files)\n\n" ]
[ 1 ]
[]
[]
[ "binding", "django", "forms", "python", "upload" ]
stackoverflow_0004255854_binding_django_forms_python_upload.txt
Q: mod_wsgi + apache not multithreaded, why? WSGI application # coding: utf-8 import time def application(environ, start_response): status = '200 OK' output = str(time.time()) time.sleep(5) output += ' -> ' + str(time.time()) response_headers = [('Content-type', 'text/html; charset=utf-8'), ...
mod_wsgi + apache not multithreaded, why?
WSGI application # coding: utf-8 import time def application(environ, start_response): status = '200 OK' output = str(time.time()) time.sleep(5) output += ' -> ' + str(time.time()) response_headers = [('Content-type', 'text/html; charset=utf-8'), ('Content-Length', str(le...
[ "This is being dealt with on mod_wsgi mailing list. See:\nhttp://groups.google.com/group/modwsgi/browse_frm/thread/b8aaab6bfc4cca6d\n", "While not exactly an answer, I noticed the serial behavior with a similar setup when testing on a single browser with multiple tabs. ( i tried chrome7 and ff4 )\nWondering if it...
[ 3, 1 ]
[]
[]
[ "apache", "python", "wsgi" ]
stackoverflow_0003341514_apache_python_wsgi.txt
Q: How to override Python list(iterator) behaviour? Running this: class DontList(object): def __getitem__(self, key): print 'Getting item %s' % key if key == 10: raise KeyError("You get the idea.") return None def __getattr__(self, name): print 'Getting attr %s' % name ...
How to override Python list(iterator) behaviour?
Running this: class DontList(object): def __getitem__(self, key): print 'Getting item %s' % key if key == 10: raise KeyError("You get the idea.") return None def __getattr__(self, name): print 'Getting attr %s' % name return None list(DontList()) Produces this: Getting...
[ "If you want to override the iteration then just define the __iter__ method in your class\n", "Just raise IndexError instead of KeyError. KeyError is meant for mapping-like classes (e.g. dict), while IndexError is meant for sequences.\nIf you define the __getitem__() method on your class, Python will automatical...
[ 7, 3, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004256357_python.txt
Q: Is it possible to use celery for synchronous tasks? Nearly synchronous works, too; basically, I want to delegate the data access and processing behind a web app to a task queue for most jobs. What's the fastest latency that I can consider reasonable for celery tasks? Update (for clarification) I guess for clarity ...
Is it possible to use celery for synchronous tasks?
Nearly synchronous works, too; basically, I want to delegate the data access and processing behind a web app to a task queue for most jobs. What's the fastest latency that I can consider reasonable for celery tasks? Update (for clarification) I guess for clarity I should explain that throughput -- while nice -- is not ...
[ "When I say throughput I mean the average latency from sending a task until it's been executed. With roundtrip I mean the average time it takes to send a task, executing it, sending the result back and retrieving the result.\nAs I said in the comments I currently don't have any official numbers to share, but with\n...
[ 7 ]
[]
[]
[ "celery", "python", "task", "task_queue" ]
stackoverflow_0004222489_celery_python_task_task_queue.txt
Q: Make URL point to .py file in App Engine I'm just now digging into GAE and I see two ways to make a particular URL pull up the right page. The first way is using handlers: handlers: - url: /.* script: helloworld.py The other way is using the following: application = webapp.WSGIApplication( ...
Make URL point to .py file in App Engine
I'm just now digging into GAE and I see two ways to make a particular URL pull up the right page. The first way is using handlers: handlers: - url: /.* script: helloworld.py The other way is using the following: application = webapp.WSGIApplication( [('/', MainPage), ...
[ "You need to use both. The section in app.yaml tells App Engine where to look for your WSGI application. application = webapp.WSGIApplication(...) sets up your WSGI application using the webapp framework.\nupdate:\napp.yaml:\nhandlers:\n - url: /city.*\n script: cityhandler.py\n\ncityhandler.py\napplication =...
[ 7 ]
[]
[]
[ "google_app_engine", "python", "url" ]
stackoverflow_0004258214_google_app_engine_python_url.txt
Q: How do I manually put cookies in a jar? I'm using python with urllib2 & cookielib and such to open a url. This url set's one cookie in it's header and two more in the page with some javascript. It then redirects to a different page. I can parse out all the relevant info for the cookies being set with the javascrip...
How do I manually put cookies in a jar?
I'm using python with urllib2 & cookielib and such to open a url. This url set's one cookie in it's header and two more in the page with some javascript. It then redirects to a different page. I can parse out all the relevant info for the cookies being set with the javascript, but I can't for the life of me figure out ...
[ "You can't set cookies for another domain - browsers will not allow it.\n" ]
[ 0 ]
[]
[]
[ "authentication", "cookielib", "cookies", "python" ]
stackoverflow_0004258278_authentication_cookielib_cookies_python.txt
Q: How can I clean stuff up on program exit? I have a command line program that wants to pickle things when I send it a ctrl-C via the terminal. I have a some questions and concerns: How do I perform this handling? Do I check for a KeyboardInterrupt? Is there a way to implement an exit function? What if the progra...
How can I clean stuff up on program exit?
I have a command line program that wants to pickle things when I send it a ctrl-C via the terminal. I have a some questions and concerns: How do I perform this handling? Do I check for a KeyboardInterrupt? Is there a way to implement an exit function? What if the program is halted in the middle of a write to a struc...
[ "You can use atexit for defining an exit handler. Modifications of Python objects will be treated atomically, so you should be fine as long as your code is arranged in a way that your objects are always in a consistent state between (byte code) instructions.\n", "(1) Use the atexit module:\ndef pickle_things():\...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004258291_python.txt
Q: shutil.move -> WindowsError: [Error32] The process cannot access the file I use Python 2.5. and have a problem with shutil.move print(srcFile) print(dstFile) shutil.move(srcFile, dstFile) Output: c:\docume~1\aaa\locals~1\temp\3\tmpnw-sgp D:\dirtest\d\c\test.txt ... WindowsError: [Error32] The process cannot acces...
shutil.move -> WindowsError: [Error32] The process cannot access the file
I use Python 2.5. and have a problem with shutil.move print(srcFile) print(dstFile) shutil.move(srcFile, dstFile) Output: c:\docume~1\aaa\locals~1\temp\3\tmpnw-sgp D:\dirtest\d\c\test.txt ... WindowsError: [Error32] The process cannot access the file because it is being used by another process: 'c:\\docume~1\\aaa\\...
[ "If you want to continue in your script use:\ntry:\n shutil.move(srcFile, dstFile)\nexcept WindowsError:\n pass\n\nThe reason your getting error 32 is because there is another process on your computer or server that is using that file. You might want to not copy temp files as they are not really important by ...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004258140_python.txt
Q: python reporting tool, similar to birtviewer Can you guys please tell if building my own birtviewer like reporting tool but using python is a crazy idea. The company I'm working now, we are using birtviewer to generate reports for the clients, but I'm already getting frustrated tweaking the code to suit our client...
python reporting tool, similar to birtviewer
Can you guys please tell if building my own birtviewer like reporting tool but using python is a crazy idea. The company I'm working now, we are using birtviewer to generate reports for the clients, but I'm already getting frustrated tweaking the code to suit our client needs and it's written on massive java code which...
[ "Sure. Write it. Make it open source and give us a git repo to have a little look... Honestly if the problem exists solve it.\n" ]
[ 0 ]
[]
[]
[ "python", "reporting" ]
stackoverflow_0004258624_python_reporting.txt
Q: Python: some function for args -> *args (similar like those in functools) I had these implementations: def vecAdd(v1, v2): return tuple(map(add, izip(v1,v2))) def vecMul(v1, f): return tuple(map(mul, izip(v1,repeat(f)))) Those didn't work because add (and mul) is called like add((x,y)), i.e. it only gets one sing...
Python: some function for args -> *args (similar like those in functools)
I had these implementations: def vecAdd(v1, v2): return tuple(map(add, izip(v1,v2))) def vecMul(v1, f): return tuple(map(mul, izip(v1,repeat(f)))) Those didn't work because add (and mul) is called like add((x,y)), i.e. it only gets one single argument. Is there some function which basically does the following? def fun...
[ "You could do this with itertools.starmap or itertools.imap.\nimap is like starmap except that it zips the arguments first.\nSo instead of calling izip yourself, you could just use imap:\nimport itertools as it\ndef vecAdd(v1, v2): return tuple(it.imap(add, v1, v2))\ndef vecMul(v1, f): return tuple(it.imap(mul, v1,...
[ 5 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0004258992_functional_programming_python.txt
Q: Convert wav to ogg vorbis in Python How can I transcode a wav file to ogg vorbis format using Python? I can convert to mp3 using PyMedia 1.3.7.3, but when I set the output stream type to 'ogg', I get the error: oggvorbis_encode_init: init_encoder failed and the script dies. A: From PyMedia's website: OGG( opt...
Convert wav to ogg vorbis in Python
How can I transcode a wav file to ogg vorbis format using Python? I can convert to mp3 using PyMedia 1.3.7.3, but when I set the output stream type to 'ogg', I get the error: oggvorbis_encode_init: init_encoder failed and the script dies.
[ "From PyMedia's website: \n\nOGG( optional with vorbis library )\n\nYou need to install Vorbis in order for the OGG encoder to work. Since the old version of your question tells me that you're on windows you can grab it here:\nhttp://www.vorbis.com/setup_windows/\n" ]
[ 2 ]
[]
[]
[ "mp3", "ogg", "oggvorbis", "python", "transcoding" ]
stackoverflow_0003982530_mp3_ogg_oggvorbis_python_transcoding.txt
Q: import of python/django modules fails on debian vps debian vps with gigatux. using django/python with mod_wsgi and im using virtualenvs as i hope to be hosting a few different sites which may well be at different levels. im having an issue getting the site running, right now i can't even do a syncdb as it refuses ...
import of python/django modules fails on debian vps
debian vps with gigatux. using django/python with mod_wsgi and im using virtualenvs as i hope to be hosting a few different sites which may well be at different levels. im having an issue getting the site running, right now i can't even do a syncdb as it refuses to import the django package that is inside the site-pack...
[ "Mixing up environments won't help.\nClearly some packages are installed in the bundled python and some other in the virtualenv.\nMy suggestion, stick to virtualenv\nAnd work on the virtualenv, always, by source /path/to/venv/bin/activate\nWithin the wsgi file, enable the virtualenv. You do that not by importing it...
[ 1, 0 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0004258277_django_mod_wsgi_python.txt
Q: In python, what's the most efficient way to combine 3 dicts and to sort by one of the dict's keys? Example: list1 = {'52': {'timestamp':'1234567890', 'name':'Jason Bourne'}, '42': {'timestamp':'2345678891', 'name':'Sarah Parker'} } list2 = {'61': {'timestamp':'3456789012', 'name':'Mike Williams'...
In python, what's the most efficient way to combine 3 dicts and to sort by one of the dict's keys?
Example: list1 = {'52': {'timestamp':'1234567890', 'name':'Jason Bourne'}, '42': {'timestamp':'2345678891', 'name':'Sarah Parker'} } list2 = {'61': {'timestamp':'3456789012', 'name':'Mike Williams'}, '12': {'timestamp':'4567889123', 'name':'Robert Tissone'} } list3 = {'56': {'times...
[ "sorted(itertools.chain(list1.itervalues(), list2.itervalues(),\n list3.itervalues()), key=operator.itemgetter('timestamp'))\n\n", "from itertools import chain\nfrom operator import itemgetter\n\ndef sortedchain(dicos, key):\n return sorted(chain(v for d in dicos for v in d.values()), key=itemgetter(key))\n...
[ 8, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004258782_dictionary_python.txt
Q: Module uncallable in Python? I've run into an error with Python. Please see the code examples below. I run event_timer.py and I get the following error message. Both of the files listed below are in the same folder. Traceback (most recent call last): File "E:\python\event_timer\event_timer.py", line 7, in ...
Module uncallable in Python?
I've run into an error with Python. Please see the code examples below. I run event_timer.py and I get the following error message. Both of the files listed below are in the same folder. Traceback (most recent call last): File "E:\python\event_timer\event_timer.py", line 7, in timer = EventTimer() TypeError: 'm...
[ "When you write\nimport EventTimer\n\nyou make a new variable, EventTimer, pointing to a module -- the module that you've just written! Inside that module is a class, Timer. So to make an instance of that class, you do\ntimer = EventTimer.Timer()\n\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0004259180_python.txt
Q: Python, BeautifulSoup or LXML - Parsing image URL's from HTML using CSS tags I have searched high and low for a decent explanation of how BeautifulSoup or LXML work. Granted, their documentation is great, but for someone like myself, a python/programming novice, it is difficult to decipher what I am looking for. ...
Python, BeautifulSoup or LXML - Parsing image URL's from HTML using CSS tags
I have searched high and low for a decent explanation of how BeautifulSoup or LXML work. Granted, their documentation is great, but for someone like myself, a python/programming novice, it is difficult to decipher what I am looking for. Anyways, as my first project, I am using Python to parse an RSS feed for post link...
[ "Using lxml, you might do something like this:\nimport feedparser\nimport lxml.html as lh\nimport urllib2\n\n#Import Feed for Parsing\nd = feedparser.parse(\"http://feeds.boston.com/boston/bigpicture/index\")\n\n# Print feed name\nprint d['feed']['title']\n\n# Determine number of posts and set range maximum\nposts ...
[ 3, 1, 1 ]
[]
[]
[ "beautifulsoup", "image", "lxml", "parsing", "python" ]
stackoverflow_0004258658_beautifulsoup_image_lxml_parsing_python.txt
Q: How to design a website on Django platform? Apologies if my question is misleading. Here's what I mean. In Visual Studio 2010 for example, you could visually design a website or a web application as well as add C# code here and there. How would I design my website without an IDE, just by using Python IDLE and Djan...
How to design a website on Django platform?
Apologies if my question is misleading. Here's what I mean. In Visual Studio 2010 for example, you could visually design a website or a web application as well as add C# code here and there. How would I design my website without an IDE, just by using Python IDLE and Django platform. Would I need to use something like ...
[ "Django source code is usually edited in a non-GUI application. So, unless you use the code tab, Dreamweaver will be useless. \nThat is, unless you create a static HTML file first then populate it with dynamic code and separate it into bits.\n", "\njust by using Python IDLE and Django platform. \n\n\nStart the we...
[ 8, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004259352_django_python.txt
Q: Python setup script extensions, how do you include a .h file? So I've got a directory that looks something like this: home\ setup.py some_python_file.py ext\ __init__.py c_file1.c c_file2.c ext_header.h Obviously the header file is necessary to compile the c fil...
Python setup script extensions, how do you include a .h file?
So I've got a directory that looks something like this: home\ setup.py some_python_file.py ext\ __init__.py c_file1.c c_file2.c ext_header.h Obviously the header file is necessary to compile the c files, but the problem is that I can't get the setup script to include...
[ "I have a feeling pyfunc is on track for a more standard solution, but I did find another solution on my own. I have no idea if this is a good solution or just a hack, but all I did is add the header file to the MANIFEST.in. The documentation doesn't really make it seem like this is what the MANIFEST.in file is f...
[ 10, 3 ]
[]
[]
[ "c", "installation", "python", "setup.py" ]
stackoverflow_0004259170_c_installation_python_setup.py.txt
Q: how to find the POST or GET variables posted by mechanize (python) i'm using mechanize to submit a form like this... import mechanize br = mechanize.Browser() br.open('http://stackoverflow.com') br.select_form(nr=0) br['q'] = "test" br.set_handle_robots(False) response = br.submit() print response.info() print ...
how to find the POST or GET variables posted by mechanize (python)
i'm using mechanize to submit a form like this... import mechanize br = mechanize.Browser() br.open('http://stackoverflow.com') br.select_form(nr=0) br['q'] = "test" br.set_handle_robots(False) response = br.submit() print response.info() print response.read() using firebug i can see that the actual variables poste...
[ "You can enable debug mode in mechanize by putting this:\nimport mechanize\n\nbr = mechanize.Browser()\nbr.set_debug_http(True)\n... \n\nHope this can help :)\n", "print br.form.get_value('q')\n\n" ]
[ 2, 1 ]
[]
[]
[ "forms", "get", "mechanize", "post", "python" ]
stackoverflow_0004186194_forms_get_mechanize_post_python.txt
Q: MAC, ethernet id using python How do you get correct MAC/Ethernet id of local network card using python? Most of the article on Google/stackoverflow suggests to parse the result of ipconfig /all (windows) and ifconfig (Linux). On windows (2x/xp/7) 'ipconfig /all' works fine but is this a fail safe method? I am new...
MAC, ethernet id using python
How do you get correct MAC/Ethernet id of local network card using python? Most of the article on Google/stackoverflow suggests to parse the result of ipconfig /all (windows) and ifconfig (Linux). On windows (2x/xp/7) 'ipconfig /all' works fine but is this a fail safe method? I am new to linux and I have no idea whethe...
[ "import sys\nimport os\n\ndef getMacAddress(): \n if sys.platform == 'win32': \n for line in os.popen(\"ipconfig /all\"): \n if line.lstrip().startswith('Physical Address'): \n mac = line.split(':')[1].strip().replace('-',':') \n break \n else: \n for lin...
[ 6, 4, 2 ]
[]
[]
[ "ethernet", "mac_address", "python" ]
stackoverflow_0004258822_ethernet_mac_address_python.txt
Q: What is the state of exception safety in Python? I know about the with statement for Python resource handling. What other concerns are there for exception safe code in Python? EDIT: The concern here is with opening files and such. For instance, suppose an init function raises an exception. What is the state of th...
What is the state of exception safety in Python?
I know about the with statement for Python resource handling. What other concerns are there for exception safe code in Python? EDIT: The concern here is with opening files and such. For instance, suppose an init function raises an exception. What is the state of the object being initialized?
[ "\nFor instance, suppose an init function raises an exception. What is the state of the object being initialized? \n\nHint. When in doubt, actually run an experiment.\n>>> class Partial( object ):\n... def __init__( self ):\n... self.a= 1\n... raise Exception\n... self.b= 2\n... \n>>> p...
[ 4, 3, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0004259792_exception_python.txt
Q: Updating a Django project from 1.2 to 1.3, manage.py not working properly I decided I wanted to update my Django 1.2 project to Django 1.3 to take advantage of the new static files mechanisms. I deleted my old version of Django, and followed the documentation's instructions for installing the development version f...
Updating a Django project from 1.2 to 1.3, manage.py not working properly
I decided I wanted to update my Django 1.2 project to Django 1.3 to take advantage of the new static files mechanisms. I deleted my old version of Django, and followed the documentation's instructions for installing the development version from svn. The changes seem to have taken. That is, python -c "import django; pr...
[ "In order to use a management command, you need to add the application that provides it to INSTALLED_APPS in settings.py. From the docs:\n\nFirst, you’ll need to make sure that django.contrib.staticfiles is in your INSTALLED_APPS.\n\nThat should make the command available.\n" ]
[ 18 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004259831_django_python.txt
Q: Running a web app in Grails vs Django I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective: Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typ...
Running a web app in Grails vs Django
I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective: Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typical tomcat + mysql on linux. If django it...
[ "You can run grails in 256 megs of ram. Many members of the community are doing so. That being said I would say in either platform you want much more ram than that to make sure your performant. But I might also reccomend checking out www.linode.com. You can get quality hosting for a very reasonable cost and add...
[ 9, 5, 2, 1, 0 ]
[]
[]
[ "django", "grails", "groovy", "python", "web_applications" ]
stackoverflow_0000195101_django_grails_groovy_python_web_applications.txt
Q: How do i correct a files extension? I started programming in Python a couple of days ago and I have a problem I couldn't solve yet. I want to correct a files file extension by guessing its mimetype. I tried this: new_file_name = mimetypes.guess_extension(mimetypes.guess_type(file_name))) os.rename(file_name, new_f...
How do i correct a files extension?
I started programming in Python a couple of days ago and I have a problem I couldn't solve yet. I want to correct a files file extension by guessing its mimetype. I tried this: new_file_name = mimetypes.guess_extension(mimetypes.guess_type(file_name))) os.rename(file_name, new_file_name) Why doesnt it work?
[ "mimetypes uses the existing extension to guess the file type. Use magic instead to examine the contents.\n" ]
[ 5 ]
[]
[]
[ "file", "mime_types", "python", "rename" ]
stackoverflow_0004260737_file_mime_types_python_rename.txt
Q: PHP equivalent of Python's func(*[args]) In Python I can do this: def f(a, b, c): print a, b, c f(*[1, 2, 3]) How do you say this in PHP? A: Use call_user_func_array: call_user_func_array('f', array(1, 2, 3)); If you wanted to call a class method, you'd use array($instance, 'f') instead of 'f' and if it w...
PHP equivalent of Python's func(*[args])
In Python I can do this: def f(a, b, c): print a, b, c f(*[1, 2, 3]) How do you say this in PHP?
[ "Use call_user_func_array:\ncall_user_func_array('f', array(1, 2, 3));\n\nIf you wanted to call a class method, you'd use array($instance, 'f') instead of 'f' and if it was a static class function you'd use array('ClassName', 'f') or 'ClassName::f'. See the callback type docs for details about that.\n" ]
[ 9 ]
[]
[]
[ "args", "php", "python" ]
stackoverflow_0004261936_args_php_python.txt
Q: How to get running counts for numpy array values? OK, I think this will be fairly simple, but my numpy-fu is not quite strong enough. I've got a an array A of ints; it's tiled N times. I want a running count of the number of times each element is used. For example, the following (I've reshaped the array to make th...
How to get running counts for numpy array values?
OK, I think this will be fairly simple, but my numpy-fu is not quite strong enough. I've got a an array A of ints; it's tiled N times. I want a running count of the number of times each element is used. For example, the following (I've reshaped the array to make the repetition obvious): [0, 1, 2, 0, 0, 1, 0] \ [0, 1, 2...
[ "Here's my take on it:\ndef countify2(ar):\n ar2 = np.ravel(ar)\n ar3 = np.empty(ar2.shape, dtype=np.int32)\n uniques = np.unique(ar2)\n myarange = np.arange(ar2.shape[0])\n for u in uniques:\n ar3[ar2 == u] = myarange\n return ar3\n\nThis method is most effective when there are many more e...
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004260645_numpy_python.txt
Q: Efficient Empirical CDF Computation / Storage I'm trying to precompute the distributions of several random variables. In particular, these random variables are the results of functions evaluated at locations in a genome, so there will be on the order of 10^8 or 10^9 values for each. The functions are pretty smooth...
Efficient Empirical CDF Computation / Storage
I'm trying to precompute the distributions of several random variables. In particular, these random variables are the results of functions evaluated at locations in a genome, so there will be on the order of 10^8 or 10^9 values for each. The functions are pretty smooth, so I don't think I'll lose much accuracy by only ...
[ "I agree with @katriealex's comment: ask someone w/ a strong statistics background.\nYou could easily evaluate min/max/mean/std deviation w/o needing to store any significant amount of memory. (note for mean + std deviation: use Knuth's technique:\ndelta = x - m[n-1]\nm[n] = m[n-1] + 1/n * delta\nS[n] = S[n-1] + (...
[ 2 ]
[]
[]
[ "bioinformatics", "optimization", "python", "statistics" ]
stackoverflow_0004261817_bioinformatics_optimization_python_statistics.txt
Q: python process._sbootstrap() / .start() How does python's multiprocessing.Process's start() method work. In particular, is there any documentation for Process._bootstrap() & if so where? A: I'm not sure you need to mess with _bootstrap. If you are looking for a basic idea on how to use the Process class, I woul...
python process._sbootstrap() / .start()
How does python's multiprocessing.Process's start() method work. In particular, is there any documentation for Process._bootstrap() & if so where?
[ "I'm not sure you need to mess with _bootstrap. If you are looking for a basic idea on how to use the Process class, I would take a look at:\n\nhttp://pymotw.com/2/multiprocessing/basics.html\nhttp://pymotw.com/2/multiprocessing/communication.html\n\n", "Here's the code, straight from my Python 2.7 install:\ndef...
[ 0, 0 ]
[]
[]
[ "bootstrapping", "multiprocessing", "process", "python" ]
stackoverflow_0004260912_bootstrapping_multiprocessing_process_python.txt
Q: CoreGraphics not found by Python on Mac OS I'm trying to run some of the Quartz demos in /Developer/Examples/Quartz/Python with Mac 10.5.8 and Python 2.6. However, I'm getting errors that CoreGraphics isn't found. Traceback (most recent call last): File "circle.py", line 38, in <module> from CoreGraphics imp...
CoreGraphics not found by Python on Mac OS
I'm trying to run some of the Quartz demos in /Developer/Examples/Quartz/Python with Mac 10.5.8 and Python 2.6. However, I'm getting errors that CoreGraphics isn't found. Traceback (most recent call last): File "circle.py", line 38, in <module> from CoreGraphics import * ImportError: No module named CoreGraphics ...
[ "The CoreGraphics wrapper is supplied by Apple as part of the Apple-supplied Python in OS X. Since in OS X 10.5 there is no Apple-supplied version of Python 2.6 (Apple supplies 2.5 and 2.3 there), you must be using a non-Apple version, possibly from a python.org installer or MacPorts. They will not have this modu...
[ 4 ]
[]
[]
[ "macos", "operating_system", "python", "quartz_graphics" ]
stackoverflow_0004261877_macos_operating_system_python_quartz_graphics.txt
Q: App Engine: CPU Over Quota on urlfetch() Hey. I'm quite new to App Engine. I created a web-based Twitter app which is now running on App Engine and I'm constantly hitting my CPU Over Quota limits. I did a little profiling and I found out that every request consists of two urlfetch queries, each one of which takes ...
App Engine: CPU Over Quota on urlfetch()
Hey. I'm quite new to App Engine. I created a web-based Twitter app which is now running on App Engine and I'm constantly hitting my CPU Over Quota limits. I did a little profiling and I found out that every request consists of two urlfetch queries, each one of which takes up to 2 CPU seconds. That time is probably spe...
[ "I would find it confusing that time spent in urlfetch to wait for a remote response is counted towards your CPU quota, given that there is no CPU time spent.\nBut assuming that's really the problem, asynchronous requests may be your solution. At a minimum, you can overlap the two urlfetch requests to proceed simul...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004256767_google_app_engine_python.txt
Q: What does the <> operator do in python? I just came across this here, always used like this: if string1.find(string2) <> -1: pass What does the <> operator do, and why not use the usual == or in? Sorry if that has been answered before, search engines don't like punctuation. A: http://docs.python.org/refer...
What does the <> operator do in python?
I just came across this here, always used like this: if string1.find(string2) <> -1: pass What does the <> operator do, and why not use the usual == or in? Sorry if that has been answered before, search engines don't like punctuation.
[ "http://docs.python.org/reference/expressions.html#notin says:\n\nThe [operators] <> and != are equivalent; for consistency with C, != is preferred. [...] The <> spelling is considered obsolescent.\n\n", "<> is the same as != although the <> form is deprecated. Your code sample could be more cleanly be written a...
[ 17, 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004262638_python.txt
Q: what is making try: exit early? in the following function, what is making try: exit early? If I put the same code outside a def block it works fine. tiles = ['095D', '094M'] in_file = 'in_file' out_file = 'out_file' expression = ''' "FIELDNAME" LIKE 'STUFF' ''' def foobar(in_file, out_file, expression): print...
what is making try: exit early?
in the following function, what is making try: exit early? If I put the same code outside a def block it works fine. tiles = ['095D', '094M'] in_file = 'in_file' out_file = 'out_file' expression = ''' "FIELDNAME" LIKE 'STUFF' ''' def foobar(in_file, out_file, expression): print in_file, out_file, expression tr...
[ "The reason it's not working is because you defined tiles in the global scope. In the function you're assigning to tiles. This makes tiles a local scoped name in the function. This, in turn, means that the code in the function won't look for tiles in the global scope at all.\nIn the assignment, you're trying to get...
[ 3, 3 ]
[ "That's an interesting bug you have. So there's a module-scoped tiles outside the function, and since you're not using global, you're creating a new tiles variable inside the function. This is fine. Or it would be fine, except that it appears (when I mess around in interactive Python) that the lvalue of the stateme...
[ -1 ]
[ "python" ]
stackoverflow_0004262609_python.txt
Q: Segmentation Fault (segfault) when using OGR CreateField() in Python Receiving a segfault when running this very short script in Ubuntu. from osgeo import ogr, osr shpfile = 'Census_County_TIGER00_IN.shp' def cust_field(field): '''cust_field(shpfile, field) creates a field definition, which, by calling cust_...
Segmentation Fault (segfault) when using OGR CreateField() in Python
Receiving a segfault when running this very short script in Ubuntu. from osgeo import ogr, osr shpfile = 'Census_County_TIGER00_IN.shp' def cust_field(field): '''cust_field(shpfile, field) creates a field definition, which, by calling cust_field(), can be used to create a field using the CreateField() function. ...
[ "\nIs this an error on my end or an issue\n with the underlying C that I'm not\n addressing properly?\n\nIt is probably both. GDAL/OGR's bindings do tend to segfault occasionally, when objects go out of scope and are garbage collected. While this is a known bug, it is unlikely to be fixed any time soon.\nChances...
[ 5 ]
[]
[]
[ "osgeo", "python" ]
stackoverflow_0004262411_osgeo_python.txt
Q: Looking for cross-platform rsync-like functionality in python, such as rsync.py I am implementing backup scripts in python. I'm trying to keep things cross platform. I hear there is a python based rsync implementation: http://pypi.python.org/pypi/rsync.py But I can't seem to find it anywhere. All of the download l...
Looking for cross-platform rsync-like functionality in python, such as rsync.py
I am implementing backup scripts in python. I'm trying to keep things cross platform. I hear there is a python based rsync implementation: http://pypi.python.org/pypi/rsync.py But I can't seem to find it anywhere. All of the download links I find are dead. Does anyone know where I could find the rsync.py program? At th...
[ "Alternative : pysync - implementation of the rsync and related algorithms in pure Python, and a high speed librsync Python extension\n\nhttp://freshmeat.net/projects/pysync/\n\nAnother alternative: http://code.google.com/p/pyrsync/\n", "Here is the algorythm (not sure if it helps you out):\nhttp://code.activesta...
[ 14, 3, 1, 0 ]
[]
[]
[ "mirroring", "python", "rsync", "scripting" ]
stackoverflow_0004260767_mirroring_python_rsync_scripting.txt
Q: Django ModelForm CheckBox Widget I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I ha...
Django ModelForm CheckBox Widget
I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so: # Type of ...
[ "In such a case, the easiest way is to put the choices into a separate model and then use a ManyToMany relationship. After that, you simply override the ModelForm's widget for that field to use forms.CheckboxSelectMultiple and Django will automatically do the right thing. If you insist to use a CharField, you'll pr...
[ 16, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0001268209_django_django_forms_django_models_python.txt
Q: Install Python 3.1 on Mac OS X version 10.5.8 I use Windows. I wrote a Python 3.1 script that my Mac-using friend would like to run, but we can't get Python 3.1 to work right on his Mac. I think the problem is that the Python 3.1 framework is not being installed. Here's exactly what what I did and why I think this...
Install Python 3.1 on Mac OS X version 10.5.8
I use Windows. I wrote a Python 3.1 script that my Mac-using friend would like to run, but we can't get Python 3.1 to work right on his Mac. I think the problem is that the Python 3.1 framework is not being installed. Here's exactly what what I did and why I think this is the problem. I downloaded Python 3.1.2 from the...
[ "Take a look at PythonBrew. It made installing Python on my Mac a lot easier.\nAlso this might help:\nIs there a Python Equivalent of Ruby's RVM?\n", "Python Launcher.app is a somewhat neglected app; there have been some discussion about removing it all together because it could be somewhat of a security risk if ...
[ 2, 1, 0 ]
[]
[]
[ "installation", "macos", "python" ]
stackoverflow_0004261429_installation_macos_python.txt
Q: Is it possible to have a Python class decorator with arguments? What I'd like to do is this: @add_cache(cache_this, cache_that, cache_this_and_that) class MyDjangoModel(models.Model): blah But fails because it seems that the first argument is implicitly the actual class object. Is it possible to get around th...
Is it possible to have a Python class decorator with arguments?
What I'd like to do is this: @add_cache(cache_this, cache_that, cache_this_and_that) class MyDjangoModel(models.Model): blah But fails because it seems that the first argument is implicitly the actual class object. Is it possible to get around this or am I forced to use the ugly syntax as opposed to this beautiful...
[ "Your arg_cache definition needs to do something like:\ndef arg_cache(cthis, cthat, cthisandthat):\n def f(obj):\n obj.cache_this = cthis\n obj.cache_that = cthat\n obj.thisandthat = cthisandthat\n return obj\n return f\n\n@arg_cache(cache_this, cache_that, cache_this_and_that)\n...\n\nT...
[ 10, 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0004262892_decorator_python.txt
Q: Keeping in-memory data in sync with a file for long running Python script I have a Python (2.7) script that acts as a server and it will therefore run for very long periods of time. This script has a bunch of values to keep track of which can change at any time based on client input. What I'm ideally after is some...
Keeping in-memory data in sync with a file for long running Python script
I have a Python (2.7) script that acts as a server and it will therefore run for very long periods of time. This script has a bunch of values to keep track of which can change at any time based on client input. What I'm ideally after is something that can keep a Python data structure (with values of types dict, list, u...
[ "Well, since you know we're basically talking about a database, albeit a very simple one, you probably won't be surprised that I suggest you have a look at the sqlite3 module.\n", "Any reason for the human readable requirement?\nI would suggest looking at sqlite for a simple database solution, or at pickle for a ...
[ 5, 2, 2, 1, 0 ]
[]
[]
[ "database", "file", "memory", "python", "python_2.7" ]
stackoverflow_0004262403_database_file_memory_python_python_2.7.txt
Q: Running Django tutorial example with mod_wsgi? I installed wsgi (mod_wsgi), and could run the simple application by calling http://localhost/myapp. WSGIScriptAlias /myapp /Library/WebServer/Documents/wsgi/scripts/myapp.wsgi def application(environ, start_response): status = '200 OK' output = 'Hello Worl...
Running Django tutorial example with mod_wsgi?
I installed wsgi (mod_wsgi), and could run the simple application by calling http://localhost/myapp. WSGIScriptAlias /myapp /Library/WebServer/Documents/wsgi/scripts/myapp.wsgi def application(environ, start_response): status = '200 OK' output = 'Hello World! WSGI working perfectly!' response_headers = ...
[ "What you need to do is add either the project directory or the directory the project is in to sys.path, and then point the settings to mysite.settings if you've done the latter.\nEDIT:\n\"Django settings\"\nEDIT 2:\nHow to set the Django settings module\nEDIT 3:\nThe settings module should be the module, not the f...
[ 2 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0004263001_django_mod_wsgi_python.txt
Q: Recording Video with FFmpeg gives "The filename, directory name, or volume label syntax is incorrect." I'm trying to record video (with audio!) in this way: ffmpeg = "C:\bin\ffmpeg.exe" cmd = '%s -r 15 -f vfwcap -i 0 c:/output2.mpg' % (ffmpeg) os.system(cmd) And I have the error: "The filename, directory name, or...
Recording Video with FFmpeg gives "The filename, directory name, or volume label syntax is incorrect."
I'm trying to record video (with audio!) in this way: ffmpeg = "C:\bin\ffmpeg.exe" cmd = '%s -r 15 -f vfwcap -i 0 c:/output2.mpg' % (ffmpeg) os.system(cmd) And I have the error: "The filename, directory name, or volume label syntax is incorrect." I think that this is a problem with vfwcap, but I don't know how to fix ...
[ "I think mermoz must be joking with you. You've got a few problems here. Python uses '\\' as an escape character, so it won't find your file unless you either double them up or switch to forward slashes, as you've then done in your cmd. The syntax of your ffmpeg command line is also completely wrong. You're say...
[ 1, 0, 0 ]
[]
[]
[ "ffmpeg", "python", "video_streaming" ]
stackoverflow_0003372820_ffmpeg_python_video_streaming.txt
Q: GAE email me errors Can GAE be configured to bust me an email when there's an error? A: I think the best you can do is to have in your main function some code like...: try: ...normal body of your main goes here... except: from google.appengine.api import mail import sys mail.send_mail(sender="Your GAE A...
GAE email me errors
Can GAE be configured to bust me an email when there's an error?
[ "I think the best you can do is to have in your main function some code like...:\ntry:\n ...normal body of your main goes here...\nexcept:\n from google.appengine.api import mail\n import sys\n\n mail.send_mail(sender=\"Your GAE App <yourappname@example.com>\",\n to=\"You <bobobobo@example.com>\",\...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002118524_google_app_engine_python.txt
Q: Google App Engine: Intro to their Data Store API for people with SQL Background? Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectiv...
Google App Engine: Intro to their Data Store API for people with SQL Background?
Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively. For Example, if you have a self created Users Table and a Message Table Where the...
[ "Here is a good link: One to Many Join using Google App Engine.\nhttp://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html\nHere is another good link: Many to Many Join using Google App Engine:\nhttp://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html\nHere is a good discussion...
[ 13, 2, 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "gql", "python", "sql" ]
stackoverflow_0000739490_google_app_engine_gql_python_sql.txt
Q: Screen Scraping in Python I am currently trying to screen scrape a website to put info into a dictionary. I am using urllib2 and BeautifulSoup. I cannot figure out how to parse the web pages source info to get what I want and to read it into a dictionary. The info I want is displayed as <title>Nov 24 | 8:00AM | So...
Screen Scraping in Python
I am currently trying to screen scrape a website to put info into a dictionary. I am using urllib2 and BeautifulSoup. I cannot figure out how to parse the web pages source info to get what I want and to read it into a dictionary. The info I want is displayed as <title>Nov 24 | 8:00AM | Sole In. Peace Out. </title> in t...
[ "Something like this..\ntitletext = soup.findAll('title')[1].string #assuming it's the second title element.. I've seen worse in html\nimport datetime\ndatetext = titletext.split(\"|\")[0]\ntitle = titletext.split(\"|\")[2]\ndate = datetime.datetime.strptime(datetext,\"%b %d\").replace(year=2010)\nthe_final_dict = ...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex", "screen_scraping" ]
stackoverflow_0004263310_python_regex_screen_scraping.txt
Q: Django modeling problem, need a subset of foreign key field I intend to create an app for categories which will have separate category sets (vocabularies) for pages, gallery, product types etc. So there will need to be two models, vocabulary and category. The categories/models.py code might be something like this:...
Django modeling problem, need a subset of foreign key field
I intend to create an app for categories which will have separate category sets (vocabularies) for pages, gallery, product types etc. So there will need to be two models, vocabulary and category. The categories/models.py code might be something like this: class Vocabulary(models.Model): title = models.CharField() ...
[ "Filtering of selection like this is done in the form using a queryset, or in the admin interface with limit_choices_to.\n" ]
[ 7 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004263421_django_django_models_python.txt
Q: Unexpected Indent error in Python I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't. def gen_fibs(): a, b = 0, 1 while True: a, b = b, ...
Unexpected Indent error in Python
I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't. def gen_fibs(): a, b = 0, 1 while True: a, b = b, a + b if len(str(a)) == 1000: ...
[ "If you just copy+pasted your code, then you used a tab on the line with the if statement. Python interprets a tab as 8 spaces and not 4. Don't ever use tabs with python1 :)\n1 Or at least don't ever use tabs and spaces mixed. It's highly advisable to use 4 spaces for consistency with the rest of the python univers...
[ 13, 4, 1, 1 ]
[ "Check whether your whitespace in front of every line is correctly typed. You may have typed tabs instead of spaces - try deleting all the space and change it so you use only tabs or only spaces.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0004263485_python.txt
Q: question about postgresql bind variables I was looking at the question and decided to try using the bind variables. I use sql = 'insert into abc2 (interfield,textfield) values (%s,%s)' a = time.time() for i in range(10000): #just a wrapper around cursor.execute db.executeUpdateCommand(sql,(i,'test')) db.c...
question about postgresql bind variables
I was looking at the question and decided to try using the bind variables. I use sql = 'insert into abc2 (interfield,textfield) values (%s,%s)' a = time.time() for i in range(10000): #just a wrapper around cursor.execute db.executeUpdateCommand(sql,(i,'test')) db.commit() and sql = 'insert into abc2 (intfiel...
[ "The queries are equivalent in Postgresql.\nBind is oracle lingo. When you use it will save the query plan so the next execution will be a little faster. prepare does the same thing in Postgres.\nhttp://www.postgresql.org/docs/current/static/sql-prepare.html\npsycopg2 supports an internal 'bind', not prepare with c...
[ 10, 7, 3 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0004263508_postgresql_psycopg2_python.txt
Q: How do I perform frequently file reading/writing operations(multi-thread) in python? Here's my problem: I need to perform frequently reading/writing operations to one file via different threads, and I tend to use threading.RLock().acquire() and threading.RLock().release() to lock the resource(e.g., one txt file). ...
How do I perform frequently file reading/writing operations(multi-thread) in python?
Here's my problem: I need to perform frequently reading/writing operations to one file via different threads, and I tend to use threading.RLock().acquire() and threading.RLock().release() to lock the resource(e.g., one txt file). The thing is, you can easily do file writing operations in a certain thread, how do you ge...
[ "You should use some variable accessible both to the worker thread and to the main thread. \nFor example, worker thread can get as an input a reference to some object and fill it when done. Main thread will wait workers threads to finish, then will check the objects.\n" ]
[ 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004263562_file_io_python.txt
Q: Chopping media stream in HTML5 websocket server for webbased chat/video conference application We are currently working on a chat + (file sharing +) video conference application using HTML5 websockets. To make our application more accessible we want to implement Adaptive Streaming, using the following sequence: R...
Chopping media stream in HTML5 websocket server for webbased chat/video conference application
We are currently working on a chat + (file sharing +) video conference application using HTML5 websockets. To make our application more accessible we want to implement Adaptive Streaming, using the following sequence: Raw audio/video data client goes to server Stream is split into 1 second chunks Encode stream into va...
[ "I think ffmpeg is the main tool you'll want to look at. It's become most well supported open source media manipulator. There is a python wrapper for it. Though it is also possible to access the command line through the subprocess module.\n", "I've found some nice articles about how other people build a stream...
[ 5, 2 ]
[]
[]
[ "html", "python", "split", "stream" ]
stackoverflow_0004242081_html_python_split_stream.txt
Q: How to see generated source from an URL page with python script and not anly source? I have some url to parse, and they used some javascript to create it dynamicly. So if i want to parse the result generated page with python... how can i do that ? Firefox do that well with web developer... so i think it possible ....
How to see generated source from an URL page with python script and not anly source?
I have some url to parse, and they used some javascript to create it dynamicly. So if i want to parse the result generated page with python... how can i do that ? Firefox do that well with web developer... so i think it possible ... but i don't know where to start... Thx for help lo
[ "I've done this by doing a POST of document.body.innerHTML, after the page is loaded, to a CGI script in Python.\nFor the parsing, BeautifulSoup is a good choice.\n", "I you want generated source you'll need a browser, I don't think you can with only python.\n" ]
[ 2, 0 ]
[]
[]
[ "dynamically_generated", "javascript", "parsing", "python", "url" ]
stackoverflow_0004264076_dynamically_generated_javascript_parsing_python_url.txt
Q: Gmail SMTP + XOAuth mystery I am using python smtplib and xoauth and I am trying to send an email. I am using the code posted by Google: http://code.google.com/p/google-mail-xoauth-tools/source/browse/trunk/python/xoauth.py I am actually authenticating against Gmail and i get this reply reply: '235 2.7.0 Accepted\...
Gmail SMTP + XOAuth mystery
I am using python smtplib and xoauth and I am trying to send an email. I am using the code posted by Google: http://code.google.com/p/google-mail-xoauth-tools/source/browse/trunk/python/xoauth.py I am actually authenticating against Gmail and i get this reply reply: '235 2.7.0 Accepted\r\n' after sending my XOAuth str...
[ "The problem is on how you do the SMTP connection here is a snippet from my code:\n smtp_conn = smtplib.SMTP('smtp.googlemail.com', 587)\n #smtp_conn.set_debuglevel(True)\n smtp_conn.ehlo()\n smtp_conn.starttls()\n smtp_conn.ehlo()\n smtp_conn.docmd('AUTH', 'XOAUTH ' + base64.b64encode(xoauth_stri...
[ 3 ]
[]
[]
[ "gmail", "oauth", "python", "smtplib" ]
stackoverflow_0003347731_gmail_oauth_python_smtplib.txt
Q: It is possible export table sqlite3 table to csv or similiar? It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3. A: I knocked this very basic script together using a slightly modified example class from the docs; it simply exports an entire table to a CSV file: import sq...
It is possible export table sqlite3 table to csv or similiar?
It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3.
[ "I knocked this very basic script together using a slightly modified example class from the docs; it simply exports an entire table to a CSV file:\nimport sqlite3\nimport csv, codecs, cStringIO\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\", \n which is encoded in t...
[ 9, 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004264379_python_sqlite.txt
Q: How to use pipes in python without blocking? In python, I want to create a subprocess and read and write data to its stdio. Lets say I have the following C program that just writes its input to its output. #include <stdio.h> int main() { char c; for(;;) { scanf("%c", &c); printf("%c", c); ...
How to use pipes in python without blocking?
In python, I want to create a subprocess and read and write data to its stdio. Lets say I have the following C program that just writes its input to its output. #include <stdio.h> int main() { char c; for(;;) { scanf("%c", &c); printf("%c", c); } } In python I should be able to use this usi...
[ "stdout is line-buffered when writing to a terminal, but fully buffered when writing to a pipe so your output isn't being seen immediately.\nTo flush the buffer, call fflush(stdout); after each printf(). See also this question which is the same except that your subprocess is written in C, and this question which re...
[ 4, 0 ]
[]
[]
[ "pipe", "popen", "python", "subprocess" ]
stackoverflow_0004264576_pipe_popen_python_subprocess.txt
Q: assign a retrievable unique ID to a changing lambda list in python? def a(p): return p + 1 def b(p): return p + 2 def c(p): return p + 3 l= [a,b,c] import itertools ll = itertools.combinations(l, 2) [x for x in ll] [(<function a at 0x00CBD770>, <function b at 0x00CBD7F0>), (<function a at 0x00CBD770>, <funct...
assign a retrievable unique ID to a changing lambda list in python?
def a(p): return p + 1 def b(p): return p + 2 def c(p): return p + 3 l= [a,b,c] import itertools ll = itertools.combinations(l, 2) [x for x in ll] [(<function a at 0x00CBD770>, <function b at 0x00CBD7F0>), (<function a at 0x00CBD770>, <function c at 0x00BB27F0>), (<function b at 0x00CBD7F0>, <function c at 0x00B...
[ "just use set to avoid dicts?\nThey are works for me.\n" ]
[ 0 ]
[]
[]
[ "lambda", "python", "uniqueidentifier" ]
stackoverflow_0004264136_lambda_python_uniqueidentifier.txt
Q: Check whether the process is being run as a pipe I have a small Python utility which should be run only as a pipe. I want it to print out the help message when it runs stand alone. How can a process know whether it is being used as a pipe. Comparing sys.stdin and sys.__stdin__ does not work. A: You can use isatt...
Check whether the process is being run as a pipe
I have a small Python utility which should be run only as a pipe. I want it to print out the help message when it runs stand alone. How can a process know whether it is being used as a pipe. Comparing sys.stdin and sys.__stdin__ does not work.
[ "You can use isatty:\nif sys.stdin.isatty():\n\nIt will be True if standard input is a tty, which roughly means it's being used directly, outside a pipe.\n" ]
[ 16 ]
[]
[]
[ "pipe", "process", "python", "stdio" ]
stackoverflow_0004265057_pipe_process_python_stdio.txt
Q: Python Django Forms Multiple Select HTML Ouput I'm trying to output the description field from my model in a django form without joy. After searching around and not finding what I need I hope I can ask here. Here is my models, form, template and template output. I've abrieviated to help make this post concise. I'm...
Python Django Forms Multiple Select HTML Ouput
I'm trying to output the description field from my model in a django form without joy. After searching around and not finding what I need I hope I can ask here. Here is my models, form, template and template output. I've abrieviated to help make this post concise. I'm working on the view in this project so the model ha...
[ "The easiest way to do this is to change the __unicode__ method of the Share model to return description instead of location, but since you say you can't change the model you will need to subclass ModelMultipleChoiceField and override the label_from_instance method.\nclass MyModelMultipleChoiceField(forms.ModelMul...
[ 1 ]
[]
[]
[ "django_forms", "python" ]
stackoverflow_0004265003_django_forms_python.txt
Q: Prompt user to save my desired text file name I wish when the user clicks on a link say. http://www.xyz.com/dynamic-text.py The browser will prompt user to save the text file. The following script will make browser to prompt user to save dynamic-text.py. I wish to prompt user to save some-file-name.txt. How can I ...
Prompt user to save my desired text file name
I wish when the user clicks on a link say. http://www.xyz.com/dynamic-text.py The browser will prompt user to save the text file. The following script will make browser to prompt user to save dynamic-text.py. I wish to prompt user to save some-file-name.txt. How can I do so? dynamic-text.py #!c:/Python27/python.exe -u...
[ "You can send the Content-Disposition HTTP header:\nprint \"Content-Type: text/plain\"\nprint \"Content-Disposition: attachment; filename=some-file-name.txt\"\nprint\n\nAlso note that you should use the text/plain content type instead of text/text which, to my knowledge, doesn't exist.\n" ]
[ 4 ]
[]
[]
[ "html", "http", "python" ]
stackoverflow_0004265381_html_http_python.txt
Q: Create a symlink to a programme Suppose I am in ~/programming/ass1 and the executable is in ~/programming/ass1/seattle/seattle_repy/repy.py. I tried to create a symlink like so ln -s seattle/seattle_repy/repy.py repy to be able to type python repy restrictions.test example.1.1.repy instead of python seattle/seat...
Create a symlink to a programme
Suppose I am in ~/programming/ass1 and the executable is in ~/programming/ass1/seattle/seattle_repy/repy.py. I tried to create a symlink like so ln -s seattle/seattle_repy/repy.py repy to be able to type python repy restrictions.test example.1.1.repy instead of python seattle/seattle_repy/repy.py restrictions.test ex...
[ "You'll need to frob sys.path to add the path containing the modules, but it's probably easier to make a shell script that calls exec python ~/programming/ass1/seattle/seattle_repy/repy.py.\n", "Thanks for the tips Ignacio and Mark.\nI solved it with the following bash script in ~/programming/ass1\n\n#!/bin/bash\...
[ 1, 0 ]
[]
[]
[ "python", "symlink" ]
stackoverflow_0004265624_python_symlink.txt
Q: How to include Non-AscII character in python appengine send html mail My problem is that I want to compose an email in python environment of google appengine. When I add Greek characters to the body of my message I get: SyntaxError: Non-ASCII character '\xce' megssage.html = """ <html> <body> παραδειγμα </bod...
How to include Non-AscII character in python appengine send html mail
My problem is that I want to compose an email in python environment of google appengine. When I add Greek characters to the body of my message I get: SyntaxError: Non-ASCII character '\xce' megssage.html = """ <html> <body> παραδειγμα </body> </html>"""
[ "Use this shebang:\n# -*- coding: utf-8 -*-\n\n" ]
[ 3 ]
[]
[]
[ "email", "google_app_engine", "html", "python" ]
stackoverflow_0004265747_email_google_app_engine_html_python.txt
Q: Set editable=False only in subclass I have a field "name" that is automatically constructed from "first_name" and "last_name" in one of the subclasses: from django.db import models from django.utils.translation import ugettext_lazy as _ class Actor(models.Model): name = models.CharField(_('name'), max_length=...
Set editable=False only in subclass
I have a field "name" that is automatically constructed from "first_name" and "last_name" in one of the subclasses: from django.db import models from django.utils.translation import ugettext_lazy as _ class Actor(models.Model): name = models.CharField(_('name'), max_length=60) class Company(Actor): pass clas...
[ "Forget about editable and exclude the field in the model's ModelAdmin instead:\nfrom django.contrib import admin\n\nadmin.site.register(Person, exclude=['name'])\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004266247_django_python.txt
Q: How can I dump raw XML of my request and server's response using suds in python i'm using suds 0.4 and python 2.6, to communicate with remote server. It's WSDL loads perfectly, but any function call returns error. Something is wrong with that server. Now i need to get a dump of soap structure, that is sent to serv...
How can I dump raw XML of my request and server's response using suds in python
i'm using suds 0.4 and python 2.6, to communicate with remote server. It's WSDL loads perfectly, but any function call returns error. Something is wrong with that server. Now i need to get a dump of soap structure, that is sent to server and it's response, in pure soap either. How can i do that?
[ "Setting the logging for suds.transport to debug will get you the sent and received messages.\nFor an interactive session, I find this is good:\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger('suds.client').setLevel(logging.DEBUG)\nlogging.getLogger('suds.transport').setLevel(logging.DEB...
[ 14 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0004265602_python_soap_suds.txt
Q: Check if a number is rational in Python, for a given fp accuracy I would like to know a good way of checking if a number x is a rational (two integers n,m exist so that x=n/m) in python. In Mathematica, this is done by the function Rationalize[6.75] : 27/4 I assume this question has an answer for a given accuracy....
Check if a number is rational in Python, for a given fp accuracy
I would like to know a good way of checking if a number x is a rational (two integers n,m exist so that x=n/m) in python. In Mathematica, this is done by the function Rationalize[6.75] : 27/4 I assume this question has an answer for a given accuracy. Is there a common algorithm of obtaining these two integers?
[ "In python >= 2.6 there is a as_integer_ratio method on floats:\n>>> a = 6.75\n>>> a.as_integer_ratio()\n(27, 4)\n>>> import math\n>>> math.pi.as_integer_ratio()\n(884279719003555, 281474976710656)\n\nHowever, due to the way floats are defined in programming languages there are no irrational numbers.\n", "The nat...
[ 20, 10, 7, 5, 4, 1, 0 ]
[]
[]
[ "algorithm", "floating_accuracy", "floating_point", "math", "python" ]
stackoverflow_0004266741_algorithm_floating_accuracy_floating_point_math_python.txt
Q: Why is int(50)<str(5) in python 2.x? In python 3, int(50)<'2' causes a TypeError, and well it should. In python 2.x, however, int(50)<'2' returns True (this is also the case for other number formats, but int exists in both py2 and py3). My question, then, has several parts: Why does Python 2.x (< 3?) allow this...
Why is int(50)<str(5) in python 2.x?
In python 3, int(50)<'2' causes a TypeError, and well it should. In python 2.x, however, int(50)<'2' returns True (this is also the case for other number formats, but int exists in both py2 and py3). My question, then, has several parts: Why does Python 2.x (< 3?) allow this behavior? (And who thought it was a good...
[ "It works like this1.\n>>> float() == long() == int() < dict() < list() < str() < tuple()\nTrue\n\nNumbers compare as less than containers. Numeric types are converted to a common type and compared based on their numeric value. Containers are compared by the alphabetic value of their names.2\nFrom the docs:\n\nCPyt...
[ 8, 6, 1, 1 ]
[]
[]
[ "comparison", "int", "python", "python_2.x", "string" ]
stackoverflow_0004266918_comparison_int_python_python_2.x_string.txt
Q: Does ruby have a zip function like python's? I am a newibe from python to ruby. In python there is a feature like the following: a=range(3) b=range(3) for e1,e2 in zip(a,b) print e1,e2 Is there something that can achieve the same function in ruby? A: That is what Array#zip does: foo = [1,2,3,4] bar = ['a','...
Does ruby have a zip function like python's?
I am a newibe from python to ruby. In python there is a feature like the following: a=range(3) b=range(3) for e1,e2 in zip(a,b) print e1,e2 Is there something that can achieve the same function in ruby?
[ "That is what Array#zip does:\nfoo = [1,2,3,4]\nbar = ['a','b','c','d']\n\nfoo.zip(bar) #=> [[1, \"a\"], [2, \"b\"], [3, \"c\"], [4, \"d\"]]\n\n", "You mean, like Array#zip?\n" ]
[ 7, 0 ]
[]
[]
[ "arrays", "python", "ruby" ]
stackoverflow_0004267206_arrays_python_ruby.txt
Q: Replace a client library with a mock from a test? Is there a way to replace a client library (which communicates with a remote server) with a mock object from within a unittest? Here's a diagram to explain what I'm attempting to do +---------------+ | tests |----{ mock } +---------------+ ...
Replace a client library with a mock from a test?
Is there a way to replace a client library (which communicates with a remote server) with a mock object from within a unittest? Here's a diagram to explain what I'm attempting to do +---------------+ | tests |----{ mock } +---------------+ | | | v ...
[ "If model.py does an\nimport client_module\n\nand doesn't use any features of it at import time, you can do\nimport model\n\n...\n\nmodel.client_module = MyMockModule()\n\nwhere MyMockModule returns suitable mocks for stuff the real client_module provides. I haven't shown setUp/tearDown stuff to take care of this, ...
[ 1 ]
[]
[]
[ "nose", "python", "unit_testing" ]
stackoverflow_0004267007_nose_python_unit_testing.txt
Q: wxPython display a login box I'm trying to build a small application in wxPython (absolute beginner) in which I display a login box before showing the content. I created a frame, inside the frame a panel with a flexigrid to put the login form inside but it doesn't show. If I launch the application the login form i...
wxPython display a login box
I'm trying to build a small application in wxPython (absolute beginner) in which I display a login box before showing the content. I created a frame, inside the frame a panel with a flexigrid to put the login form inside but it doesn't show. If I launch the application the login form is invisible. If I resize the appli...
[ "I just discovered I'm calling frame.Show() too soon. :)\n" ]
[ 4 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004267651_python_wxpython.txt
Q: How to determine whether an object is a sequence I can think of two ways to determine whether an object is a sequence: hasattr(object, '__iter__'). And whether calling iter(object) raises a TypeError. As it is most Pythonic to ask forgiveness than to ask permission, I'd use the second idiom, although I consider ...
How to determine whether an object is a sequence
I can think of two ways to determine whether an object is a sequence: hasattr(object, '__iter__'). And whether calling iter(object) raises a TypeError. As it is most Pythonic to ask forgiveness than to ask permission, I'd use the second idiom, although I consider it more ugly (additionally, raising an exception once ...
[ "Use isinstance(obj, collections.Sequence). Abstract base classes are exactly for this. They didn't exist prior to 2.6 though. In case you're forced to use older versions, you're out of luck and better stick with EAFP.\n" ]
[ 4 ]
[]
[]
[ "collections", "python", "python_3.x" ]
stackoverflow_0004267909_collections_python_python_3.x.txt
Q: urllib2 not retrieving entire HTTP response I'm perplexed as to why I'm not able to download the entire contents of some JSON responses from FriendFeed using urllib2. >>> import urllib2 >>> stream = urllib2.urlopen('http://friendfeed.com/api/room/the-life-scientists/profile?format=json') >>> stream.headers['conten...
urllib2 not retrieving entire HTTP response
I'm perplexed as to why I'm not able to download the entire contents of some JSON responses from FriendFeed using urllib2. >>> import urllib2 >>> stream = urllib2.urlopen('http://friendfeed.com/api/room/the-life-scientists/profile?format=json') >>> stream.headers['content-length'] '168928' >>> data = stream.read() >>> ...
[ "Best way to get all of the data:\nfp = urllib2.urlopen(\"http://www.example.com/index.cfm\")\n\nresponse = \"\"\nwhile 1:\n data = fp.read()\n if not data: # This might need to be if data == \"\": -- can't remember\n break\n response += data\n\nprint response\n\nThe reason is that .rea...
[ 18, 4, 2, 0 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0001824069_http_python_urllib2.txt
Q: How to get Phone Number from Latitude & Longitude I have a bunch of restaurants in an Excel. All these restaurants have Lat/Long co-ordinates. Sadly in this Excel their phone number is missing. If I want to book a reservation at a particular restaurant, I'll have to find out manually. Is there some service which ...
How to get Phone Number from Latitude & Longitude
I have a bunch of restaurants in an Excel. All these restaurants have Lat/Long co-ordinates. Sadly in this Excel their phone number is missing. If I want to book a reservation at a particular restaurant, I'll have to find out manually. Is there some service which legally allows me to return the address along with phon...
[ "Getting the address of a lat/lon pair is called reverse geocoding, and there are websites who can give an address. For example the webservice at geonames.org is offering this. I don't know the possibilities with google maps. But this blogpost says it is possible.\nBut you won't get a phone number this way. \n", ...
[ 2, 2, 1 ]
[]
[]
[ "geocoding", "python", "reverse_geocoding" ]
stackoverflow_0004267788_geocoding_python_reverse_geocoding.txt
Q: How should I jump into the Flex-Python Boat http://www.artima.com/weblogs/viewpost.jsp?thread=208528 Bruce Eckel talked about using Flex and Python together. Since then, we have had PyAMF and the likes. It has been almost three years, but googling does not reveal much more than a bunch of articles/comments linking...
How should I jump into the Flex-Python Boat
http://www.artima.com/weblogs/viewpost.jsp?thread=208528 Bruce Eckel talked about using Flex and Python together. Since then, we have had PyAMF and the likes. It has been almost three years, but googling does not reveal much more than a bunch of articles/comments linking to that article above (or related ones). There i...
[ "An application written in Flex/Flash is server agnostic...and it should be easy to replace the server side language with another one. The client application will consume some web services exposed by the server(REST/SOAP), or it can use as an alternative remote method invocation. The last one is implemented for the...
[ 2 ]
[]
[]
[ "apache_flex", "pyamf", "python" ]
stackoverflow_0004266889_apache_flex_pyamf_python.txt
Q: retrieving the listening port during buildProtocol i'm modifying the ServerFactory's buildProtocol method, basically the factory listens in at port 11000 and 12000, and I have two protocols, one for port each port. I'm trying to retrieve the port that the client used to listen in so that I can instantiate the cor...
retrieving the listening port during buildProtocol
i'm modifying the ServerFactory's buildProtocol method, basically the factory listens in at port 11000 and 12000, and I have two protocols, one for port each port. I'm trying to retrieve the port that the client used to listen in so that I can instantiate the correct protocol. ex. client listens in at port 11000, pr...
[ "I think, you may need to use Twisted services:\nlink text\nYou code become something like:\nfrom twisted.application import internet, service\nfrom twisted.internet import protocol, reactor\nfrom twisted.protocols import basic\n\nclass UpperCaseProtocol(basic.LineReceiver):\n def lineReceived(self, line):\n ...
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0004251433_python_twisted.txt
Q: How do I use StandardAnalyzer with TermQuery? I'm trying to produce something similar to what QueryParser in lucene does, but without the parser, i.e. run a string through StandardAnalyzer, tokenize this and use TermQuery:s in a BooleanQuery to produce a query. My problem is that I only get Token:s from StandardAn...
How do I use StandardAnalyzer with TermQuery?
I'm trying to produce something similar to what QueryParser in lucene does, but without the parser, i.e. run a string through StandardAnalyzer, tokenize this and use TermQuery:s in a BooleanQuery to produce a query. My problem is that I only get Token:s from StandardAnalyzer, and not Term:s. I can convert a Token to a ...
[ "The established way to get the token text is with token.termText() - that API's been there forever.\nAnd yes, you'll need to specify a field name to both the Analyzer and the Term; I think that's considered normal. 8-)\n", "I've come across the same problem, and, using Lucene 2.9 API and Java, my code snippet l...
[ 2, 0 ]
[]
[]
[ "lucene", "pylucene", "python" ]
stackoverflow_0001390088_lucene_pylucene_python.txt
Q: how to generate various database dumps I have a CSV file and want to generate dumps of the data for sqlite, mysql, postgres, oracle, and mssql. Is there a common API (ideally Python based) to do this? I could use an ORM to insert the data into each database and then export dumps, however that would require install...
how to generate various database dumps
I have a CSV file and want to generate dumps of the data for sqlite, mysql, postgres, oracle, and mssql. Is there a common API (ideally Python based) to do this? I could use an ORM to insert the data into each database and then export dumps, however that would require installing each database. It also seems a waste of ...
[ "SQLAlchemy is a database library that (as well as ORM functionality) supports SQL generation in the dialects of the all the different databases you mention (and more).\nIn normal use, you could create a SQL expression / instruction (using a schema.Table object), create a database engine, and then bind the instruct...
[ 5, 1, 0 ]
[]
[]
[ "csv", "database", "mysqldump", "python" ]
stackoverflow_0004121658_csv_database_mysqldump_python.txt
Q: RabbitMQ / Celery with Django hangs on delay/ready/etc - No useful log info So I just setup celery and rabbitmq, created my user, setup the vhost, mapped the user to the vhost, and ran the celery daemon succesfully (or so I assume) (queuetest)corky@corky-server:~/projects/queuetest$ ./manage.py celeryd celery@cor...
RabbitMQ / Celery with Django hangs on delay/ready/etc - No useful log info
So I just setup celery and rabbitmq, created my user, setup the vhost, mapped the user to the vhost, and ran the celery daemon succesfully (or so I assume) (queuetest)corky@corky-server:~/projects/queuetest$ ./manage.py celeryd celery@corky-server v0.9.5 is starting. Configuration -> . broker -> amqp://celery@localho...
[ "I just fixed a really ugly bug that would only show up for new users that would have caused this. (http://github.com/ask/celery/commit/a9c1316b15055b67ee3c38d294461fa82ed6d2b5)\nPlease pull from the master branch at github. If it still doesn't work you \nprobably have to stop rabbitmq, remove the rabbitmq database...
[ 4, 2 ]
[]
[]
[ "celery", "django", "python", "rabbitmq" ]
stackoverflow_0002141083_celery_django_python_rabbitmq.txt
Q: Resolve variables from a string I have a string in the following form : "425x344" Now I'd like to resolve first and second numbers from this string as two separate variables. How can I do this ? I've created this regex: regex = re.compile(r"^(\d+x\d+)") to check if the string form is proper. But what next ? A: a...
Resolve variables from a string
I have a string in the following form : "425x344" Now I'd like to resolve first and second numbers from this string as two separate variables. How can I do this ? I've created this regex: regex = re.compile(r"^(\d+x\d+)") to check if the string form is proper. But what next ?
[ "a, b = '425x344'.split('x')\n", "Since you're filtering it with a regex, you can just do\na, b = map(int, s.split('x'))\nres = a * b\n\nIf you're planning on multiplying, it can be done in one line:\nres = eval(s.replace('x', '*'))\n\nor\nres = (lambda x, y: x * y)(*map(int, s.split('x')))\n\nWith an import and ...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "match", "python", "regex" ]
stackoverflow_0004268323_match_python_regex.txt
Q: Gtk loop or Cron for timer Well, I have created a python script, which checks the number of uncompleted tasks of tasque and displays it using pynotify periodically. My question is how do I implement this timer. I can think of two things. A Cron job to execute a python script periodically or using a python script w...
Gtk loop or Cron for timer
Well, I have created a python script, which checks the number of uncompleted tasks of tasque and displays it using pynotify periodically. My question is how do I implement this timer. I can think of two things. A Cron job to execute a python script periodically or using a python script which uses a gtk loop to call the...
[ "Cron job. It's more likely to be \"in line\" with actual time, since it's a more stable and time-tested choice. It's also less demanding on resources than using a loop in Python since it doesn't require a constant Python interpreter process, and is probably better optimized than pyGTK (choice is mature, stable sof...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004268374_python.txt
Q: How can I use non ASCII file names in a zipped file and extract them using ZipFile in Python 2.4? I have a file öl_och_ål_är_gott.txt inside a zip archive named öl_och_ål_är_gott.zip. The archive isn't created using zipfile. It could come from any software capable of creating a zip archive. src = open(file_path, "...
How can I use non ASCII file names in a zipped file and extract them using ZipFile in Python 2.4?
I have a file öl_och_ål_är_gott.txt inside a zip archive named öl_och_ål_är_gott.zip. The archive isn't created using zipfile. It could come from any software capable of creating a zip archive. src = open(file_path, "rb" ) zip_file = ZipFile(src) for info in zip_file.infolist(): print info.filename ... prints ...
[ "As the docs state, there is no official file name encoding for ZIP files. If you have Unicode file names (as in your case), you must convert them to byte strings in your desired encoding before passing them.\nDOCS\nThough I don't know why it doesn't work for you.\n>>> src = open('/Desktop/test.zip', 'rb')\n>>> zip...
[ 1 ]
[]
[]
[ "character_encoding", "python", "python_zipfile" ]
stackoverflow_0004269084_character_encoding_python_python_zipfile.txt
Q: mixing 2d and 3d in opengl (using pyglet) I am trying to mix 2d and 3d in opengl in pyglet, i.e. draw a 3d scene then switch to orthographic projection and draw stuff over the top. I draw the 3d stuff, push the projection matrix to the stack, do a glOrtho projection matrix, draw the 2d stuff, then pop the previou...
mixing 2d and 3d in opengl (using pyglet)
I am trying to mix 2d and 3d in opengl in pyglet, i.e. draw a 3d scene then switch to orthographic projection and draw stuff over the top. I draw the 3d stuff, push the projection matrix to the stack, do a glOrtho projection matrix, draw the 2d stuff, then pop the previous matrix off the stack. The 3d stuff draws fine...
[ "I would recommend that you fully reset the modelview and projection matrices on each render, and then don't use push/pop when you go from 3d to 2d.\nHowever, I suspect that you are using bad coordinates so the scene is drawing outside the clip planes. In partciular I am a tad suspicious of putting the near clippin...
[ 2, 0 ]
[]
[]
[ "opengl", "pyglet", "python" ]
stackoverflow_0004269079_opengl_pyglet_python.txt
Q: Combiner function in python hadoop streaming I have a mapper that outputs key and value , which is sorted and piped into reducer.py , As the keys are already sorted, before I get to the reducer , I want to write a combiner which iterates through the sorted list and outputs key , [ v1,v2,v3] pair which will be use...
Combiner function in python hadoop streaming
I have a mapper that outputs key and value , which is sorted and piped into reducer.py , As the keys are already sorted, before I get to the reducer , I want to write a combiner which iterates through the sorted list and outputs key , [ v1,v2,v3] pair which will be used in reducer. cat data | python mapper.py | sort |...
[ "Use itertools.groupby:\n>>> import itertools\n>>> import operator\n>>> foo = [(\"a\", 1), (\"a\", 2), (\"b\", 1), (\"c\", 1), (\"c\", 2)]\n>>> for group in itertools.groupby(foo, operator.itemgetter(0)):\n... print group[0], list(map(operator.itemgetter(1), group[1]))\n...\na [1, 2]\nb [1]\nc [1, 2]\n\n\nExpla...
[ 5 ]
[]
[]
[ "hadoop", "mapreduce", "python" ]
stackoverflow_0004269355_hadoop_mapreduce_python.txt
Q: Does Django or mod_wsgi modify sys.path when it's running? I setup mod_wsgi, and checked it works fine. I also came up with simple django project, and also checked it works fine with the following command django-admin.py runserver --settings=mysite.settings However, when I run the following wsgi, import os imp...
Does Django or mod_wsgi modify sys.path when it's running?
I setup mod_wsgi, and checked it works fine. I also came up with simple django project, and also checked it works fine with the following command django-admin.py runserver --settings=mysite.settings However, when I run the following wsgi, import os import sys mysite = '/Users/smcho/Desktop/django/mysite' if mysite...
[ "You only check that '/Users/smcho/Desktop/django/mysite' is in sys.path, but if not you add that and the '/Users/smcho/Desktop/django'. To import mysite.settings, Python needs the latter, not the former. So you should be sure to add that.\n" ]
[ 1 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0004269445_django_mod_wsgi_python.txt
Q: Should I wait for Django to start supporting Python 3? I have a website idea that I'm very excited about, and I love Python. So, I'm interested in using Django. However, I started learning Python in version 3.1, and Django currently only supports various 2.x versions. I've searched for information about when Djang...
Should I wait for Django to start supporting Python 3?
I have a website idea that I'm very excited about, and I love Python. So, I'm interested in using Django. However, I started learning Python in version 3.1, and Django currently only supports various 2.x versions. I've searched for information about when Django will start supporting Python 3.x, and gotten mostly articl...
[ "No. Don't wait. \nWhy? Pretty much all django libraries are written for Python 2.x, and if you ever plan on using any of them with Python 3 with the next major release of Django then you'll be waiting not 1 but 3-4 years when everyone starts converting their code.\nIn this time, you could have already mastered dja...
[ 14, 3, 2 ]
[]
[]
[ "django", "python", "python_3.x" ]
stackoverflow_0004270192_django_python_python_3.x.txt
Q: Python cumulative histogram of 2D array I have the following problem. I have a 2D array of N pairs. e.g: x = [[5,2],[10,5],[3,2],...] (so a set of arrays a = [5,10,3,...] and b= [2,5,2,...] The first column (a) corresponds to the number of items. The second column (b) is time taken to obtain the items in column (a...
Python cumulative histogram of 2D array
I have the following problem. I have a 2D array of N pairs. e.g: x = [[5,2],[10,5],[3,2],...] (so a set of arrays a = [5,10,3,...] and b= [2,5,2,...] The first column (a) corresponds to the number of items. The second column (b) is time taken to obtain the items in column (a). I want to plot a cumulative histogram of t...
[ "Any chance this is what you are talking about?\n>>> pairs = [[5,2],[10,5],[3,2]]\n>>> a, b = zip(*pairs)\n>>> x = list(a)\n>>> y = [reduce(lambda c, d: c+d, b[:i], 0) for i in range(1, len(b)+1)]\n>>> x\n[5, 10, 3]\n>>> y\n[2, 7, 9]\n\nHere the resulting y values is the sum of all values from b up to that index. \...
[ 2, 1, 1 ]
[]
[]
[ "histogram", "python" ]
stackoverflow_0004269929_histogram_python.txt
Q: How do I require Tkinter with distutils? I'm trying to compile a program using distutils but I want to make sure that the user has Tkinter installed before installing my package. My Google searches have failed to turn up any useful info, any clue how I'd do this? Thanks, Wayne A: You can have a class that inheri...
How do I require Tkinter with distutils?
I'm trying to compile a program using distutils but I want to make sure that the user has Tkinter installed before installing my package. My Google searches have failed to turn up any useful info, any clue how I'd do this? Thanks, Wayne
[ "You can have a class that inherits from install and then do this:\nfrom distutils.command.install import install\n\nclass Install(install):\n def run(self):\n if not check_dependencies():\n # Tkinter was not installed, handle this here\n install.run(self) # proceed with the installatio...
[ 2, 1, 0 ]
[]
[]
[ "distutils", "python", "tkinter" ]
stackoverflow_0004269541_distutils_python_tkinter.txt
Q: Django: retrieve session or cookies in middleware can i get the current session or cookie inside a middleware? I tried but I got: 'WSGIRequest' object has no attribute 'session' A: This will work in any middleware that comes after django.contrib.sessions.middleware.SessionMiddleware in settings.py.
Django: retrieve session or cookies in middleware
can i get the current session or cookie inside a middleware? I tried but I got: 'WSGIRequest' object has no attribute 'session'
[ "This will work in any middleware that comes after django.contrib.sessions.middleware.SessionMiddleware in settings.py. \n" ]
[ 5 ]
[]
[]
[ "django", "django_middleware", "django_sessions", "python" ]
stackoverflow_0004270389_django_django_middleware_django_sessions_python.txt
Q: How can I restore EXIF data after resizing an image with PIL? This question has been asked before, but it was answered a few years ago and the answer is refers to a broken link and is probably no longer the best method. pyxiv2 looks like it would do the task, but it has a lot of dependencies for a seemingly simple...
How can I restore EXIF data after resizing an image with PIL?
This question has been asked before, but it was answered a few years ago and the answer is refers to a broken link and is probably no longer the best method. pyxiv2 looks like it would do the task, but it has a lot of dependencies for a seemingly simple task. I'd also like to know what values will no longer be valid fo...
[ "Just in case someone would like to use piexiv2, here is a solution: image is resized using PIL library, EXIF data copied with pyexiv2 and image size EXIF fields are set with new size.\nimport pyexiv2\nimport tempfile\nfrom PIL import Image\n\n\ndef resize_image(source_path, dest_path, size):\n # resize image\n ...
[ 3 ]
[]
[]
[ "exif", "python", "python_imaging_library" ]
stackoverflow_0004029353_exif_python_python_imaging_library.txt
Q: Python inheritance - One constructor that calls a method that's overriden in child classes, which method is used? I'm writing a class in python that has multiple subclasses in it I have: class Parent: def __init__(self, parameters): self.MethodA(parameters) def MethodA(parameters): doStuff cla...
Python inheritance - One constructor that calls a method that's overriden in child classes, which method is used?
I'm writing a class in python that has multiple subclasses in it I have: class Parent: def __init__(self, parameters): self.MethodA(parameters) def MethodA(parameters): doStuff class child1(Parent): def MethodA(parameters): doOtherStuff Which method will be used when I make an object of ...
[ "Try it and see:\nclass Parent(object):\n def __init__(self, params):\n self.method(params)\n\n def method(self, params):\n print \"Parent's method called with\", params\n\nclass Child(Parent):\n def method(self, params):\n print \"Child's method called with\", params\n\nChild('foo')\n...
[ 3, 1, 1, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0004270988_inheritance_python.txt
Q: Need to build a Python/Django "dashboard" to replace system emails to admins For my python/django site I need to build a "dashboard" that will update me on the status of dozens of error/heartbeat/unexpected events going on. There are a few types of "events" that I'm currently tracking by having the Django site sen...
Need to build a Python/Django "dashboard" to replace system emails to admins
For my python/django site I need to build a "dashboard" that will update me on the status of dozens of error/heartbeat/unexpected events going on. There are a few types of "events" that I'm currently tracking by having the Django site send emails to the admin accounts: 1) Something that normally should happen goes wron...
[ "Sounds like you want to create a basic logging system that outputs to a web page.\nSo you could write something simple app called, say, systemevents that creates an Event record each time something happens on the site. You'd add a signal hook so that anywhere in the rest of the site you could code something like:\...
[ 3, 2 ]
[]
[]
[ "dashboard", "django", "python" ]
stackoverflow_0004268937_dashboard_django_python.txt
Q: pygame OpenGL windows not refreshing on Mac OS X 10.6, Python 2.7 I posted this on the pygame mailing list but maybe someone here will have an answer. I can't be sure whether it's a pygame problem or an SDL problem, really. Essentially, I have some code that uses PyOpenGL and pygame to render rudimentary animation...
pygame OpenGL windows not refreshing on Mac OS X 10.6, Python 2.7
I posted this on the pygame mailing list but maybe someone here will have an answer. I can't be sure whether it's a pygame problem or an SDL problem, really. Essentially, I have some code that uses PyOpenGL and pygame to render rudimentary animations. It works fine under Linux but for some reason, the pygame windows on...
[ "It turns out some sort of OS X driver glitch causes this when I Ctrl+C a pygame-based application, and the only fix is to reboot.\n", "I am afraid its not a OpenGL problem. I had refresh problem in both windows 7 and MACOSX 10.4.11 . For a strange reason no refresh problem on Linux.\nWhat I did to solve this is...
[ 1, 0 ]
[]
[]
[ "macos", "osx_snow_leopard", "pygame", "python", "sdl" ]
stackoverflow_0004161926_macos_osx_snow_leopard_pygame_python_sdl.txt
Q: Functional programming in Python and C++ Is there any good book for functional programming in Python or C++ ? I need to master functional programming in those languages. A: By functional programming, I assume you mean referential transparency (basically, no global state or side-effects), plus things like functio...
Functional programming in Python and C++
Is there any good book for functional programming in Python or C++ ? I need to master functional programming in those languages.
[ "By functional programming, I assume you mean referential transparency (basically, no global state or side-effects), plus things like functions as first-class objects, polymorphic types, partial function application etc.\nThere is no book that I know of that covers functional programming in C++. You could program ...
[ 6, 6, 3, 1, 0, 0 ]
[ "For Perl, I can recommend \"Higher Order Perl\".\nDon't know about Python or C++ though.\n" ]
[ -1 ]
[ "c++", "functional_programming", "python" ]
stackoverflow_0004268152_c++_functional_programming_python.txt
Q: Writing a Python RegEx to select a sub-set of list items in HTML I have a web index view of a folder... <ul><li><a href="/sustainabilitymedia/pics/s5/"> Parent Directory</a></li> <li><a href="n150850_.jpg"> n150850_.jpg</a></li> <li><a href="n150850_ss.jpg"> n150850_ss.jpg</a></li> <li><a href="n150850q.jpg"> n...
Writing a Python RegEx to select a sub-set of list items in HTML
I have a web index view of a folder... <ul><li><a href="/sustainabilitymedia/pics/s5/"> Parent Directory</a></li> <li><a href="n150850_.jpg"> n150850_.jpg</a></li> <li><a href="n150850_ss.jpg"> n150850_ss.jpg</a></li> <li><a href="n150850q.jpg"> n150850q.jpg</a></li> <li><a href="n150858_.jpg"> n150858_.jpg</a></li...
[ "You can do a findAll() using a regex, for example soup_object.findAll('a', {'href': re.compile('.*_ss\\.jpg')}).\n", "Brent's exactly right; +1 to him for being so fast.\nI had already worked out an example so I figured I'd just post anyway (no need to vote on this): \n>>> from BeautifulSoup import BeautifulSou...
[ 6, 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "regex" ]
stackoverflow_0004271215_beautifulsoup_html_python_regex.txt
Q: App Engine: Is time.sleep() counting towards my quotas? Hey. I'm working on an App Engine app that involves queries to the Google Maps API for geocoding. Google Maps doesn't like too much requests so I put a 1 second delay between each request with time.sleep(1). I noticed that my quotas are running low in my GAE...
App Engine: Is time.sleep() counting towards my quotas?
Hey. I'm working on an App Engine app that involves queries to the Google Maps API for geocoding. Google Maps doesn't like too much requests so I put a 1 second delay between each request with time.sleep(1). I noticed that my quotas are running low in my GAE dashboard and decided to run a short test: import cProfile i...
[ "You certainly don't want to be trying to sleep in a system that's designed completely from the ground up to finish requests in the absolute shortest time possible :D\nWhat you could do instead, is create a task for each geocode, (check out the deferred library). You'd want to specify a queue for this task, then ju...
[ 17, 2, 1, 1 ]
[]
[]
[ "cprofile", "google_app_engine", "python" ]
stackoverflow_0004254678_cprofile_google_app_engine_python.txt
Q: IPC on Windows between Java and Python secured to the current user We have a Rest API that requires client certificate authentication. The API is used by this collection of python scripts that a user can run. To make it so that the user doesn't have to enter their password for their client certificate every time...
IPC on Windows between Java and Python secured to the current user
We have a Rest API that requires client certificate authentication. The API is used by this collection of python scripts that a user can run. To make it so that the user doesn't have to enter their password for their client certificate every time they run one of the scripts, we've created this broker process in java ...
[ "The most simple approach is to use cookie-based access control. Have a file in the user's profile/homedirectory which contains the cookie. Have the Java server generate and save the cookie, and have the Python client scripts send the cookie as the first piece of data on any TCP connection.\nThis is secure as long ...
[ 0, 0 ]
[]
[]
[ "ipc", "java", "python", "ssl_certificate", "windows" ]
stackoverflow_0004257038_ipc_java_python_ssl_certificate_windows.txt
Q: Python Undo Unicode Let's say I have the following two variables: bob1 = u'bob\xf0\xa4\xad\xa2' bob2 = 'bob\xf0\xa4\xad\xa2' How can I get the value of bob1 to be the value of bob2? That is, how do I unroll the unicode formatting but keep the escapped hex value? If I do this: bob1.encode('utf8') 'bob\xc3\xb0\xc2...
Python Undo Unicode
Let's say I have the following two variables: bob1 = u'bob\xf0\xa4\xad\xa2' bob2 = 'bob\xf0\xa4\xad\xa2' How can I get the value of bob1 to be the value of bob2? That is, how do I unroll the unicode formatting but keep the escapped hex value? If I do this: bob1.encode('utf8') 'bob\xc3\xb0\xc2\xa4\xc2\xad\xc2\xa2' Th...
[ "Code points between U+0000 and U+00FF map to the same byte value in the ISO 8859-1 or Latin 1 encodings.\n>>> u'bob\\xf0\\xa4\\xad\\xa2'.encode('latin-1')\n'bob\\xf0\\xa4\\xad\\xa2'\n\n" ]
[ 6 ]
[]
[]
[ "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0004271670_encoding_python_unicode_utf_8.txt
Q: Django AdminSite - Difficult or Easy Implementation? Has anyone implemented their own AdminSite? How easy/hard was the basic implementation? I'm in the midst of building a "cms" that's going to be quite large and decently complex in some areas and I'm wondering if using something like AdminSite would save some tim...
Django AdminSite - Difficult or Easy Implementation?
Has anyone implemented their own AdminSite? How easy/hard was the basic implementation? I'm in the midst of building a "cms" that's going to be quite large and decently complex in some areas and I'm wondering if using something like AdminSite would save some time. I'd rather not have to make my own implementation for a...
[ "You've read the admin site docs. It's a lengthy document, but two main hooks for adding custom functionality is through custom urls and modified standard views in your own AdminSite and ModelAdmin objects. Once you hook those in and the urls get mapped, it's just like building any other Django application, only th...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004271089_django_django_admin_python.txt
Q: Python & Multiprocessing, breaking a set generation down into sub-processes I've got to generate a set of strings based on some calculations of other strings. This takes quite a while, and I'm working on a multiprocessor/multicore server so I figured that I could break these tasks down into chunks and pass them o...
Python & Multiprocessing, breaking a set generation down into sub-processes
I've got to generate a set of strings based on some calculations of other strings. This takes quite a while, and I'm working on a multiprocessor/multicore server so I figured that I could break these tasks down into chunks and pass them off to different process. Firstly I break the first list of strings down into chun...
[ "Consider using a pool of workers: http://docs.python.org/dev/library/multiprocessing.html#using-a-pool-of-workers. This does a lot of the work for you in a map-reduce style and returns the assembled results.\n", "Use a multiprocessing.Pipe, or Queue (or other such object) to pass data between processes. Use a Pi...
[ 2, 1, 0 ]
[]
[]
[ "list", "locks", "multiprocessing", "python", "set" ]
stackoverflow_0004271322_list_locks_multiprocessing_python_set.txt
Q: guidance on python scraping packages I'm still a newcomer to python, so I hope this question isn't inane. The more I google for web scraping solutions, the more confused I become (unable to see a forest, despite investigating many trees..) I've been reading documentation on a number of projects, including (but n...
guidance on python scraping packages
I'm still a newcomer to python, so I hope this question isn't inane. The more I google for web scraping solutions, the more confused I become (unable to see a forest, despite investigating many trees..) I've been reading documentation on a number of projects, including (but not limited to) scrapy mechanize spynner bu...
[ "For full browser interaction you are best to look at using Selenium-RC\nThis has a python driver and you can script a browser to \"test\" just about any site on the internet\n" ]
[ 2 ]
[]
[]
[ "mechanize", "python", "scrape", "scrapy" ]
stackoverflow_0004270476_mechanize_python_scrape_scrapy.txt
Q: Calling urlopen from within cgi script, 'connection refused' error I have a python cgi-script that checks if a process is active, and starts it if this process is not found. The process itself is a webserver (based on web.py). After I ensure that the process is running, I try to make a url request to it. The idea ...
Calling urlopen from within cgi script, 'connection refused' error
I have a python cgi-script that checks if a process is active, and starts it if this process is not found. The process itself is a webserver (based on web.py). After I ensure that the process is running, I try to make a url request to it. The idea is to redirect the results of this request to the requester of my cgi sc...
[ "A possibility is that the subprocess hasn't had an opportunity to completely start up before you try to connect to it. To test this, try adding a time.sleep(5) before you call urlopen. \nThis isn't ideal, but will at least help you figure out if that's the problem. Down the road, you'll probably want to set up a...
[ 0 ]
[]
[]
[ "cgi", "python", "urllib2" ]
stackoverflow_0004267834_cgi_python_urllib2.txt
Q: The Python script youtube-dl returns a new file I'm writing a script which uses youtube-dl in a subprocess, p = subprocess.Popen(cmd), to download a YouTube video. What is the best way to get back the new file (which is determined by %(title)s.%(ext)s variables by youtube-dl --output=TEMPLATE)? Unfortunately, ther...
The Python script youtube-dl returns a new file
I'm writing a script which uses youtube-dl in a subprocess, p = subprocess.Popen(cmd), to download a YouTube video. What is the best way to get back the new file (which is determined by %(title)s.%(ext)s variables by youtube-dl --output=TEMPLATE)? Unfortunately, there is no option to print the new file name which I cou...
[ "It does print destination filenane on stdout. It looks like this:\n[download] Destination: XXX\nif you give it options --no-progress --output=XXX.\nOr you could make a template for filename that would allow you to easily recognize newly downloaded file: %(title)s.%(ext)s-latest-download or something and rename it ...
[ 2 ]
[]
[]
[ "download", "python", "youtube" ]
stackoverflow_0004271983_download_python_youtube.txt
Q: pydb problems on invocation from MinGW and from Emacs I am trying to run pydb 1.26 from emacs on a MinGW environment running in windows 7. The python I am currently running is python26 although I have tried this with python25 with the same results. Reading the documentation and looking at the video seems to indic...
pydb problems on invocation from MinGW and from Emacs
I am trying to run pydb 1.26 from emacs on a MinGW environment running in windows 7. The python I am currently running is python26 although I have tried this with python25 with the same results. Reading the documentation and looking at the video seems to indicate that in order to start using pydb with GUD all I have t...
[ "I think there is a lot of confusion here. Also a lot of vagueness in terms of how you are set up in terms of how you got emacs, python and pydb installed.\npydb comes with GNU Emacs code that hooks into the Emacs Lisp package GUD (grand unified debugger). Let's leave that aside for the moment since that has nothin...
[ 0 ]
[]
[]
[ "emacs", "mingw", "python" ]
stackoverflow_0004248558_emacs_mingw_python.txt