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: Run Pylons controller as separate app? I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the...
Run Pylons controller as separate app?
I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons ap...
[ "If you want to load parts of a Pylons app, such as the models from outside Pylons, load the Pylons app in the script first:\nfrom paste.deploy import appconfig\nfrom pylons import config\n\nfrom YOURPROJ.config.environment import load_environment\n\nconf = appconfig('config:development.ini', relative_to='.')\nload...
[ 11, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0000134387_pylons_python.txt
Q: Investigating python process to see what's eating CPU I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how bus...
Investigating python process to see what's eating CPU
I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc? Update: configured access log which ...
[ "Profiling might help you learn a bit of what it's doing. If your sort the output by \"time\" you will see which functions are chowing up cpu time, which should give you some good hints.\n", "As you noted, in --reload mode, Paste sweeps the filesystem every second to see if any of the files loaded have changed. I...
[ 8, 7 ]
[]
[]
[ "debugging", "monitoring", "multithreading", "pylons", "python" ]
stackoverflow_0000760039_debugging_monitoring_multithreading_pylons_python.txt
Q: Is there a way to resize images in Django via imagename.230x150.jpg? There's a nice plugin for Frog CMS that lets you just type in yourpicture.120x120.jpg or whatever, and it will automatically use the image in that dimension. If it doesn't exist, it creates it and adds it to the filesystem. http://www.naehrstoff....
Is there a way to resize images in Django via imagename.230x150.jpg?
There's a nice plugin for Frog CMS that lets you just type in yourpicture.120x120.jpg or whatever, and it will automatically use the image in that dimension. If it doesn't exist, it creates it and adds it to the filesystem. http://www.naehrstoff.ch/code/image-resize-for-frog I was wondering if there's anything like thi...
[ "I think this snippet is close to what you need: Dynamic thumbnail generator\nYou might also want to investigate sorl-thumbnail which, even though it codes the thumbnail dimensions in the template instead of the URL, is more flexible/powerful.\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000784099_django_python.txt
Q: Django Model.object.get pre_save Function Weirdness I have made a function that connects to a models 'pre_save' signal. Inside the function I am trying to check if the model instance's pk already exists in the table with: sender.objects.get(pk=instance._get_pk_val()) The first instance of the model raises an erro...
Django Model.object.get pre_save Function Weirdness
I have made a function that connects to a models 'pre_save' signal. Inside the function I am trying to check if the model instance's pk already exists in the table with: sender.objects.get(pk=instance._get_pk_val()) The first instance of the model raises an error. I catch the error and generate a slug field from the t...
[ "S.Lott is correct... use save(), as you've already acknowledged that you have started doing.\nAs for the signal question, I can honestly see nothing wrong with your code. I've even run it locally myself with success. Are you sure that you're representing it properly in the question? Or that instance2 isn't already...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_signals", "error_handling", "python" ]
stackoverflow_0000702150_django_django_models_django_signals_error_handling_python.txt
Q: One view ( frontpage ) for many controllers (sub views) Notes: Cannot use Javascript or iframes. In fact I can't trust the client browser to do just about anything but the ultra basics. I'm rebuilding a legacy PHP4 app as a MVC application, with most of my research currently focused with the Pylon's framework. One...
One view ( frontpage ) for many controllers (sub views)
Notes: Cannot use Javascript or iframes. In fact I can't trust the client browser to do just about anything but the ultra basics. I'm rebuilding a legacy PHP4 app as a MVC application, with most of my research currently focused with the Pylon's framework. One of the first weird issues I've run into and one I've solved ...
[ "While in most cases I'd recommend what you originally stated, using Javascript to load each widget, since that isn't an option I think you'll need to do something a little different.\nIn addition to using the approach of trying to have a single front controller go through all the widgets needed and building them, ...
[ 6, 0 ]
[]
[]
[ "cherrypy", "model_view_controller", "pylons", "python" ]
stackoverflow_0000574140_cherrypy_model_view_controller_pylons_python.txt
Q: Getting Python System Calls as string results I'd like to use os.system("md5sum myFile") and have the result returned from os.system instead of just runned in a subshell where it's echoed. In short I'd like to do this: resultMD5 = os.system("md5sum myFile") And only have the md5sum in resultMD5 and not echoed. A...
Getting Python System Calls as string results
I'd like to use os.system("md5sum myFile") and have the result returned from os.system instead of just runned in a subshell where it's echoed. In short I'd like to do this: resultMD5 = os.system("md5sum myFile") And only have the md5sum in resultMD5 and not echoed.
[ "subprocess is better than using os.system or os.popen\nimport subprocess\nresultMD5 = subprocess.Popen([\"md5sum\",\"myFile\"],stdout=subprocess.PIPE).communicate()[0]\n\nOr just calculate the md5sum yourself with the hashlib module.\nimport hashlib\nresultMD5 = hashlib.md5(open(\"myFile\").read()).hexdigest()\n\n...
[ 12, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000785078_python.txt
Q: AttributeError: xmlNode instance has no attribute 'isCountNode' I'm using libxml2 in a Python app I'm writing, and am trying to run some test code to parse an XML file. The program downloads an XML file from the internet and parses it. However, I have run into a problem. With the following code: xmldoc = libxml2.p...
AttributeError: xmlNode instance has no attribute 'isCountNode'
I'm using libxml2 in a Python app I'm writing, and am trying to run some test code to parse an XML file. The program downloads an XML file from the internet and parses it. However, I have run into a problem. With the following code: xmldoc = libxml2.parseDoc(gfile_content) droot = xmldoc.children # Get documen...
[ "isCountNode should read \"lsCountNode\" (a lower-case \"L\")\n" ]
[ 3 ]
[]
[]
[ "centos", "centos5", "libxml2", "python", "xml" ]
stackoverflow_0000785972_centos_centos5_libxml2_python_xml.txt
Q: Color picking from given coordinates What is the simplest way to pick up the RGB color code of the given coordinates? For simplicity let's assume that the screen resolution is 1024x768 and color depth/quality 32 bits. The coordinates are given relative to the upper left corner of the screen. I'd like to get some t...
Color picking from given coordinates
What is the simplest way to pick up the RGB color code of the given coordinates? For simplicity let's assume that the screen resolution is 1024x768 and color depth/quality 32 bits. The coordinates are given relative to the upper left corner of the screen. I'd like to get some tips or examples how it can be done with Py...
[ "The win32gui ActivePython documentation should be useful.\nI think you can construct something like:\nimport win32gui\nGetPixel(GetDC(WindowFromPoint( (XPos,YPos) )), XPos , YPos )\n\n" ]
[ 1 ]
[]
[]
[ "color_picker", "python", "windows" ]
stackoverflow_0000785157_color_picker_python_windows.txt
Q: Django blows up with 1.1, Can't find urls module EDIT: Issue solved, answered it below. Lame error. Blah So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback: http://dpaste.com/37391/ - This happens on any page I try to go to. I've modified my urls.py to incl...
Django blows up with 1.1, Can't find urls module
EDIT: Issue solved, answered it below. Lame error. Blah So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback: http://dpaste.com/37391/ - This happens on any page I try to go to. I've modified my urls.py to include the admin in the new method: from django.contrib ...
[ "I figured it out. I was missing a urls.py that I referenced (for some reason, SVN said it was in the repo but it never was fetched on an update) and it simply said could not find urls (with no reference to notes.urls which WAS missing) so it got very confusing.\nEither way, fixed -- Awesome!\n", "try this:\n ...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_1.1", "python" ]
stackoverflow_0000785987_django_django_1.1_python.txt
Q: Django restapi passing parameter to read() In the test example http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/custom_urls.py on line 19 to they parse the request.path to get the poll_id. This looks very fragile to me. If the url changes then this line breaks. I have attempted t...
Django restapi passing parameter to read()
In the test example http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/custom_urls.py on line 19 to they parse the request.path to get the poll_id. This looks very fragile to me. If the url changes then this line breaks. I have attempted to pass in the poll_id but this did not work. ...
[ "Views are only called when the associated url is matched. By crafting the url regex properly, you can guarantee that any request passed to your view will have the poll_id at the correct position in the request path. This is what the example does:\nurl(r'^json/polls/(?P<poll_id>\\d+)/choices/$', json_choice_resourc...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000786199_django_python.txt
Q: Is there a way to retrieve process stats using Perl or Python? Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific. There are a few problems: I won't know the PID ahead of time, but I can run the process in question from the script itself. For example, I'd hav...
Is there a way to retrieve process stats using Perl or Python?
Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific. There are a few problems: I won't know the PID ahead of time, but I can run the process in question from the script itself. For example, I'd have no problem doing: ./myscript.pl some/process/I/want/to/get/stats/f...
[ "Have a look at the Proc::ProcessTable module which returns quite a bit of information on the processes in the system. Call the \"fields\" method to get a list of details that you can extract from each process.\nI recently discovered the above module which has just about replaced the Process module that I had writt...
[ 7, 2, 1 ]
[]
[]
[ "linux", "perl", "process", "python" ]
stackoverflow_0000785810_linux_perl_process_python.txt
Q: How to get the public channel URL from YouTubeVideoFeed object using the YouTube API? I'm using the Python version of the YouTube API to get a YouTubeVideoFeed object using the following URL: http://gdata.youtube.com/feeds/api/users/USERNAME/uploads Note: I've replaced USERNAME with the account I need to follow....
How to get the public channel URL from YouTubeVideoFeed object using the YouTube API?
I'm using the Python version of the YouTube API to get a YouTubeVideoFeed object using the following URL: http://gdata.youtube.com/feeds/api/users/USERNAME/uploads Note: I've replaced USERNAME with the account I need to follow. So far getting the feed, iterating the entries, getting player urls, titles and thumbnails...
[ "Well, the youtube.com/user/USERNAME is a pretty safe bet if you want to construct the URL yourself, but I think what you want is the link rel='alternate'\nYou have to get the link array from the feed and iterate to find alternate, then grab the href\nsomething like:\nclient = gdata.youtube.service.YouTubeService()...
[ 1, 0 ]
[]
[]
[ "feed", "python", "youtube", "youtube_api" ]
stackoverflow_0000776110_feed_python_youtube_youtube_api.txt
Q: How to design an email system? I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communicat...
How to design an email system?
I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will...
[ "This is a real good candidate for using some off the shelf software. There are any number of open-source mailing list manager packages around; they already know how to do the mass mailings. It's not completely clear whether these mailings would go to the same set of people each time; if so, get any one of the re...
[ 5, 3, 2, 0 ]
[]
[]
[ "email", "linux", "python" ]
stackoverflow_0000786138_email_linux_python.txt
Q: is it possible to define name of function's arguments dynamically? Now I have this code: attitude = request.REQUEST['attitude'] if attitude == 'want': qs = qs.filter(attitudes__want=True) elif attitude == 'like': qs = qs.filter(attitudes__like=True) elif atti...
is it possible to define name of function's arguments dynamically?
Now I have this code: attitude = request.REQUEST['attitude'] if attitude == 'want': qs = qs.filter(attitudes__want=True) elif attitude == 'like': qs = qs.filter(attitudes__like=True) elif attitude == 'hate': qs = qs.filter(attitudes__hate=True) ...
[ "Yes.\nqs.filter( **{ 'attitudes__%s'%arg:True } )\n\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000787262_django_python.txt
Q: Python-getting data from an asp.net AJAX application Using Python, I'm trying to read the values on http://utahcritseries.com/RawResults.aspx. I can read the page just fine, but am having difficulty changing the value of the year combo box, to view data from other years. How can I read the data for years other t...
Python-getting data from an asp.net AJAX application
Using Python, I'm trying to read the values on http://utahcritseries.com/RawResults.aspx. I can read the page just fine, but am having difficulty changing the value of the year combo box, to view data from other years. How can I read the data for years other than the default of 2002? The page appears to be doing an H...
[ "Use the excellent mechanize library:\nfrom mechanize import Browser\n\nb = Browser()\nb.open(\"http://utahcritseries.com/RawResults.aspx\")\nb.select_form(nr=0)\n\nyear = b.form.find_control(type='select')\nyear.get(label='2005').selected = True\n\nsrc = b.submit().read()\nprint src\n\nMechanize is available on Py...
[ 3 ]
[]
[]
[ "asp.net", "asp.net_ajax", "python", "screen_scraping" ]
stackoverflow_0000786603_asp.net_asp.net_ajax_python_screen_scraping.txt
Q: How to add seconds on a datetime value in Python? I tried modifying the second property, but didn't work. Basically I wanna do: datetime.now().second += 3 A: Have you checked out timedeltas? from datetime import datetime, timedelta x = datetime.now() + timedelta(seconds=3) x += timedelta(seconds=3) A: You cann...
How to add seconds on a datetime value in Python?
I tried modifying the second property, but didn't work. Basically I wanna do: datetime.now().second += 3
[ "Have you checked out timedeltas?\nfrom datetime import datetime, timedelta\nx = datetime.now() + timedelta(seconds=3)\nx += timedelta(seconds=3)\n\n", "You cannot add seconds to a datetime object. From the docs:\n\nA DateTime object should be considered immutable; all conversion and numeric operations return a n...
[ 82, 3 ]
[]
[]
[ "python" ]
stackoverflow_0000787564_python.txt
Q: Python embedding -- how to get the if() truth test behavior from C/C++? I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc. I have been looking at the python/include headers, but h...
Python embedding -- how to get the if() truth test behavior from C/C++?
I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc. I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject_...
[ "Isn't this it, in object.h:\nPyAPI_FUNC(int) PyObject_IsTrue(PyObject *);\n\n?\n", "Use\nint PyObject_IsTrue(PyObject *o)\nReturns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.\n\n(from Python/C API Reference Manual)\n" ...
[ 5, 1 ]
[]
[]
[ "embedded_language", "python" ]
stackoverflow_0000787711_embedded_language_python.txt
Q: Python: email get_payload decode fails when hitting equal sign? Running into strangeness with get_payload: it seems to crap out when it sees an equal sign in the message it's decoding. Here's code that displays the error: import email data = file('testmessage.txt').read() msg = email.message_from_string( data ) ...
Python: email get_payload decode fails when hitting equal sign?
Running into strangeness with get_payload: it seems to crap out when it sees an equal sign in the message it's decoding. Here's code that displays the error: import email data = file('testmessage.txt').read() msg = email.message_from_string( data ) payload = msg.get_payload(decode=True) print payload And here's a sa...
[ "You have a line endings problem. The body of your test message uses bare carriage returns (\\r) without newlines (\\n). If you fix up the line endings before parsing the email, it all works:\nimport email, re\ndata = file('testmessage.txt').read()\ndata = re.sub(r'\\r(?!\\n)', '\\r\\n', data) # Bare \\r becomes...
[ 7 ]
[]
[]
[ "email", "python" ]
stackoverflow_0000787739_email_python.txt
Q: How to install python-rsvg without python-gnome2-desktop on Ubuntu 8.10? I need rsvg support in Python 2.5.2. It appears that I have to install all 199 deps along with the package python-gnome2-desktop, which doesn't sound fun at all. Alternatives? A: No longer relevant. Installed the entire package, and got rsv...
How to install python-rsvg without python-gnome2-desktop on Ubuntu 8.10?
I need rsvg support in Python 2.5.2. It appears that I have to install all 199 deps along with the package python-gnome2-desktop, which doesn't sound fun at all. Alternatives?
[ "No longer relevant. Installed the entire package, and got rsvg that way.\n" ]
[ 2 ]
[]
[]
[ "librsvg", "python", "rsvg" ]
stackoverflow_0000787812_librsvg_python_rsvg.txt
Q: python 2.5 dated? I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version? A: Basically, python code, for the moment, will be divided into python 2.X code and python 3 c...
python 2.5 dated?
I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version?
[ "Basically, python code, for the moment, will be divided into python 2.X code and python 3 code. Python 3 breaks many changes in the interest of cleaning up the language. The majority of code and libraries are written for 2.X in mind. It is probably best to learn one, and know what is different with the other. On a...
[ 6, 4, 3, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000787849_python.txt
Q: Python Django Template: Iterate Through List Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code: <div id="right_pod"> {%for i in rangeLength%} ...
Python Django Template: Iterate Through List
Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code: <div id="right_pod"> {%for i in rangeLength%} <div class="user_pod" > {{c.i.0.from_user}...
[ "Do you need i to be an index? If not, see if the following code does what you're after:\n<div id=\"right_pod\">\n{% for i in c %}\n <div class=\"user_pod\">\n {{ i.0.from_user }}\n </div>\n{% endfor %}\n\n", "Please read the entire documentation on the template language's for loops. First of all, th...
[ 28, 15, 9 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000784124_django_django_templates_python.txt
Q: How to get publisher.authors when you have book.publisher and book.author? Fresh from the Djangobook tutorial using the Books app example, you have Book related to Author through a many-to-many relationship and Book related to Publisher. You can get a set of books associated with a publisher with p.book_set.all(),...
How to get publisher.authors when you have book.publisher and book.author?
Fresh from the Djangobook tutorial using the Books app example, you have Book related to Author through a many-to-many relationship and Book related to Publisher. You can get a set of books associated with a publisher with p.book_set.all(), but what do you need to do to get a set of authors associated with a publisher ...
[ "Something like that:\npublisher = Publisher.objects.get(...)\nauthors = Author.objects.filter(book__publisher=publisher).distinct()\n\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000788192_django_python.txt
Q: How do i interface with the MSN Protocol using Python? I am trying to connect to the MSN network using Python.. I've done some searching and it seems like http://blitiri.com.ar/p/msnlib/ and http://msnp.sourceforge.net/ are the available libraries. However both seem very old and is there any other up to date libra...
How do i interface with the MSN Protocol using Python?
I am trying to connect to the MSN network using Python.. I've done some searching and it seems like http://blitiri.com.ar/p/msnlib/ and http://msnp.sourceforge.net/ are the available libraries. However both seem very old and is there any other up to date library that i can use? Dupplicate of : MSN with Python
[ "I might be babbling here, but I think Python Twisted has a protocol implementation of msn.\n", "libpurple at http://developer.pidgin.im/wiki/WhatIsLibpurple\nis the library that drives pidgin, and allows you to connect to MSN and others, not sure if there's a python wrapper for it.\n" ]
[ 2, 2 ]
[]
[]
[ "msn", "python" ]
stackoverflow_0000788715_msn_python.txt
Q: ORM (object relational manager) solution with multiple programming language support Is there a good ORM (object relational manager) solution that can use the same database from C++, C#, Python? It could also be multiple solutions, e.g. one per language, as long as they can can access the same database and use the ...
ORM (object relational manager) solution with multiple programming language support
Is there a good ORM (object relational manager) solution that can use the same database from C++, C#, Python? It could also be multiple solutions, e.g. one per language, as long as they can can access the same database and use the same schema. Multi platform support is also needed. Clarification: The idea is to have on...
[ "With SQLAlchemy, you can use reflection to get the schema, so it should work with any of the supported engines.\nI've used this to migrate data from an old SQLite to Postgres.\n", "I know DataAbstract for Pascal, C# and soon for objective C for Mac and Iphone but no Python support.\n", "We have an O/RM that ha...
[ 1, 1, 0 ]
[]
[]
[ "c#", "c++", "orm", "python" ]
stackoverflow_0000482612_c#_c++_orm_python.txt
Q: Problem running twisted.words example using msn protocol I am currently trying to use the Twisted library specifically twisted words to try and interat with MSN. However when i run the sample script provided by twisted , i get an error. Specifically the error is found here http://i42.tinypic.com/wl945w.jpg . The s...
Problem running twisted.words example using msn protocol
I am currently trying to use the Twisted library specifically twisted words to try and interat with MSN. However when i run the sample script provided by twisted , i get an error. Specifically the error is found here http://i42.tinypic.com/wl945w.jpg . The script can be found over here http://twistedmatrix.com/projects...
[ "Since MSN involves SSL connections, you must have pyOpenSSL installed in order to use it. It seems as though you probably do not. This isn't a very good way for Twisted to be reporting this missing dependency, though. I recommend filing a ticket in the Twisted issue tracker for improving this reporting.\n", "...
[ 3, 2 ]
[]
[]
[ "msn", "python", "twisted", "twisted.words" ]
stackoverflow_0000788902_msn_python_twisted_twisted.words.txt
Q: Case insensitivity in Python strings I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that. Is there a cas...
Case insensitivity in Python strings
I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that. Is there a case insensitive version of replace()?
[ "You can supply the flag re.IGNORECASE to functions in the re module as described in the docs.\nmatcher = re.compile(myExpression, re.IGNORECASE)\n\n", "Using re is the best solution even if you think it's complicated.\nTo replace all occurrences of 'abc', 'ABC', 'Abc', etc., with 'Python', say:\nre.sub(r'(?i)abc...
[ 10, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000787842_python.txt
Q: Web development with python and sql I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4...
Web development with python and sql
I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4) create web pages, shopping carts etc fo...
[ "Django was made for this kind of thing. Check it out.\nAs far as hosting, djangofriendly.com is a great resource. I have used WebFaction before and I am absolutely in love with how easy it is to get Django going with them and with their excellent customer service. Very top notch for reasonable prices if you are go...
[ 8, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000788083_python.txt
Q: Handling Authorization in web frameworks I want to write a simple web framework myself using WSGI, Python. I am in study to understand the authorization system. The system needs to be more modular and abstract enough to add new system into the project as a plug-in. User may use DB or distributed key/value pair, bi...
Handling Authorization in web frameworks
I want to write a simple web framework myself using WSGI, Python. I am in study to understand the authorization system. The system needs to be more modular and abstract enough to add new system into the project as a plug-in. User may use DB or distributed key/value pair, bigtable, etc to store their information. Lets ...
[ "\n\"Is it possible to work with 'identity' object at entire framework?\"\n\"But it is really tough to define \"Identity\" as an object due to its complex nature. \"\n\nUntil you define identity, yes, it's difficult to work with.\nIdentity has to be positively specified. Leaving it so vague that \"It may contain a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0000789468_python.txt
Q: What is the easiest way to build Python26.zip for embedded distribution? I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of...
What is the easiest way to build Python26.zip for embedded distribution?
I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I have...
[ "It shouldn't be too difficult to write a script for that. Check out the zipfile.PyZipFile class and it's writepy method.\n", "I would probably use setuptools to create an egg (basically a java jar for python). The setup.py would probably look something like this:\nfrom setuptools import setup, find_packages\n\...
[ 2, 2 ]
[]
[]
[ "c++", "distribution", "embedded_language", "python" ]
stackoverflow_0000789598_c++_distribution_embedded_language_python.txt
Q: Why builtin functions instead of root class methods? (I'm sure this is a FAQ, but also hard to google) Why does Python use abs(x) instead of x.abs? As far as I see everything abs() does besides calling x.__abs__ could just as well be implemented in object.abs() Is it historical, because there hasn't always been a ...
Why builtin functions instead of root class methods?
(I'm sure this is a FAQ, but also hard to google) Why does Python use abs(x) instead of x.abs? As far as I see everything abs() does besides calling x.__abs__ could just as well be implemented in object.abs() Is it historical, because there hasn't always been a root class?
[ "The official answer from Guido van Rossum, with additional explanation from Fredrik Lundh, is here: http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm\nIn a nutshell:\n\nabs(x) reads more naturally than x.abs() for most such operations...
[ 13, 1, 0 ]
[ "i think it involves how object oriented way python has been used, because the first parameter of method calls on object is the object itself, so x.abs() is in essential abs(x)\nlook at the follow page under chapter 3.2.3 Python supports object-oriented programming \nthat should explain some things\n" ]
[ -3 ]
[ "oop", "python" ]
stackoverflow_0000789718_oop_python.txt
Q: How do I watch a serial port with QSocketNotifier (linux)? Could someone give me an example on how to setup QSocketNotifier to fire an event if something comes on /dev/ttyS0 ? (preferably in python/pyqt4) A: Here's an example that just keeps reading from a file using QSocketNotifier. Simply replace that 'foo.txt...
How do I watch a serial port with QSocketNotifier (linux)?
Could someone give me an example on how to setup QSocketNotifier to fire an event if something comes on /dev/ttyS0 ? (preferably in python/pyqt4)
[ "Here's an example that just keeps reading from a file using QSocketNotifier. Simply replace that 'foo.txt' with '/dev/ttyS0' and you should be good to go.\n\nimport os\n\nfrom PyQt4.QtCore import QCoreApplication, QSocketNotifier, SIGNAL\n\n\ndef readAllData(fd):\n bufferSize = 1024\n while True:\n ...
[ 5 ]
[]
[]
[ "pyqt4", "python", "qt", "serial_port" ]
stackoverflow_0000789304_pyqt4_python_qt_serial_port.txt
Q: What is wrong with my attempt to do a string replace operation in Python? What am I doing wrong here? import re x = "The sky is red" r = re.compile ("red") y = r.sub(x, "blue") print x # Prints "The sky is red" print y # Prints "blue" How do i get it to print "The sky is blue"? A: The problem with your code i...
What is wrong with my attempt to do a string replace operation in Python?
What am I doing wrong here? import re x = "The sky is red" r = re.compile ("red") y = r.sub(x, "blue") print x # Prints "The sky is red" print y # Prints "blue" How do i get it to print "The sky is blue"?
[ "The problem with your code is that there are two sub functions in the re module. One is the general one and there's one tied to regular expression objects. Your code is not following either one:\nThe two methods are:\nre.sub(pattern, repl, string[, count]) (docs here)\nUsed like so:\n>>> y = re.sub(r, 'blue', x)\n...
[ 12, 6, 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000786881_python.txt
Q: Locales and temperature/length conversion Do locales contain information about preferred units for temperature, lengths, etc. on Unix/Linux? Is it possible to access these properties from Python? I checked out the "locales" module, but didn't find anything suitable. I'd like my application to automatically convert...
Locales and temperature/length conversion
Do locales contain information about preferred units for temperature, lengths, etc. on Unix/Linux? Is it possible to access these properties from Python? I checked out the "locales" module, but didn't find anything suitable. I'd like my application to automatically convert values into the most suitable unit.
[ "No, that's not possible.\nI think every country in the world is on the metric system, with the dubious exceptions of the United States and a few others. With that said, you can be confident about choosing metric.\nYou'd want to write classes with conversion and math rules to define proper operations for each meas...
[ 3, 0 ]
[]
[]
[ "localization", "python" ]
stackoverflow_0000789953_localization_python.txt
Q: finding substrings in python Can you please help me to get the substrings between two characters at each occurrence For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences: ex: QUWESEADFQDFSAEDFS and to find the substring with minimum length. A: import re DATA ...
finding substrings in python
Can you please help me to get the substrings between two characters at each occurrence For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences: ex: QUWESEADFQDFSAEDFS and to find the substring with minimum length.
[ "import re\nDATA = \"QUWESEADFQDFSAEDFS\"\n\n# Get all the substrings between Q and E:\nsubstrings = re.findall(r'Q([^E]+)E', DATA)\nprint \"Substrings:\", substrings\n\n# Sort by length, then the first one is the shortest:\nsubstrings.sort(key=lambda s: len(s))\nprint \"Shortest substring:\", substrings[0]\n\n", ...
[ 16, 7 ]
[]
[]
[ "algorithm", "python", "regex", "substring" ]
stackoverflow_0000788699_algorithm_python_regex_substring.txt
Q: What is the best way to redirect email to a Python script? I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a...
What is the best way to redirect email to a Python script?
I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool...
[ "To directly answer your questions:\n1,2) Check out this FAQ in the WebFaction website. It explains how to easily route incoming emails into the script of your choice. When creating an email address, you can just not specify a username to make it be a catch-all email that anything sent to the domain goes to.\n3) As...
[ 4, 2, 0, 0 ]
[]
[]
[ "django", "email", "python" ]
stackoverflow_0000789685_django_email_python.txt
Q: Updating tkinter labels in python I'm working on giving a python server a GUI with tkinter by passing the Server's root instance to the Tkinter window. The problem is in keeping information in the labels up to date. For instance, the server has a Users list, containing the users that are logged on. It's simple eno...
Updating tkinter labels in python
I'm working on giving a python server a GUI with tkinter by passing the Server's root instance to the Tkinter window. The problem is in keeping information in the labels up to date. For instance, the server has a Users list, containing the users that are logged on. It's simple enough to do this for an initial list: str...
[ "You could use callbacks on the server instance. Install a callback that updates the label whenever the user-list changes.\nIf you can't change the server code, you would need to poll the list for updates every few seconds. You could use the Tkinter event system to keep track of the updates.\ndef user_updater(self)...
[ 3, 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0000773797_python_tkinter.txt
Q: Is there a replacement for Paste.Template? I have grown tired of all the little issues with paste template, it's horrible to maintain the templates, it has no way of updating an old project and it's very hard to test. I'm wondering if someone knows of an alternative for quickstart generators as they have proven t...
Is there a replacement for Paste.Template?
I have grown tired of all the little issues with paste template, it's horrible to maintain the templates, it has no way of updating an old project and it's very hard to test. I'm wondering if someone knows of an alternative for quickstart generators as they have proven to be useful.
[]
[]
[ "I haven't used paste templates, so I'm not sure how it compares, but Mako seems like a fairly good system.\nA snippet of the template language from their front page:\n<%inherit file=\"base.html\"/>\n<%\n rows = [[v for v in range(0,10)] for row in range(0,10)]\n%>\n<table>\n % for row in rows:\n ${mak...
[ -1 ]
[ "generator", "python", "templates" ]
stackoverflow_0000790534_generator_python_templates.txt
Q: Python library to modify MP3 audio without transcoding I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase. My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those ...
Python library to modify MP3 audio without transcoding
I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase. My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be con...
[ "If you want to do things low-level, use pymad. It turns MP3s into a buffer of sample data.\nIf you want something a little higher-level, use the Echo Nest Remix API (disclosure: I wrote part of it for my dayjob). It includes a few examples. If you look at the cowbell example (i.e., MoreCowbell.dj), you'll see a fo...
[ 7, 6, 3, 1, 1 ]
[]
[]
[ "codec", "mp3", "python" ]
stackoverflow_0000310765_codec_mp3_python.txt
Q: Python - lines from files - all combinations I have two files - prefix.txt and terms.txt both have about 100 lines. I'd like to write out a third file with the Cartesian product http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join -about 10000 lines. What is the best way to approach this in Python? Secondly, is th...
Python - lines from files - all combinations
I have two files - prefix.txt and terms.txt both have about 100 lines. I'd like to write out a third file with the Cartesian product http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join -about 10000 lines. What is the best way to approach this in Python? Secondly, is there a way to write the 10,000 lines to the third f...
[ "You need itertools.product.\nfor prefix, term in itertools.product(open('prefix.txt'), open('terms.txt')):\n print(prefix.strip() + term.strip())\n\nPrint them, or accumulate them, or write them directly. You need the .strip() because of the newline that comes with each of them.\nAfterwards, you can shuffle the...
[ 4, 1, 1 ]
[]
[]
[ "file_io", "python", "random" ]
stackoverflow_0000790860_file_io_python_random.txt
Q: Is it possible to call a Python module from ObjC? Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString? For example, doing the equivalent of the following Python code: import mymodule result = mymodule.mymethod() ..in pseudo-ObjC: PyModule *mypymod = [PyIm...
Is it possible to call a Python module from ObjC?
Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString? For example, doing the equivalent of the following Python code: import mymodule result = mymodule.mymethod() ..in pseudo-ObjC: PyModule *mypymod = [PyImport module:@"mymodule"]; NSString *result = [[mypymod ...
[ "As mentioned in Alex Martelli's answer (although the link in the mailing-list message was broken, it should be https://docs.python.org/extending/embedding.html#pure-embedding).. The C way of calling.. \nprint urllib.urlopen(\"http://google.com\").read()\n\n\nAdd the Python.framework to your project (Right click Ex...
[ 12, 3 ]
[]
[]
[ "objective_c", "pyobjc", "python" ]
stackoverflow_0000790103_objective_c_pyobjc_python.txt
Q: Object class override or modify Is it possible to add a method to an object class, and use it on all objects? A: In Python attributes are implemented using a dictionary : >>> t = test() >>> t.__dict__["foo"] = "bla" >>> t.foo 'bla' But for "object", it uses a 'dictproxy' as an interface to prevent such assignem...
Object class override or modify
Is it possible to add a method to an object class, and use it on all objects?
[ "In Python attributes are implemented using a dictionary :\n>>> t = test()\n>>> t.__dict__[\"foo\"] = \"bla\"\n>>> t.foo\n'bla'\n\nBut for \"object\", it uses a 'dictproxy' as an interface to prevent such assignement :\n>>> object.__dict__[\"test\"] = \"test\"\nTypeError: 'dictproxy' object does not support item as...
[ 8, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000790560_python.txt
Q: Elixir reflection I define some Entities which works fine; for meta programming issues. I now need to reflect the field properties defined in the model. For example: class Foo(Entity): bar = OneToMany('Bar') baz = ManyToMany('Baz') Which type of relation is set: "ManyToMany", "OneToMany" or even a pla...
Elixir reflection
I define some Entities which works fine; for meta programming issues. I now need to reflect the field properties defined in the model. For example: class Foo(Entity): bar = OneToMany('Bar') baz = ManyToMany('Baz') Which type of relation is set: "ManyToMany", "OneToMany" or even a plain "Field", and the rel...
[ "You can do introspection in Elixir as you would anywhere in Python -- get all names of attributes of class Foo with dir(Foo), extract an attribute given its name with getattr(Foo, thename), check the type of the attribute with type(theattr) or isinstance, etc. The string 'Bar' that you pass as the attribute to th...
[ 4 ]
[]
[]
[ "pylons", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0000791150_pylons_python_python_elixir_sqlalchemy.txt
Q: Sorting by key and value in case keys are equal The official oauth guide makes this recommendation: It is important not to try and perform the sort operation on some combined string of both name and value as some known separators (such as '=') will cause the sort order to change due to their impact on t...
Sorting by key and value in case keys are equal
The official oauth guide makes this recommendation: It is important not to try and perform the sort operation on some combined string of both name and value as some known separators (such as '=') will cause the sort order to change due to their impact on the string value. If this is the case, then what woul...
[ "Just sort the list of tuples (name, value) -- Python does lexicographic ordering for you.\n" ]
[ 4 ]
[]
[]
[ "oauth", "python", "sorting" ]
stackoverflow_0000791316_oauth_python_sorting.txt
Q: wxPython crashes under Vista I am following the Getting Started guide for wxPython. But unfortunately the first 'Hello World' example crashes. The dialog window shows just fine, but as soon as I move my mouse over the window a "pythonw.exe has stopped working" Windows message appears. I use: Python 2.6.2 wxPytho...
wxPython crashes under Vista
I am following the Getting Started guide for wxPython. But unfortunately the first 'Hello World' example crashes. The dialog window shows just fine, but as soon as I move my mouse over the window a "pythonw.exe has stopped working" Windows message appears. I use: Python 2.6.2 wxPython2.8-win32-unicode-2.8.9.2-py26 Vi...
[ "See here for why: http://www.tejerodgers.com/snippets/2009/why-wxpython-crashes-python-26/\nSee wxPython's README for a hack that will let you work around the problem.\nA fix has been discovered and will be included in the next release.\n", "32 or 64 bit Vista? When you did installs did you \"run as admin\"? I a...
[ 4, 2 ]
[]
[]
[ "python", "windows_vista", "wxpython" ]
stackoverflow_0000791341_python_windows_vista_wxpython.txt
Q: Using Python set type to implement ACL Currently I have tables like: Pages, Groups, GroupPage, Users, UserGroup. With pickled sets I can implement the same thing with only 3 tables: Pages, Groups, Users. set seems a natural choice for implementing ACL, as group and permission related operations can be expressed ve...
Using Python set type to implement ACL
Currently I have tables like: Pages, Groups, GroupPage, Users, UserGroup. With pickled sets I can implement the same thing with only 3 tables: Pages, Groups, Users. set seems a natural choice for implementing ACL, as group and permission related operations can be expressed very naturally with sets. If I store the allow...
[ "If you're going to pickle sets, you should find a good object database (like ZODB). In a pure-relational world, your sets are stored as BLOBS, which works out well. Trying to pickle sets in an ORM situation may lead to confusing problems with the ORM mappings, since they mostly assume purely relational mappings ...
[ 3, 2, 2, 1 ]
[]
[]
[ "acl", "pickle", "python", "set" ]
stackoverflow_0000790613_acl_pickle_python_set.txt
Q: pyinotify bug with reading file on creation? I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use pyinotify to setup a directory to watch for IN_CREATE kernel events, and fire the parse() method. Here is the module: from pyinotify import WatchManager, Threa...
pyinotify bug with reading file on creation?
I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use pyinotify to setup a directory to watch for IN_CREATE kernel events, and fire the parse() method. Here is the module: from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CREATE class Watche...
[ "may be you want to wait till file is closed?\n", "As @SilentGhost mentioned, you may be reading the file before any content has been added to file (i.e. you are getting notified of the file creation not file writes).\nUpdate: The loop.py example with pynotify tarball will dump the sequence of inotify events to t...
[ 3, 1, 1, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0000790898_linux_python.txt
Q: Adobe Flash and Python Is it possible to use CPython to develop Adobe Flash based applications? A: You can try ming, a library for generating Macromedia Flash files (.swf). It's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl. A: take a look at Flex PyPy: http://c...
Adobe Flash and Python
Is it possible to use CPython to develop Adobe Flash based applications?
[ "You can try ming, a library for generating Macromedia Flash files (.swf).\nIt's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl. \n", "take a look at Flex PyPy: http://code.google.com/p/flex-pypy/\n", "I guess it would be possible to compile the python interpreter ...
[ 3, 2, 1 ]
[]
[]
[ "flash", "flashdevelop", "python" ]
stackoverflow_0000304779_flash_flashdevelop_python.txt
Q: Best way to turn a list into a dict, where the keys are a value of each object? I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: class S...
Best way to turn a list into a dict, where the keys are a value of each object?
I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: class SomeClass(object): def __init__(self, name): self.name = name object_lis...
[ "In python 3.0 you can use a dict comprehension:\n{an_object.name : an_object for an_object in object_list}\n\nThis is also possible in Python 2, but it's a bit uglier:\ndict([(an_object.name, an_object) for an_object in object_list])\n\n", "d = dict(zip([o.name for o in object_list], object_list))\n\n", "If yo...
[ 13, 8, 7 ]
[]
[]
[ "python" ]
stackoverflow_0000791708_python.txt
Q: Can't decode utf-8 string in python on os x terminal.app I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors: >>> wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last):...
Can't decode utf-8 string in python on os x terminal.app
I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors: >>> wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'as...
[ "I think there is encode/decode confusion all over the place. You start with an unicode object:\nu'\\xe4\\xf6\\xfc'\n\nThis is an unicode object, the three characters are the unicode codepoints for \"äöü\". If you want to turn them into Utf-8, you have to encode them:\n>>> u'\\xe4\\xf6\\xfc'.encode('utf-8')\n'\\xc3...
[ 18, 4, 3, 2 ]
[]
[]
[ "macos", "python", "terminal", "unicode" ]
stackoverflow_0000792017_macos_python_terminal_unicode.txt
Q: Navigating Callable-Iterators I'd like to use regular expressions to extract information out of some chat logs. The format of the strings being parsed are 03:22:32 PM <b>blcArmadillo</b>. I used the python type() command to find that the variable messages is a callable-iterator. My question is how do I most effici...
Navigating Callable-Iterators
I'd like to use regular expressions to extract information out of some chat logs. The format of the strings being parsed are 03:22:32 PM <b>blcArmadillo</b>. I used the python type() command to find that the variable messages is a callable-iterator. My question is how do I most efficiently navigate through a callable-i...
[ "An iterator is just an object with a next method. Every time you call it, it returns the next item in a collection. If you need to access arbitrary indexes, you will pretty much have to convert it into a list. Instead of this:\nfor result in messages:\n times.append(result.group('time'))\n\nYou can say this ...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000792304_python.txt
Q: Find shortest substring I have written a code to find the substring from a string. It prints all substrings. But I want a substring that ranges from length 2 to 6 and print the substring of minimum length. Please help me Program: import re p=re.compile('S(.+?)N') s='ASDFANSAAAAAFGNDASMPRKYN' s1=p.findall(s) print...
Find shortest substring
I have written a code to find the substring from a string. It prints all substrings. But I want a substring that ranges from length 2 to 6 and print the substring of minimum length. Please help me Program: import re p=re.compile('S(.+?)N') s='ASDFANSAAAAAFGNDASMPRKYN' s1=p.findall(s) print s1 output: ['DFA', 'AAAAAFG...
[ "If you already have the list, you can use the min function with the len function as the second argument.\n>>> s1 = ['DFA', 'AAAAAFG', 'MPRKY']\n>>> min(s1, key=len)\n'DFA'\n\nEDIT:\nIn the event that two are the same length, you can extend this further to produce a list containing the elements that are all the sam...
[ 9, 4 ]
[]
[]
[ "python", "substring" ]
stackoverflow_0000792394_python_substring.txt
Q: How do I use Tkinter with Python on Windows Vista? I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve th...
How do I use Tkinter with Python on Windows Vista?
I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?
[ "Maybe you should downgrade to 2.5 version?\n", "It seems this is a one of the many weird Vista problems and some random reinstalling, installing/upgrading of the visual studio runtime or some such seems sometimes to help, or disabling sxs in the system configuration or writing a manifest file etc.\nThough I thin...
[ 1, 1 ]
[ "python 2.6.2 + tkinter 8.5, no problems\n" ]
[ -1 ]
[ "python", "tkinter", "windows", "windows_vista" ]
stackoverflow_0000219215_python_tkinter_windows_windows_vista.txt
Q: How to offer platform-specific implementations of a module? I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works: do_it = getattr(__import__(__name__), "do_on_" + sys.platform) ...but breaks if the module is...
How to offer platform-specific implementations of a module?
I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works: do_it = getattr(__import__(__name__), "do_on_" + sys.platform) ...but breaks if the module is put into a package. An alternative would be an if/elif with hard...
[ "Put the code for platform support in different files in your package. Then add this to the file people are supposed to import from:\nif sys.platform.startswith(\"win\"):\n from ._windows_support import *\nelif sys.platform.startswith(\"linux\"):\n from ._unix_support import *\nelse:\n raise ImportError(\"...
[ 5, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000791098_python.txt
Q: Can I write my apps in python and then run them from C? I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the...
Can I write my apps in python and then run them from C?
I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code. Is it possible to eval the python code and run ...
[ "here's a nice tutorial for doing exactly that http://www.linuxjournal.com/article/8497\n", "It's called embedding Python -- it's well covered in the Python docs. See https://docs.python.org/extending/embedding.html\nSee how do i use python libraries in C++?\n", "Yes you can run the Python code from C by embed...
[ 5, 2, 1 ]
[]
[]
[ "c", "interop", "python" ]
stackoverflow_0000792924_c_interop_python.txt
Q: How to avoid Gdk-ERROR caused by Tkinter, visual, and ipython? The following lines cause with ipython a crash as soon as I close the tk-window instance a. import visual, Tkinter a = Tkinter.Tk() a.update() display = visual.display(title = "Hallo") display.exit = 0 visual.sphere() If I close the visual display fir...
How to avoid Gdk-ERROR caused by Tkinter, visual, and ipython?
The following lines cause with ipython a crash as soon as I close the tk-window instance a. import visual, Tkinter a = Tkinter.Tk() a.update() display = visual.display(title = "Hallo") display.exit = 0 visual.sphere() If I close the visual display first, the entire terminal crashes. I run everything on kubuntu 8.10. I...
[ "Have you tried starting ipython with the -gthread -tk command-line switches? \nFrom ipython --help:\n\n -gthread, -qthread, -q4thread, -wthread, -pylab\n\n Only ONE of these can be given, and it can only be given as the\n first option passed to IPython (it will have no effect in any...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0000792816_python_tkinter.txt
Q: Basic MVT issue in Django I have a Django website as follows: site has several views each view has its own template to show its data each template extends a base template base template is the base of the site, has all the JS/CSS and the basic layout So up until now it's all good. So now we have the master head o...
Basic MVT issue in Django
I have a Django website as follows: site has several views each view has its own template to show its data each template extends a base template base template is the base of the site, has all the JS/CSS and the basic layout So up until now it's all good. So now we have the master head of the site (which exists in the...
[ "You want to use context_instance and RequestContexts. \nFirst, add at the top of your views.py:\nfrom django.template import RequestContext\n\nThen, update all of your views to look like:\ndef someview(request, ...)\n ...\n return render_to_response('viewtemplate.html', someContext, context_instance=RequestC...
[ 7, 2 ]
[ "or use a generic view, because they are automatically passed the request context.\na simple direct to template generic view can be used to avoid having to import/pass in the request context.\n" ]
[ -1 ]
[ "django", "django_templates", "python" ]
stackoverflow_0000786149_django_django_templates_python.txt
Q: Is site-packages appropriate for applications or just libraries? I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to ...
Is site-packages appropriate for applications or just libraries?
I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?
[ "We do it like this.\nMost stuff we download is in site-packages. They come from pypi or Source Forge or some other external source; they are easy to rebuild; they're highly reused; they don't change much.\nMust stuff we write is in other locations (usually under /opt, or c:\\opt) AND is included in the PYTHONPATH...
[ 4, 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000787015_python.txt
Q: How do I get the dimensions of the view (not obstructed by scrollbars) in a wx.ScrolledWindow? Is there an easy way to do this? Alternatively, if I could get the width of the scrollbars, I could just use the dimensions of the ScrolledWindow and subtract them out myself... A: Use wx.SystemSettings.GetMetric() wi...
How do I get the dimensions of the view (not obstructed by scrollbars) in a wx.ScrolledWindow?
Is there an easy way to do this? Alternatively, if I could get the width of the scrollbars, I could just use the dimensions of the ScrolledWindow and subtract them out myself...
[ "Use wx.SystemSettings.GetMetric() with wx.SYS_HSCROLL_Y and wx.SYS_VSCROLL_X to get the scrollbar sizes. Then use window.GetClientSize() and subtract it out.\nhttp://docs.wxwidgets.org/stable/wx_wxsystemsettings.html#wxsystemsettings\n>>> wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)\n16\n>>> wx.SystemSettings.Ge...
[ 4 ]
[]
[]
[ "python", "scrolledwindow", "wxpython", "wxwidgets" ]
stackoverflow_0000793381_python_scrolledwindow_wxpython_wxwidgets.txt
Q: Getting Aspen and Gheat on Windows working I am not really familiar Python setup, I am trying to get gheat running on a Windows box, and it tells me it can't find pygame. I have tried Python25,26, older pygame version too. I have installed those as well as numpy as it has a dependency. Could someone with experienc...
Getting Aspen and Gheat on Windows working
I am not really familiar Python setup, I am trying to get gheat running on a Windows box, and it tells me it can't find pygame. I have tried Python25,26, older pygame version too. I have installed those as well as numpy as it has a dependency. Could someone with experience try and help me out getting it up and running....
[ "With thanks to SeC- from the #csharp channel on Freenode, he figured out it is the problem with the latest trunk of aspen, (I thought I'd tried the older version)\nhttp://www.zetadev.com/software/aspen/0.8/dist/aspen-0.8.zip\nYou will need the 0.8 version to get it working!!\nCheers anyway!\n" ]
[ 0 ]
[]
[]
[ "aspen", "pygame", "python" ]
stackoverflow_0000793341_aspen_pygame_python.txt
Q: retrieve bounding box of a geodjango multipolygon object How can I get the bounding box of a MultiPolygon object in geodjango? Can't find anything in the API http://geodjango.org/docs/geos.html ... A: Use the extent property. It returns a 4-tuple comprising the lower left and upper right coordinates, respectivel...
retrieve bounding box of a geodjango multipolygon object
How can I get the bounding box of a MultiPolygon object in geodjango? Can't find anything in the API http://geodjango.org/docs/geos.html ...
[ "Use the extent property.\nIt returns a 4-tuple comprising the lower left and upper right coordinates, respectively.\nYou can also use the envelope property if you want a Polygon object representation of the bounding box.\n" ]
[ 14 ]
[]
[]
[ "django", "geodjango", "gis", "python" ]
stackoverflow_0000793240_django_geodjango_gis_python.txt
Q: Simple webserver or web testing framework Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http w...
Simple webserver or web testing framework
Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party ...
[ "Use cherrypy, take a look at Hello World:\nimport cherrypy\n\nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\ncherrypy.quickstart(HelloWorld())\n\nRun this code and you have a very fast Hello World server ready on localhost port 8080!! Pretty easy huh?\...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "testing", "web_applications", "web_services" ]
stackoverflow_0000776495_python_testing_web_applications_web_services.txt
Q: Accessing MultipleChoiceField choices values How do I get the choices field values and not the key from the form? I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for...
Accessing MultipleChoiceField choices values
How do I get the choices field values and not the key from the form? I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now): class Contacts(forms.ModelForm): def __i...
[ "Ok, hopefully this is closer to what you wanted.\nemails = filter(lambda t: t[0] in form.cleaned_data['emails'], form.fields['emails'].choices)\n\nThat should give you the list of selected choices that you want.\n", "It might not be a beautiful solution, but I would imagine that the display names are all still a...
[ 8, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000794178_django_python.txt
Q: Why are 0d arrays in Numpy not considered scalar? Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept? >>> foo = numpy.array(1.11111111111, numpy.float64) >>> numpy.ndim(foo) 0 >>> numpy.isscalar(foo) False >>> foo.item() 1.111111111...
Why are 0d arrays in Numpy not considered scalar?
Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept? >>> foo = numpy.array(1.11111111111, numpy.float64) >>> numpy.ndim(foo) 0 >>> numpy.isscalar(foo) False >>> foo.item() 1.11111111111
[ "One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.\nThe curious situation with Numpy scalar-types was bore out of the fact that there is no graceful and consistent way to degrade the 1x1 matrix to scalar types. Even though mathematically they are t...
[ 166, 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000773030_numpy_python.txt
Q: PyQT combobox only react on user interaction I have a listbox that you can select users in. To the left of that is a combobox listing the available groups the user can be put it. If the user is in a group, the combobox will automatically be set to that group. I want to make it so when you change the group selectio...
PyQT combobox only react on user interaction
I have a listbox that you can select users in. To the left of that is a combobox listing the available groups the user can be put it. If the user is in a group, the combobox will automatically be set to that group. I want to make it so when you change the group selection, it will move the user to that group. I added th...
[ "Catch a signal from the QComboBox (activated(int index)), and update the selected user based on that. In you Handler function, don't do anything if the selected index in the combobox is the same as the group the selected user is in.\nMaybe move your combobox to the right of the user listbox, as your order of acti...
[ 5 ]
[]
[]
[ "python", "qcombobox", "qt" ]
stackoverflow_0000794813_python_qcombobox_qt.txt
Q: How to convert datetime to string in python in django I have a datetime object at my model. I am sending it to the view, but in html i don't know what to write in order to format it. I am trying {{ item.date.strftime("%Y-%m-%d")|escape }} but I get TemplateSyntaxError: Could not parse some characters: item.date...
How to convert datetime to string in python in django
I have a datetime object at my model. I am sending it to the view, but in html i don't know what to write in order to format it. I am trying {{ item.date.strftime("%Y-%m-%d")|escape }} but I get TemplateSyntaxError: Could not parse some characters: item.date.strftime|("%Y-%m-%d")||escape when I am just using {{ it...
[ "Try using the built-in Django date format filter instead:\n{{ item.date|date:\"Y M d\" }}\n\n" ]
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000794995_django_python.txt
Q: How to compare value of 2 fields in Django QuerySet? I have a django model like this: class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() What would be the Django QuerySet equivalent of the following SQL? SELECT * FROM player WHERE batt...
How to compare value of 2 fields in Django QuerySet?
I have a django model like this: class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() What would be the Django QuerySet equivalent of the following SQL? SELECT * FROM player WHERE batting > bowling;
[ "In django 1.1 you can do the following:\nplayers = Player.objects.filter(batting__gt=F('bowling'))\n\nSee the other question for details\n" ]
[ 20 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0000795310_django_model_python.txt
Q: How do you open and transfer a file on the filesystem in mod_python? I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response: from mod_python import apache ...
How do you open and transfer a file on the filesystem in mod_python?
I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response: from mod_python import apache def handler(req): req.content_type = 'application/octet-stream' fI...
[ "To debug this kind of thing, you need to gather all information from the running mod_python instance.\nStop messing with \"checking a dozen times that it [exists]\". Some assumption isn't correct.\nDo something like this to get some debugging information.\ndef handler(req):\n req.content_type = 'text/plain'\n ...
[ 4, 0 ]
[]
[]
[ "file_io", "mod_python", "python" ]
stackoverflow_0000795837_file_io_mod_python_python.txt
Q: Wrapping a script with subprocess.Popen() I have a script that's provided with another software package - which I would not like to modify in any way. I need to execute this script, provide a password, and then interact with it from the terminal (using raw_input, etc.). A: pexpect is what you want to use. Pexpe...
Wrapping a script with subprocess.Popen()
I have a script that's provided with another software package - which I would not like to modify in any way. I need to execute this script, provide a password, and then interact with it from the terminal (using raw_input, etc.).
[ "pexpect is what you want to use.\n\nPexpect is a Python module for\n spawning child applications and\n controlling them automatically.\n Pexpect can be used for automating\n interactive applications such as ssh,\n ftp, passwd, telnet, etc. It can be\n used to a automate setup scripts for\n duplicating softw...
[ 2 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0000795977_python_scripting.txt
Q: IronPython - Convert int to byte array What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing? A: Use struct. import struct print struct.pack('L', len("some string")) # int to a (long) byte array ...
IronPython - Convert int to byte array
What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?
[ "Use struct.\nimport struct\n\nprint struct.pack('L', len(\"some string\")) # int to a (long) byte array\n\n", "using .Net: \nbyte[] buffer = System.BitConverter.GetBytes(string.Length)\nprint System.BitConverter.ToString(buffer)\n\nThat will output the bytes as hex. You may have to clean up the syntax for IronPy...
[ 4, 1 ]
[]
[]
[ ".net", "bytearray", "ironpython", "python" ]
stackoverflow_0000796197_.net_bytearray_ironpython_python.txt
Q: Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC This document by Apple Technical Q&A QA1235 describes a way to convert unicode strings from a composed to a decomposed version. Since I have a problem with file names containing some characters (e.g. an accent grave), I'd like to try the conv...
Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC
This document by Apple Technical Q&A QA1235 describes a way to convert unicode strings from a composed to a decomposed version. Since I have a problem with file names containing some characters (e.g. an accent grave), I'd like to try the conversion function void CFStringNormalize(CFMutableStringRef theString, ...
[ "OC_PythonString (which is what Python strings are bridged to) is an NSString subclass, so you could get an NSMutableString with:\nmutableString = NSMutableString.alloc().initWithString_(\"abc\")\n\nthen use mutableString as the argument to CFStringNormalize.\n" ]
[ 2 ]
[]
[]
[ "objective_c", "python" ]
stackoverflow_0000794836_objective_c_python.txt
Q: What is a good tutorial on the QuickTime API for MS Windows? I'm working on a project that has to read and manipulate QuickTimes on Windows. Unfortunately, all the tutorials and sample code at the Apple site seem to be pretty much Mac specific. Is there a good resource on the web that deals specifically with progr...
What is a good tutorial on the QuickTime API for MS Windows?
I'm working on a project that has to read and manipulate QuickTimes on Windows. Unfortunately, all the tutorials and sample code at the Apple site seem to be pretty much Mac specific. Is there a good resource on the web that deals specifically with programming QuickTime for Windows? Yes, I know that I can bludgeon my w...
[ "QuickTime For Windows starts off with the differences between Mac OS and Windows programming and Building QuickTime Capability Into a Windows Application then discusses how to incorporate the capability into Windows platform\n", "There is an official mailing list for QT developers. It has an archive. It would ce...
[ 3, 1, 0 ]
[]
[]
[ "python", "quicktime", "rebol", "windows" ]
stackoverflow_0000722315_python_quicktime_rebol_windows.txt
Q: string formatting I am not getting why the colon shifted left in the second time >>> print '%5s' %':' : >>> print '%5s' %':' '%2s' %':' : : Help me out of this please A: In Python, juxtaposed strings are concatenated: >>> t = 'a' 'bcd' >>> t 'abcd' So in your second example, it is equivalent to: >>> pr...
string formatting
I am not getting why the colon shifted left in the second time >>> print '%5s' %':' : >>> print '%5s' %':' '%2s' %':' : : Help me out of this please
[ "In Python, juxtaposed strings are concatenated:\n>>> t = 'a' 'bcd'\n>>> t\n'abcd'\n\nSo in your second example, it is equivalent to:\n>>> print '%5s' % ':%2s' % ':'\n\nwhich by the precedence rules for Python's % operator, is:\n>>> print ('%5s' % ':%2s') % ':'\n\nor\n>>> print ' :%2s' % ':'\n : :\n\n", "What are...
[ 9, 2 ]
[]
[]
[ "format", "python", "string" ]
stackoverflow_0000797132_format_python_string.txt
Q: import statement fails for one module Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help. I have a series of import statements, the last of which will not work. Any idea why? option...
import statement fails for one module
Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help. I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as ev...
[ "I suspect that one of your other imports redefined snipplets with an assignment statement. Or one of your other modules changed sys.path.\n\nEdit\n\"so the flow goes like this: add snipplets packages to path import...\" \nNo.\nDo not modify sys.path -- that way lies problems. Modifying site.path leads to ambigui...
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000797241_python.txt
Q: How to make two python programs interact? I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to: Write a script that would start the app and then the HTTP server; Make these programs exchange data in operation. How are these things usually do...
How to make two python programs interact?
I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to: Write a script that would start the app and then the HTTP server; Make these programs exchange data in operation. How are these things usually done? I would really appriciate Python solutions ...
[ "a) You can start applications using os.system:\n\nos.system(\"command\")\n\nor you can use the subprocess module. More information here.\nb) use sockets\n", "Well, you can probably just use the subprocess module. For the exchanging data, you may just be able to use the Popen.stdin and Popen.stdout streams. Of ...
[ 3, 3, 2, 1, 1, 0 ]
[]
[]
[ "interaction", "ipc", "multithreading", "process", "python" ]
stackoverflow_0000797785_interaction_ipc_multithreading_process_python.txt
Q: Running numpy from cygwin I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. This all works great when I run the Python (command line) tool that comes with Python. However, if I run cygwin and then run Python from within, it cannot find the numpy package...
Running numpy from cygwin
I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. This all works great when I run the Python (command line) tool that comes with Python. However, if I run cygwin and then run Python from within, it cannot find the numpy package. What environment variable do ...
[ "Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin.\nTo test this, try opening a bash prompt in Cygwin and typing which python to see where the Python executable is located. If it says /cygdr...
[ 4, 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000318390_numpy_python.txt
Q: Python exceptions: call same function for any Exception Notice in the code below that foobar() is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception? try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu):...
Python exceptions: call same function for any Exception
Notice in the code below that foobar() is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception? try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() except: fo...
[ "success = False\ntry:\n foo()\n success = True\nexcept(A):\n bar()\nexcept(B):\n baz()\nexcept(C):\n bay()\nfinally:\n if not success:\n foobar()\n\n", "You can use a dictionary to map exceptions against functions to call:\nexception_map = { ErrorTypeA : bar, ErrorTypeB : baz }\ntry:\n ...
[ 18, 12 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000799293_exception_python.txt
Q: Returning an object vs returning a tuple I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. My question is relative to the design of a getCoordinate(index) method. Should I return a tup...
Returning an object vs returning a tuple
I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object? In the firs...
[ "Compromise solution: Instead of a class, make Coord3D a namedtuple and return that :-)\nUsage:\nCoord3D = namedtuple('Coord3D', 'x y z')\n\ndef getCoordinate(index):\n # do stuff, creating variables x, y, z\n return Coord3D(x, y, z)\n\nThe return value can be used exactly as a tuple, and has the same speed a...
[ 13, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000794132_python.txt
Q: Print long integers in python If I run this where vote.created_on is a python datetime: import calendar created_on_timestamp = calendar.timegm(vote.created_on.timetuple())*1000 created_on_timestamp = str(created_on_timestamp) created_on_timestamp will be printed with encapsulating tick marks ('). If I do int() o...
Print long integers in python
If I run this where vote.created_on is a python datetime: import calendar created_on_timestamp = calendar.timegm(vote.created_on.timetuple())*1000 created_on_timestamp = str(created_on_timestamp) created_on_timestamp will be printed with encapsulating tick marks ('). If I do int() or something like that, I'll get som...
[ ">>> i = 1240832864000L\n>>> i\n1240832864000L\n>>> print i\n1240832864000\n>>> \n>>> '<script type=\"text/javascript\"> var num = %s; </script>' % i\n'<script type=\"text/javascript\"> var num = 1240832864000; </script>'\n\nThe L only shows up when you trigger the object's __repr__\nWhen and how are you sending th...
[ 5, 4 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0000799434_datetime_django_python.txt
Q: Python HTML output (first attempt), several questions (code included) While I have been playing with Python for a few months now (just a hobbyist), I know very little about Web programming (a little HTML, zero JavaScript, etc). That said, I have a current project that is making me look at web programming for the ...
Python HTML output (first attempt), several questions (code included)
While I have been playing with Python for a few months now (just a hobbyist), I know very little about Web programming (a little HTML, zero JavaScript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask: What's easiest way to get Python script ou...
[ "It would not be overkill to use a framework for something like this; Python frameworks tend to be very light and easy to work with and would make it much easier for you to add features to your tiny site. But neither is it required; I'll assume you're doing this for learning purposes and talk about how I would chan...
[ 8, 5, 4, 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0000799479_javascript_python.txt
Q: Correlate one set of vectors to another in numpy? Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed fi...
Correlate one set of vectors to another in numpy?
Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type). What is the cle...
[ "The simplest thing that I could find was using the scipy.stats package\nIn [8]: x\nOut[8]: \narray([[ 0. , 0. , 0. ],\n [-1. , 0. , -1. ],\n [-2. , 0. , -2. ],\n [-3. , 0. , -3. ],\n [-4. , 0.1, -4. ]])\nIn [9]: y\nOut[9]: \narray([[0. , 0. ],\n [1. , 0. ],\n [2. , 0. ],\n...
[ 2, 1 ]
[ "As David said, you should define the correlation you're using. I don't know of any definitions of correlation that gives sensible numbers when correlating empty and non-empty signals.\n" ]
[ -1 ]
[ "numpy", "python" ]
stackoverflow_0000795570_numpy_python.txt
Q: keeping same formatting for floating point values I have a python program that reads floating point values using the following regular expression (-?\d+\.\d+) once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.23...
keeping same formatting for floating point values
I have a python program that reads floating point values using the following regular expression (-?\d+\.\d+) once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.2345678 or 1.234 or 1.2340000. The problem I am facing is...
[ "If you want to keep a fixed precision, avoid using floats and use Decimal instead:\n>>> from decimal import Decimal\n>>> d = Decimal('-1.2345')\n>>> str(d)\n'-1.2345'\n>>> float(d)\n-1.2344999999999999\n\n", "You method is basically correct. \nString formatting has a less often used * operator you can put for th...
[ 8, 3, 1 ]
[]
[]
[ "floating_point", "formatting", "python" ]
stackoverflow_0000800015_floating_point_formatting_python.txt
Q: Best Python podcasts? Could any one suggest good Python-related podcasts out there, it could be anything about Python or its eco-system (like django, pylons, etc). A: Google Code University (several languages there) Python Podcasts Python Learning Foundation Python411 on PodcastAlley.com A: I didn't think much...
Best Python podcasts?
Could any one suggest good Python-related podcasts out there, it could be anything about Python or its eco-system (like django, pylons, etc).
[ "Google Code University (several languages there)\nPython Podcasts\nPython Learning Foundation\nPython411 on PodcastAlley.com\n", "I didn't think much of Python411 - the episode I downloaded primarily consisted of the host talking about how he was planning on writing a GAE site.\nThis Week in Django as pointed ou...
[ 23, 4, 3, 2, 2 ]
[]
[]
[ "podcast", "python" ]
stackoverflow_0000791618_podcast_python.txt
Q: Updating data in google app engine I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model: class Player(db.Model): """ Represents a player in the club. """ first_name = db.StringProperty() surname = db.StringProperty() ...
Updating data in google app engine
I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model: class Player(db.Model): """ Represents a player in the club. """ first_name = db.StringProperty() surname = db.StringProperty() gender = db.StringProperty() I want...
[ "On each request you are working on a new instance of the same class. That's why you can't create a varable in get() and use its value in post(). What you could do is either retrieve the values again in your post()-method or store the data in the memcache.\nRefer to the documentation of memcache here:\nhttp://code....
[ 2, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000801477_google_app_engine_python.txt
Q: Memory efficiency: One large dictionary or a dictionary of smaller dictionaries? I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store. I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smalle...
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store. I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the s...
[ "Three suggestions:\n\nUse one dictionary.\nIt's easier, it's more straightforward, and someone else has already optimized this problem for you. Until you've actually measured your code and traced a performance problem to this part of it, you have no reason not to do the simple, straightforward thing.\nOptimize la...
[ 82, 16, 8, 7, 5, 2, 1 ]
[]
[]
[ "dictionary", "memory", "performance", "python" ]
stackoverflow_0000671403_dictionary_memory_performance_python.txt
Q: Is Python faster and lighter than C++? I've always thought that Python's advantages are code readibility and development speed, but time and memory usage were not as good as those of C++. These stats struck me really hard. What does your experience tell you about Python vs C++ time and memory usage? A: I think y...
Is Python faster and lighter than C++?
I've always thought that Python's advantages are code readibility and development speed, but time and memory usage were not as good as those of C++. These stats struck me really hard. What does your experience tell you about Python vs C++ time and memory usage?
[ "I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.\nMy experiences with Python show the same definite trend that Python is ...
[ 273, 143, 26, 15, 8, 6, 4, 2 ]
[]
[]
[ "c++", "memory", "performance", "python", "statistics" ]
stackoverflow_0000801657_c++_memory_performance_python_statistics.txt
Q: Python selecting a value in a combo box and HTTP POST In Python, I'm trying to read the values on http://utahcritseries.com/RawResults.aspx. How can I read years other than the default of 2002? So far, using mechanize, I've been able to reference the SELECT and list all of its available options/values but am unsu...
Python selecting a value in a combo box and HTTP POST
In Python, I'm trying to read the values on http://utahcritseries.com/RawResults.aspx. How can I read years other than the default of 2002? So far, using mechanize, I've been able to reference the SELECT and list all of its available options/values but am unsure how to change its value and resubmit the form. I'm sure ...
[ "So how about this:\nfrom mechanize import Browser\nyear=\"2005\"\n\nbr=Browser()\nbr.open(\"http://utahcritseries.com/RawResults.aspx\")\nbr.select_form(name=\"aspnetForm\")\ncontrol=br.form.find_control(\"ctl00$ContentPlaceHolder1$ddlSeries\")\ncontrol.set_value_by_label((year,))\nresponse2=br.submit()\n\nprint r...
[ 1, 0 ]
[]
[]
[ "asp.net", "http", "python", "web_scraping" ]
stackoverflow_0000769948_asp.net_http_python_web_scraping.txt
Q: how can I debug more than one script in pyscripter? I installed portable python on my USB drive, and I really like pyscripter a lot. The thing is, after I start debugging a script, the IDE kind of freezes ( waiting for the code to reach a breakpoint ). This means I can't do anything with it ( I can't even save fil...
how can I debug more than one script in pyscripter?
I installed portable python on my USB drive, and I really like pyscripter a lot. The thing is, after I start debugging a script, the IDE kind of freezes ( waiting for the code to reach a breakpoint ). This means I can't do anything with it ( I can't even save files ). It would be very useful to be able to debug more th...
[ "To solve your problem, use Remote Interpreter and Debugger and PyScripter will become much more responsive. Even if something goes wrong, IDE will not crash - just reinitialize remote interpreter and resume working.\n" ]
[ 1 ]
[]
[]
[ "debugging", "ide", "pyscripter", "python" ]
stackoverflow_0000797754_debugging_ide_pyscripter_python.txt
Q: Notifying container object: best practices I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well. I think of three alternatives on how to achieve this: 1) Hold...
Notifying container object: best practices
I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well. I think of three alternatives on how to achieve this: 1) Hold a reference within Operator to the container [A...
[ "You're over-thinking this. Seriously. Python isn't C++; your concerns are non-issues in Python. Just write what makes sense in your problem domain.\n\" Not absolutely good because of circular references.\"\nWhy not? Circularity is of no relevance here at all. Bidirectional relationships are great things. Use...
[ 5, 3, 3, 3, 0 ]
[]
[]
[ "architecture", "containers", "notifications", "python" ]
stackoverflow_0000801931_architecture_containers_notifications_python.txt
Q: Using Twisted's twisted.web classes, how do I flush my outgoing buffers? I've made a simple http server using Twisted, which sends the Content-Type: multipart/x-mixed-replace header. I'm using this to test an http client which I want to set up to accept a long-term stream. The problem that has arisen is that my cl...
Using Twisted's twisted.web classes, how do I flush my outgoing buffers?
I've made a simple http server using Twisted, which sends the Content-Type: multipart/x-mixed-replace header. I'm using this to test an http client which I want to set up to accept a long-term stream. The problem that has arisen is that my client request hangs until the http.Request calls self.finish(), then it receive...
[ "Using time.sleep() prevents twisted from doing its job. To make it work you can't use time.sleep(), you must return control to twisted instead. The easiest way to modify your existing code to do that is by using twisted.internet.defer.inlineCallbacks, which is the next best thing since sliced bread:\n#!/usr/bin/en...
[ 10, 1 ]
[]
[]
[ "multipart_mixed_replace", "python", "twisted" ]
stackoverflow_0000776631_multipart_mixed_replace_python_twisted.txt
Q: Database Reporting Services in Django or Python I am wondering if there are any django based, or even Python Based Reporting Services ala JasperReports or SQL Server Reporting Services? Basically, I would love to be able to create reports, send them out as emails as CSV or HTML or PDF without having to code the re...
Database Reporting Services in Django or Python
I am wondering if there are any django based, or even Python Based Reporting Services ala JasperReports or SQL Server Reporting Services? Basically, I would love to be able to create reports, send them out as emails as CSV or HTML or PDF without having to code the reports. Even if I have to code the report I wouldn't m...
[ "\"I would love to be able to create reports ... without having to code the reports\" \nSo would I. Sadly, however, each report seems to be unique and require custom code.\nFrom Django model to CSV is easy. Start there with a few of your reports.\nimport csv\nfrom myApp.models import This, That, TheOther\ndef pa...
[ 4, 3 ]
[]
[]
[ "django", "python", "reporting_services" ]
stackoverflow_0000793130_django_python_reporting_services.txt
Q: SQLAlchemy many-to-many orphan deletion I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users. When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlch...
SQLAlchemy many-to-many orphan deletion
I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users. When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simp...
[ "The way I've generally handled this is to have a function on your user or group called leave_group. When you want a user to leave a group, you call that function, and you can add any side effects you want into there. In the long term, this makes it easier to add more and more side effects. (For example when you...
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000740630_python_sqlalchemy.txt
Q: python - readable list of objects This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the; <__main__.evolutions instance at 0x01B8EA08> but instead ...
python - readable list of objects
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the; <__main__.evolutions instance at 0x01B8EA08> but instead to show a selected attribute of a chose...
[ "If you want to just display a particular attribute of each class instance, you can do\nprint([obj.attr for obj in my_list_of_objs])\n\nWhich will print out the attr attribute of each object in the list my_list_of_objs. Alternatively, you can define the __str__() method for your class, which specifies how to conve...
[ 8, 4, 4, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000444058_list_python.txt
Q: Inserting multiple model instances using a single db.put() on Google App Engine Edit: Sorry I didn't clarify this, it's a Google App Engine related question. According to this, I can give db.put() a list of model instances and ask it to input them all into the datastore. However, I haven't been able do this succes...
Inserting multiple model instances using a single db.put() on Google App Engine
Edit: Sorry I didn't clarify this, it's a Google App Engine related question. According to this, I can give db.put() a list of model instances and ask it to input them all into the datastore. However, I haven't been able do this successfully. I'm still a little new with Python, so go easy on me list_of_models = [] for ...
[ "Please define what you mean by \"going wrong\" -- the tiny pieces of code you're showing could perfectly well be part of an app that's quite \"right\". Consider e.g.:\nclass Hello(db.Model):\n name = db.StringProperty()\n when = db.DateTimeProperty()\n\nclass MainHandler(webapp.RequestHandler):\n\n def get(sel...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000803517_google_app_engine_python.txt
Q: How to get last inserted item key in Google App Engine I am working with Google App Engine and Python. I have a model with Items. Immediately after I insert an item with item.put() I want to get it's key and redirect to a page using this key. Something like: redirectUrl = "/view/key/%s/" % item.key self.redirect(r...
How to get last inserted item key in Google App Engine
I am working with Google App Engine and Python. I have a model with Items. Immediately after I insert an item with item.put() I want to get it's key and redirect to a page using this key. Something like: redirectUrl = "/view/key/%s/" % item.key self.redirect(redirectUrl)
[ "Also, item.put() returns the key as the result, so it's hardly ever necessary to fetch that key immediately again -- just change your sequence, e.g\n item.put()\n redirectUrl = \"/view/key/%s/\" % item.key()\n\ninto\n k = item.put()\n redirectUrl = \"/view/key/%s/\" % k\n\n", "After you did you put() you can...
[ 4, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000799803_google_app_engine_python.txt
Q: Django caching - can it be done pre-emptively? I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup. This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after ...
Django caching - can it be done pre-emptively?
I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup. This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant d...
[ "So you want to schedule something to run at a regular interval? At the cost of some CPU time, you can use this simple app.\nAlternatively, if you can use it, the cron job for every 5 minutes is:\n*/5 * * * * /path/to/project/refresh_cache.py\n\nWeb hosts provide different ways of setting these up. For cPanel, us...
[ 8, 4, 4, 0 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0000797773_caching_django_python.txt
Q: How can I get the results of a Perl script in Python script? I have one script in Perl and the other in Python. I need to get the results of Perl in Python and then give the final report. The results from Perl can be scalar variable, hash variable, or an array. Please let me know as soon as possible regarding this...
How can I get the results of a Perl script in Python script?
I have one script in Perl and the other in Python. I need to get the results of Perl in Python and then give the final report. The results from Perl can be scalar variable, hash variable, or an array. Please let me know as soon as possible regarding this.
[ "Use the subprocess module to run your Perl script to capture its output:\nYou can format the output however you choose in either script, and use Python to print the final report. For example: your Perl script can output XML which can be parsed by the Python script and then printed using a different format.\n", ...
[ 6, 3, 2 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0000805160_perl_python.txt
Q: Learning Graphical Layout Algorithms During my day-to-day work, I tend to come across data that I want to visualize in a custom manner. For example, automatically creating a call graph similar to a UML sequence diagram, display digraphs, or visualizing data from a database (scatter plots, 3D contours, etc). For g...
Learning Graphical Layout Algorithms
During my day-to-day work, I tend to come across data that I want to visualize in a custom manner. For example, automatically creating a call graph similar to a UML sequence diagram, display digraphs, or visualizing data from a database (scatter plots, 3D contours, etc). For graphs, I tend to use GraphViz. For UML-li...
[ "Here are some sources,\n\nGraphic Layout and Design (Paperback).\nActive Layout Engine: Algorithms and Applications in Variable\nData Printing\n\n" ]
[ 2 ]
[]
[]
[ "c++", "graphics", "layout", "python", "visualization" ]
stackoverflow_0000805356_c++_graphics_layout_python_visualization.txt
Q: Sphinx automated image numbering/captions? Is there a way to automatically generate an image/figure caption using sphinx? I currently have rest-sphinx files I'm converting to html and (latex)pdf using sphinx. I'd like an easy way for users to reference a specific image in the resulting html/pdf files. For example,...
Sphinx automated image numbering/captions?
Is there a way to automatically generate an image/figure caption using sphinx? I currently have rest-sphinx files I'm converting to html and (latex)pdf using sphinx. I'd like an easy way for users to reference a specific image in the resulting html/pdf files. For example, if a user is refering to the documentation in a...
[ "Sphinx consumes reStructuredText as templated by Jinja. According to the Sphinx documentation though, you have other templating options.\nYou should be able to use Jinja's control structures in a custom template to achieve the effect you're after.\n" ]
[ 2 ]
[]
[]
[ "python", "python_sphinx", "templates" ]
stackoverflow_0000805943_python_python_sphinx_templates.txt
Q: How to improve Trac's performance I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN). Setup Info: This is via a SELinux system hosted by WebFaction. It is behind A...
How to improve Trac's performance
I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN). Setup Info: This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. C...
[ "It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like mod_python, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using mod_python...
[ 5, 3, 2, 1 ]
[]
[]
[ "performance", "python", "trac" ]
stackoverflow_0000213838_performance_python_trac.txt
Q: Python equivalent of Perl's while (<>) {...}? I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use while (<>) { do stuff; } This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this if len(sys.argv) == 2: # there's a command ...
Python equivalent of Perl's while (<>) {...}?
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use while (<>) { do stuff; } This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for...
[ "The fileinput module in the standard library is just what you want:\nimport fileinput\n\nfor line in fileinput.input(): ...\n\n", "import fileinput\nfor line in fileinput.input():\n process(line)\n\nThis iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty....
[ 51, 15, 7 ]
[]
[]
[ "python", "stdin" ]
stackoverflow_0000807173_python_stdin.txt