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: gaema twitter handle error i use gaema for twitter user loggin http://code.google.com/p/gaema/ and my code is : class TwitterAuth(WebappAuth, auth.TwitterMixin): pass class TwitterHandler(BaseHandler): def get(self): twitter_auth = TwitterAuth(self) try: if self.request.GET.get...
gaema twitter handle error
i use gaema for twitter user loggin http://code.google.com/p/gaema/ and my code is : class TwitterAuth(WebappAuth, auth.TwitterMixin): pass class TwitterHandler(BaseHandler): def get(self): twitter_auth = TwitterAuth(self) try: if self.request.GET.get("oauth_token", None): ...
[ "http://www.google.com/codesearch?q=%22def+require_setting%22+package:http://gaema.googlecode.com&hl=en\nThis is a bug. They should be using \"self\" as the first argument to require_settings.\nI see it's already been reported @ http://code.google.com/p/gaema/issues/detail?id=6\n" ]
[ 1 ]
[]
[]
[ "gaema", "google_app_engine", "python", "twitter" ]
stackoverflow_0002870893_gaema_google_app_engine_python_twitter.txt
Q: How can I implement this Python snippet in Java? I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments. Here is the code: def ternarySearch(f, left, right, absolutePrecision): #left and ...
How can I implement this Python snippet in Java?
I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments. Here is the code: def ternarySearch(f, left, right, absolutePrecision): #left and right are the current bounds; the maximum is between t...
[ "In Java, there are no higher-order functions. That is, you can't pass a function as an argument to another function. What you can do is use the Command pattern; define an Interface supporting the method that you need, then pass an instance of that Interface implementing the method.\nFor example:\nint ternarySear...
[ 8 ]
[]
[]
[ "function", "java", "python" ]
stackoverflow_0002874487_function_java_python.txt
Q: How to write this snippet in Python? I am learning Python (I have a C/C++ background). I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic...
How to write this snippet in Python?
I am learning Python (I have a C/C++ background). I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic of what I want to do. BTW I am using pyth...
[ "to get the value from the dictionary you need to use .get method of the dict:\n>>> d = {1: 2}\n>>> d.get(1, 3)\n2\n>>> d.get(5, 3)\n3\n\nThis will remove the need for getItemValue function. I wont' comment on the existing syntax since it's clearly alien to Python. Correct syntax for the ternary in Python is:\ntrue...
[ 5, 2, 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0002874270_postgresql_python.txt
Q: Is it possible to use template tags in ValidationError's strings? I need to throw ValidationError containing anchor. if not profile.activated(): raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.') What I need to modify to make this work?...
Is it possible to use template tags in ValidationError's strings?
I need to throw ValidationError containing anchor. if not profile.activated(): raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.') What I need to modify to make this work?
[ "Why do you want to use a template tag here? Template tags are for use in templates. If you want to find a reverse URL, use the reverse function.\n", "First: just don't do this! Put HTML code where it belongs: into the template.\nSecond: you might be able to do this with \nfrom django.template import Context, Tem...
[ 3, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python", "validation" ]
stackoverflow_0002874324_django_django_forms_django_templates_python_validation.txt
Q: PyQt Drag and Drop - Nothing happens I'm trying to get drop a file onto a Window (I've tried the same thing with a QListWidget without success there too) test.py: #! /usr/bin/python # Test from PyQt4 import QtCore, QtGui import sys from qt_test import Ui_MainWindow class MyForm(QtGui.QMainWindow, Ui_MainWindow): ...
PyQt Drag and Drop - Nothing happens
I'm trying to get drop a file onto a Window (I've tried the same thing with a QListWidget without success there too) test.py: #! /usr/bin/python # Test from PyQt4 import QtCore, QtGui import sys from qt_test import Ui_MainWindow class MyForm(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): ...
[ "Yes. Well... sort of.\nDragging plain text from an editor worked fine for me, as for files...\nWhen you drop a file onto your app, it's type is \"text/uri-list\". For this you will want to use the event.mimeData().urls() method to get a list of PyQt4.QtCore.QUrl objects.\nYou will need to handle different mime da...
[ 3 ]
[]
[]
[ "drag_and_drop", "pyqt", "python" ]
stackoverflow_0002871663_drag_and_drop_pyqt_python.txt
Q: Catching single-character input on stdin while outputting to stdout in Python I'm writing a simple dual timer in Python. (I'm running Linux, and this should only need to run on my system.) The idea is that the script has two separate timers, one of which is running at any one time. The user should be able to press...
Catching single-character input on stdin while outputting to stdout in Python
I'm writing a simple dual timer in Python. (I'm running Linux, and this should only need to run on my system.) The idea is that the script has two separate timers, one of which is running at any one time. The user should be able to press a button to either switch which timer is running, or pause both. Currently, the te...
[ "See this SO question and this article.\nBoth of those describe either platform-specific options or using something like pygame.\nHowever, if you need a cross-platform solution that doesn't require any external dependencies (e.g. pygame), I think you should also be able to do it through the threading module in the ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002874469_python.txt
Q: Why subtract a value from itself (x - x) in Python? In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do? t,w = asarray(t), asa...
Why subtract a value from itself (x - x) in Python?
In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do? t,w = asarray(t), asarray(duty) w = asarray(w + (t-t)) t = asarray(t + (w-w)) ...
[ "I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.\n" ]
[ 14 ]
[]
[]
[ "numpy", "python", "type_conversion" ]
stackoverflow_0002875024_numpy_python_type_conversion.txt
Q: Wizard Page load event in wxWizard I'm using a wxWizard control. I know about the on EVT_WIZARD_PAGE_CHANGED and the EVT_WIZARD_PAGE_CHANGING events but could anyone please tell me how to trigger an event when a particular wizard page loads? Thanks. A: from the Wxwizard.py example included with wx distribution ...
Wizard Page load event in wxWizard
I'm using a wxWizard control. I know about the on EVT_WIZARD_PAGE_CHANGED and the EVT_WIZARD_PAGE_CHANGING events but could anyone please tell me how to trigger an event when a particular wizard page loads? Thanks.
[ "from the Wxwizard.py example included with wx distribution\n def OnWizPageChanged(self, evt):\n if evt.GetDirection():\n dir = \"forward\"\n else:\n dir = \"backward\"\n\n page = evt.GetPage()\n self.log.write(\"OnWizPageChanged: %s, %s\\n\" % (dir, page.__class__))\n\nThis could be modif...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002873171_python_wxpython.txt
Q: How can I put all twill commands together into one piece of code in a .py file? I have just started exploring TWILL. Twill is an amazing scripting language for Web browsing and it does all I want!!! So far I've been using twill from a Python shell (IDLE (Python GUI) to be precise) and I do things there in the way...
How can I put all twill commands together into one piece of code in a .py file?
I have just started exploring TWILL. Twill is an amazing scripting language for Web browsing and it does all I want!!! So far I've been using twill from a Python shell (IDLE (Python GUI) to be precise) and I do things there in the way of executing commands one by one (I mean, I type one command, run it, then type the ...
[ "Put your twill commands into a file, for example test.twill\nsetlocal query \"twill Python\"\n\ngo http://google.com/\n\nfv 1 q $query\nsubmit btnI # use the \"I'm feeling lucky\" button\n\nshow\n\nAnd then just pass filename as parameter to twill-sh command, like\npython twill-sh test.twill\n\nAnd you might w...
[ 3, 3, 2, 1 ]
[]
[]
[ "command", "python", "twill" ]
stackoverflow_0002688408_command_python_twill.txt
Q: How to combine twill and python into one code that could be run on "Google App Engine"? I have installed twill on my computer (having previously installed Python 2.5) and have been using it recently. Python is installed on disk C on my computer: C:\Python25 And the twill folder (“twill-0.9”) is located here: E:\t...
How to combine twill and python into one code that could be run on "Google App Engine"?
I have installed twill on my computer (having previously installed Python 2.5) and have been using it recently. Python is installed on disk C on my computer: C:\Python25 And the twill folder (“twill-0.9”) is located here: E:\tmp\twill-0.9 Here is a code that I’ve been using in twill: go “some website’s sign-in page U...
[ "here is an example of using twill to run a google search if this helps. It shows using twill and beautifulsoup together to parse web pages:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> \n>>> class browser:\n... def __init__(self, url=\"http://www.google.com\",log = None):\n... self.a=twill.co...
[ 3, 1, 1, 1 ]
[]
[]
[ "google_app_engine", "import", "python", "twill" ]
stackoverflow_0002717325_google_app_engine_import_python_twill.txt
Q: Resolving a relative path from py:match in a genshi template <py:match path="foo"> <?python import os href = select('@href').render() SOMEWHERE = ... # what file contained the foo tag? path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href) f = file(path,'...
Resolving a relative path from py:match in a genshi template
<py:match path="foo"> <?python import os href = select('@href').render() SOMEWHERE = ... # what file contained the foo tag? path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href) f = file(path,'r') # (do something interesting with f) ?> </py:match>...
[ "You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the foo tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as ...
[ 1 ]
[]
[]
[ "genshi", "python", "relative_path" ]
stackoverflow_0001024475_genshi_python_relative_path.txt
Q: Testing with Unittest Python I am runninig test's with Python Unittest. I am running tests but I want to do negative testing and I would like to test if a function throw's an exception, it passes but if no exception is thrown the test fail's. The script I have is: try: result = self.client.service.GetS...
Testing with Unittest Python
I am runninig test's with Python Unittest. I am running tests but I want to do negative testing and I would like to test if a function throw's an exception, it passes but if no exception is thrown the test fail's. The script I have is: try: result = self.client.service.GetStreamUri(self.stream, self.token) ...
[ "TestCase.assertRaises is what you need however in your example you appear to be misusing it slightly. You need something like:\ndef test_GetStreamUri(self):\n self.assertRaises(WebFault, self.client.service.GetStreamUri)\n result = self.client.service.GetStreamUri(self.stream, self.token)\n\nYou need to tell...
[ 5, 1, 1, 0 ]
[]
[]
[ "exception", "python", "testing", "unit_testing" ]
stackoverflow_0002874753_exception_python_testing_unit_testing.txt
Q: How do I parse a templated string in Python? I'm new to Python, so I'm not sure exactly what this operation is called, hence I'm having a hard time searching for information in it. Basically I'd like to have a string such as: "[[size]] widget that [[verb]] [[noun]]" Where size, verb, and noun are each a list. I'd...
How do I parse a templated string in Python?
I'm new to Python, so I'm not sure exactly what this operation is called, hence I'm having a hard time searching for information in it. Basically I'd like to have a string such as: "[[size]] widget that [[verb]] [[noun]]" Where size, verb, and noun are each a list. I'd like to interpret the string as a metalanguage, s...
[ "If you change your syntax to\n\"{size} widget that {verb} {noun}\"\n\nThen you could use string's format method to do the substitutions:\n\"{size} widget that {verb} {noun}\".format(size='Tiny',verb='pounds',noun='nails')\n\nor \nchoice={'size':'Big',\n 'verb':'plugs',\n 'noun':'holes'}\n\"{size} widget that...
[ 7, 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002869128_python.txt
Q: Preprocess SHPAML in Django's template loader? Is there any way to make Django's template loader run all templates it loads (i.e. directly or via extend/include) through SHPAML if it figures the HTML is out of date? I know how to invoke SHPAML recursively over an entire directory, but I would prefer to be able to ...
Preprocess SHPAML in Django's template loader?
Is there any way to make Django's template loader run all templates it loads (i.e. directly or via extend/include) through SHPAML if it figures the HTML is out of date? I know how to invoke SHPAML recursively over an entire directory, but I would prefer to be able to run it on demand so I don't have to remember to sync...
[ "I suspect you can achieve what you want by inheriting from django.template.loaders.app_directories.Loader (or whatever loader you use) and overwriting the load_template_source method, e.g.:\nfrom django.template.loaders.app_directories import Loader\nfrom shpaml import convert_text\n\nclass SHPAMLLoader(Loader):\n...
[ 3, 1 ]
[]
[]
[ "django", "preprocessor", "python", "shpaml", "templates" ]
stackoverflow_0002131029_django_preprocessor_python_shpaml_templates.txt
Q: How can I create a GUI on top of a Python APP so it can do either GUI or CLI? I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base? I assume there will be mo...
How can I create a GUI on top of a Python APP so it can do either GUI or CLI?
I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base? I assume there will be more code, but is there a simple way of detecting something like GTK, so it only appl...
[ "\nis there a simple way of detecting something like GTK, so it only applied the code when GTK was present?\n\nFirst, break your app into 3 separate modules.\n\nThe actual work: foo_core.py.\nA CLI module that imports foo_core. Call it foo_cli.py.\nA GUI module that imports foo_core. Call it foo_gui.pyw. \n\nThe ...
[ 12, 1, 0, 0 ]
[]
[]
[ "glade", "gtk", "python", "user_interface", "xml" ]
stackoverflow_0002857634_glade_gtk_python_user_interface_xml.txt
Q: cx_Freeze and PYC/PYD files I'm using cx_Freeze to freeze my python program. On running cx_Freeze, a bunch of PYD files are created, a whole bunch of PYC files are put into a archive named library.zip and a few DLL files are there too. Could someone tell me the difference between the PYC and the PYD files? What's ...
cx_Freeze and PYC/PYD files
I'm using cx_Freeze to freeze my python program. On running cx_Freeze, a bunch of PYD files are created, a whole bunch of PYC files are put into a archive named library.zip and a few DLL files are there too. Could someone tell me the difference between the PYC and the PYD files? What's the reason for the PYD files not ...
[ "Disclaimer: I haven't used cx_Freeze in awhile......\n.PYD files are DLL machine-code files that contain specific python-required functions. \n.PYC files are .py files that have been compiled into bytecode.\nso PYDs are machine code and PYCs are bytecode\nNow as for why the PYDs aren't in the .zip....I'd imagine i...
[ 6 ]
[]
[]
[ "cx_freeze", "python" ]
stackoverflow_0002875530_cx_freeze_python.txt
Q: Shuttle control in wxPython I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this: alt text http://knol.google.com/k/-/-/153594c4goidl/p559ta/picture-52.png I've got two listboxes — one's populated, one'...
Shuttle control in wxPython
I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this: alt text http://knol.google.com/k/-/-/153594c4goidl/p559ta/picture-52.png I've got two listboxes — one's populated, one's not. Could someone show me how ...
[ "i don't know what a shuttle control is exactly, maybe for videos? maybe this will help\n# in your init method\nself.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.mainlist)\n\n\n# the callback\ndef EvtListBoxDClick(self, event):\n self.otherlist.Append(self.mainlist.GetSelection())\n self.mainlist...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002871762_python_wxpython.txt
Q: Does setup.py's extras_require keyword support comma-separated extras? Setuptools lets you list requirements for optional features # mypackage 'extras_require' : { 'PDF' : ['reportlab'], 'DOCX' : ['docxlib'] } and another package can specify 'requires' : [ 'mypackage[PDF]' ]. If another package wants to require m...
Does setup.py's extras_require keyword support comma-separated extras?
Setuptools lets you list requirements for optional features # mypackage 'extras_require' : { 'PDF' : ['reportlab'], 'DOCX' : ['docxlib'] } and another package can specify 'requires' : [ 'mypackage[PDF]' ]. If another package wants to require more than one extra from the first package, can it ask for 'requires' : [ 'my...
[ "from: http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies\nsetuptools and pkg_resources use a common syntax for specifying a project's required dependencies. This syntax consists of a project's PyPI name, optionally followed by a comma-separated list of \"extras\" in square brackets, optional...
[ 6 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0002321798_distutils_python_setuptools.txt
Q: What's the fastest way to strip and replace a document of high unicode characters using Python? I am looking to replace from a large document all high unicode characters, such as accented Es, left and right quotes, etc., with "normal" counterparts in the low range, such as a regular 'E', and straight quotes. I nee...
What's the fastest way to strip and replace a document of high unicode characters using Python?
I am looking to replace from a large document all high unicode characters, such as accented Es, left and right quotes, etc., with "normal" counterparts in the low range, such as a regular 'E', and straight quotes. I need to perform this on a very large document rather often. I see an example of this in what I think mig...
[ "# -*- encoding: utf-8 -*-\nimport unicodedata\n\ndef shoehorn_unicode_into_ascii(s):\n return unicodedata.normalize('NFKD', s).encode('ascii','ignore')\n\nif __name__=='__main__':\n s = u\"éèêàùçÇ\"\n print(shoehorn_unicode_into_ascii(s))\n # eeeaucC\n\nNote, as @Mark Tolonen kindly points out, the met...
[ 8, 4, 3, 1, 0 ]
[]
[]
[ "ascii", "parsing", "python", "text_processing", "unicode" ]
stackoverflow_0002854230_ascii_parsing_python_text_processing_unicode.txt
Q: Django startup problems This is something similar to what's posted here: No Module named django.core To reiterate, I'm getting this error on running "django-admin.py startproject mysite"(without the double quotes): C:\Documents and Settings\fixavier\Desktop>django-admin.py startproject mysite Traceback (most recen...
Django startup problems
This is something similar to what's posted here: No Module named django.core To reiterate, I'm getting this error on running "django-admin.py startproject mysite"(without the double quotes): C:\Documents and Settings\fixavier\Desktop>django-admin.py startproject mysite Traceback (most recent call last): File "C:\Prog...
[ "What happens if you try to import django from the Python shell? Type python at a command prompt, then type import django at the next prompt. I'm not familiar with BitNami, but you might want to consider just installing Django the normal way. Otherwise you're going to have a hard time getting answers to issues via ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002877071_django_python.txt
Q: Problems with i18n using django translation on App-Engine with Korean and Hindi I've got a setup based on the post here, and it works perfectly. Adding more languages to the mix, it recognises them fine, except for Korean (ko) and Hindi (hi). Chinese/Japanese/Hebrew are all fine, so nothing to do with encodings/ch...
Problems with i18n using django translation on App-Engine with Korean and Hindi
I've got a setup based on the post here, and it works perfectly. Adding more languages to the mix, it recognises them fine, except for Korean (ko) and Hindi (hi). Chinese/Japanese/Hebrew are all fine, so nothing to do with encodings/charsets I don't think. Taking a look into the django code inside the app-engine SDK, I...
[ "My guess is you are hitting the 'locale restriction' listed here: http://docs.djangoproject.com/en/dev/topics/i18n/localization/#id1 that since 0.96 didn't have translations for Django in those languages, Django is not letting you translate your app.\nI think it is probably easiest to use django 1.1, which does ha...
[ 3 ]
[]
[]
[ "django", "google_app_engine", "internationalization", "python" ]
stackoverflow_0002876494_django_google_app_engine_internationalization_python.txt
Q: Parameters for find function I'm using beautiful soup (in Python). I have such hidden input object: <input type="hidden" name="form_build_id" id="form-531f740522f8c290ead9b88f3da026d2" value="form-531f740522f8c290ead9b88f3da026d2" /> I need in id/value. Here is my code: mainPageData = cookieOpener.open('http://p...
Parameters for find function
I'm using beautiful soup (in Python). I have such hidden input object: <input type="hidden" name="form_build_id" id="form-531f740522f8c290ead9b88f3da026d2" value="form-531f740522f8c290ead9b88f3da026d2" /> I need in id/value. Here is my code: mainPageData = cookieOpener.open('http://page.com').read() soupHandler = Bea...
[ "Try using the alternative attrs keyword:\nareaId = soupHandler.find('input', attrs={'name':'form_build_id', 'type':'hidden'})\n\n\nYou can't use a keyword argument\n called name because the Beautiful Soup\n search methods already define a name\n argument. You also can't use a Python\n reserved word like for as...
[ 35 ]
[]
[]
[ "beautifulsoup", "find", "python" ]
stackoverflow_0002877114_beautifulsoup_find_python.txt
Q: Python, store a dict in a database What's the best way to store and retrieve a python dict in a database? A: If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for...
Python, store a dict in a database
What's the best way to store and retrieve a python dict in a database?
[ "If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example MongoDB. The MongoDB python bindings allow you to just insert dicts in the DB, and query them based on...
[ 19, 6, 4, 4 ]
[]
[]
[ "dictionary", "python", "string" ]
stackoverflow_0002877410_dictionary_python_string.txt
Q: What's the best way to use python-syntax config files (in python of course)? My config file is really just a big python dict, but I have many config files to run different experiments and I want to 'import' a different one based on a command line option. Instinctively I want to do import ConfigFileName where Confi...
What's the best way to use python-syntax config files (in python of course)?
My config file is really just a big python dict, but I have many config files to run different experiments and I want to 'import' a different one based on a command line option. Instinctively I want to do import ConfigFileName where ConfigFileName is a string with the config file's python package name in it... but tha...
[ "Use the __import__ builtin function. But like nosklo, I prefer to store it in simpler data format like JSON of INI config file.\n", "Switch to json. It's included with python and makes a better format overall for config files.\n", "You might consider ConfigParser, also included with python. It offers simple s...
[ 5, 1, 1 ]
[]
[]
[ "config", "configuration", "import", "python" ]
stackoverflow_0002874431_config_configuration_import_python.txt
Q: Marquee style progressbar in wxPython Could anyone tell me how to implement a marquee style progress bar in wxPython? As stated on MSDN: you can animate it in a way that shows activity but does not indicate what proportion of the task is complete. Thank you. alt text http://i.msdn.microsoft.com/dynimg/IC100...
Marquee style progressbar in wxPython
Could anyone tell me how to implement a marquee style progress bar in wxPython? As stated on MSDN: you can animate it in a way that shows activity but does not indicate what proportion of the task is complete. Thank you. alt text http://i.msdn.microsoft.com/dynimg/IC100842.png I tried this but it doesn't seem to...
[ "wxGauge has a Pulse() function\ngauge.Pulse()\n\n", "Here is an example:\n def loadBallots(self):\n self.dirtyBallots = Ballots()\n self.dirtyBallots.exceptionQueue = Queue(1)\n loadThread = Thread(target=self.dirtyBallots.loadUnknown, args=(self.filename,))\n loadThread.start()\n\n # Display a p...
[ 1, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002856382_python_wxpython.txt
Q: Django Form inheritance problem Why can't I do this? from django import forms from django.forms import widgets class UserProfileConfig(forms.Form): def __init__(self,*args,**kwargs): super (UserProfileConfig,self).__init__(*args,**kwargs) self.tester = 'asdf' username = forms.CharField(la...
Django Form inheritance problem
Why can't I do this? from django import forms from django.forms import widgets class UserProfileConfig(forms.Form): def __init__(self,*args,**kwargs): super (UserProfileConfig,self).__init__(*args,**kwargs) self.tester = 'asdf' username = forms.CharField(label='Username',max_length=100,initial...
[ "What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created. self.tester doesn't exist until you call __init__ at instance creation time.\n", "You can just do it this way\nfrom django import forms\nfro...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002373348_django_django_forms_python.txt
Q: wxpython Prevent Ctrl+Enter from changing the focus I have two wxListCtrl and want to process the Ctrl+Enter keyboard event without letting wx change the focus to the other ListCtrl. I have event handlers for wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR and KillFocus, but KillFocus is always called first, then the...
wxpython Prevent Ctrl+Enter from changing the focus
I have two wxListCtrl and want to process the Ctrl+Enter keyboard event without letting wx change the focus to the other ListCtrl. I have event handlers for wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR and KillFocus, but KillFocus is always called first, then the focus changes and the the keyboard handlers are called f...
[ "No idea if this will work, but who knows! \n ac = [(wx.ACCEL_CTRL, wx.WXK_RETURN, wx.NewId())]\n tbl = wx.AcceleratorTable(ac)\n list.SetAcceleratorTable(tbl) # should overwrite its bindings?\n\nor also try EVT_CHAR_HOOK\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002783397_python_wxpython.txt
Q: Referring to objects inside a list without using references or indices I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it. Basically, I ...
Referring to objects inside a list without using references or indices
I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it. Basically, I need a simple way to point to a particular item that isn't its index, and is...
[ "Instead of using a list, why not use a dictionary and use small integers as the keys? Adding and removing items from the dictionary will not change the indices into the dictionary. You will want to keep one value in the dictionary that lets you know what the next assigned index will be.\n", "A UUID seems perfect...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002877617_python.txt
Q: New to PyDev, question about auto completion I installed Eclipse and PyDev and I'm wondering if I have to setup anything else? The reason I'm asking is that I'm finding the auto complete isn't working in certain cases. For example, if I have a variable a_string, I'd like to see a list of available methods once I t...
New to PyDev, question about auto completion
I installed Eclipse and PyDev and I'm wondering if I have to setup anything else? The reason I'm asking is that I'm finding the auto complete isn't working in certain cases. For example, if I have a variable a_string, I'd like to see a list of available methods once I type "a_string." or if I have an array I'd like to ...
[ "It should work out of the box (given you configured your python interpreter path properly).\nHowever, keep in mind that since Python is duck-typed you will not necessarily get the full auto-complete set you would expect from strongly-typed languages such as Java. Having said that, PyDev does do a good job with det...
[ 2 ]
[]
[]
[ "code_completion", "pydev", "python" ]
stackoverflow_0002877872_code_completion_pydev_python.txt
Q: Is there a better way to write this URL Manipulation in Python? I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated. parsed = urlparse(url) if parsed.query != "": ...
Is there a better way to write this URL Manipulation in Python?
I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated. parsed = urlparse(url) if parsed.query != "": params = dict([s.split("=") for s in parsed.query.split("&")]) ...
[ "Use urlparse.parse_qsl() to crack the query string. You can filter this in one go:\nparams = [(k,v) for (k,v) in parse_qsl(parsed.query) if k != 'page']\n\n", "I've created a small helper class to represent a url in a structured way:\nimport cgi, urllib, urlparse\n\nclass Url(object):\n def __init__(self, url...
[ 11, 9 ]
[]
[]
[ "parsing", "python", "url" ]
stackoverflow_0002873438_parsing_python_url.txt
Q: Sort a list of dicts by dict values I have a list of dictionaries: [{'title':'New York Times', 'title_url':'New_York_Times','id':4}, {'title':'USA Today','title_url':'USA_Today','id':6}, {'title':'Apple News','title_url':'Apple_News','id':2}] I'd like to sort it by the title, so elements with A go before Z: [{'...
Sort a list of dicts by dict values
I have a list of dictionaries: [{'title':'New York Times', 'title_url':'New_York_Times','id':4}, {'title':'USA Today','title_url':'USA_Today','id':6}, {'title':'Apple News','title_url':'Apple_News','id':2}] I'd like to sort it by the title, so elements with A go before Z: [{'title':'Apple News','title_url':'Apple_Ne...
[ "l.sort(key=lambda x:x['title'])\n\nTo sort with multiple keys, assuming all in ascending order:\nl.sort(key=lambda x:(x['title'], x['title_url'], x['id']))\n\n", "The hypoallergenic alternative for those who sneeze when approached by lambdas:\nimport operator\nL.sort(key=operator.itemgetter('title','title_url','...
[ 20, 19, 2 ]
[ "originalList.sort(lambda d1, d2: cmp(d1['title'], d2['title']))\n\nThough this only sorts on title and order after that is undefined. Doing multiple levels would be painful this way.\n" ]
[ -1 ]
[ "dictionary", "python", "sorting" ]
stackoverflow_0002878084_dictionary_python_sorting.txt
Q: Making REST calls only available to local applications? Suppose I have a url like: http://example.com/get-users which returns a JSON object of all users. But, I don't want anyone (or any bots) to be able to go to this url to fetch this information. I want it to only respond to calls from other local modules in t...
Making REST calls only available to local applications?
Suppose I have a url like: http://example.com/get-users which returns a JSON object of all users. But, I don't want anyone (or any bots) to be able to go to this url to fetch this information. I want it to only respond to calls from other local modules in the same website. How would I go about implementing someting l...
[ "Compare the REMOTE_ADDR against a white list of approved IPs. If it's not in that list, simply return nothing, close the socket, or return an HTTP error.\n" ]
[ 1 ]
[ "Are you using Spring? Have considered adding a filter bean inside your context to only allow HTTP requests from your site?\n" ]
[ -1 ]
[ "django", "django_piston", "python", "rest" ]
stackoverflow_0002878245_django_django_piston_python_rest.txt
Q: Python timezone issue? im having troubles with parsing a feed and getting the time. i am using dateutil.parser from dateutil.parser import parse print updated, parse(updated ), parse( updated ).utcoffset() this should be a time in cali, output 2010-05-20T11:00:00.000-07:00 2010-05-20 11:00:00.000000-07:00 -1 da...
Python timezone issue?
im having troubles with parsing a feed and getting the time. i am using dateutil.parser from dateutil.parser import parse print updated, parse(updated ), parse( updated ).utcoffset() this should be a time in cali, output 2010-05-20T11:00:00.000-07:00 2010-05-20 11:00:00.000000-07:00 -1 day, 17:00:00 why is the offs...
[ "\"Minus 7 hours\" is equal to \"minus 1 day, plus 17 hours\". So probably the time zone offset is correct and just displayed in a weird way.\n" ]
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002878400_datetime_python.txt
Q: ungetc in Python Some file read (readlines()) functions in Python copy the file contents to memory (as a list) I need to process a file that's too large to be copied in memory and as such need to use a file pointer (to access the file one byte at a time) -- as in C getc(). The additional requirement I have is ...
ungetc in Python
Some file read (readlines()) functions in Python copy the file contents to memory (as a list) I need to process a file that's too large to be copied in memory and as such need to use a file pointer (to access the file one byte at a time) -- as in C getc(). The additional requirement I have is that I'd like to rewin...
[ "\nYou do not need file pointers, which Python does not have or want. \nTo go through a file line by line without reading the whole thing into memory, just iterate over the file object itself, i.e.\n with open(filename, \"r\") as f:\n for line in f:\n ...\n\nUsing readlines is generally to be avoided.\n...
[ 5, 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "readline", "readlines", "ungetc" ]
stackoverflow_0002655643_python_readline_readlines_ungetc.txt
Q: How do I include the Django settings file? I have a .py file in a directory , which is inside the Django project folder. I have email settings in my settings.py, but this .py file does not import that file. How can I specify to Django that settings.py should be used , so that I can use EmailMessage class with the ...
How do I include the Django settings file?
I have a .py file in a directory , which is inside the Django project folder. I have email settings in my settings.py, but this .py file does not import that file. How can I specify to Django that settings.py should be used , so that I can use EmailMessage class with the settings that are in my settings.py?
[ "from django.conf import settings\n\nshould do it!\n", "Depending on how you want to call your python script you can use one of a couple ways to accomplish what you want. The first is purely inside the python file.\nfrom django.core.management import setup_environ\nfrom mysite import settings\n\nsetup_environ(set...
[ 7, 1, 0 ]
[]
[]
[ "django", "email", "python", "settings" ]
stackoverflow_0002869909_django_email_python_settings.txt
Q: Replacing backslashes in Python strings I have some code to encrypt some strings in Python. Encrypted text is used as a parameter in some urls, but after encrypting, there comes backslashes in string and I cannot use single backslash in urllib2.urlopen. I cannot replace single backslash with double. For example: p...
Replacing backslashes in Python strings
I have some code to encrypt some strings in Python. Encrypted text is used as a parameter in some urls, but after encrypting, there comes backslashes in string and I cannot use single backslash in urllib2.urlopen. I cannot replace single backslash with double. For example: print cipherText '\t3-@\xab7+\xc7\x93H\xdc\x...
[ "probably what you are seeing is not a real \"backslash character\", but it is the string representation of a non printable (or non-ascii) character. For example \\t is Tab, not a backslash and t.\nYou should build your url with\n\"http://awebsite.me/main?%s\" % (urllib.urlencode({'param': cipherText}))\n\n" ]
[ 7 ]
[]
[]
[ "backslash", "python", "replace", "string" ]
stackoverflow_0002878549_backslash_python_replace_string.txt
Q: Python: set a function timeout without using signal or threads? Is there a way to have a function raise an error if it takes longer than a certain amount of time to return? I want to do this without using signal (because I am not in the main thread) or by spawning more threads, which is cumbersome. A: If your fu...
Python: set a function timeout without using signal or threads?
Is there a way to have a function raise an error if it takes longer than a certain amount of time to return? I want to do this without using signal (because I am not in the main thread) or by spawning more threads, which is cumbersome.
[ "If your function is looping through a lot of things, you could check the elapsed time during each iteration of the loop... but if it's blocked on something for the long period, then you need to have some other thread which can be handling the timing stuff while the thread you're timing is blocked.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002878474_python.txt
Q: Make OS open directory in Python I am writing a program in Python, and want to get it to make the OS open the current working directory, making for instance Windows open explorer.exe and navigating to the wanted directory. Any ideas on how to do this? The directory is already given by os.getcwd. Cross platform m...
Make OS open directory in Python
I am writing a program in Python, and want to get it to make the OS open the current working directory, making for instance Windows open explorer.exe and navigating to the wanted directory. Any ideas on how to do this? The directory is already given by os.getcwd. Cross platform methods preferred :)
[ "There is os.startfile, but it's only available under windows:\nimport os\nos.startfile('C:/') # opens explorer at C:\\ drive\n\nHere someone (credits to Eric_Dexter@msn.com apparently) posted an alternative for use on unix-like systems, and someone mentions the desktop package available at pypi (but i've never use...
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0002878712_python.txt
Q: In python, a good way to remove a list from a list of dicts I have a list of dicts: list = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'}, {'id': 3L, 'title_url': u'Test', 'title': u'Test'}] I'd like to remove the list item with title = 'Test' What is the best way to do this given that the...
In python, a good way to remove a list from a list of dicts
I have a list of dicts: list = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'}, {'id': 3L, 'title_url': u'Test', 'title': u'Test'}] I'd like to remove the list item with title = 'Test' What is the best way to do this given that the order of the key/value pairs change? Thanks.
[ "[i for i in lst if i['title']!= u'Test']\n\nAlso, please don't use list as a variable name, it shadows built-in.\n", "mylist = [x for x in mylist if x['title'] != 'Test']\n\nOther solutions are possible, but any solution will be O(n) since you have to search through the whole list for the right element. Given t...
[ 6, 4, 3, 3, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002878230_dictionary_list_python.txt
Q: Scalable chat site in python Hey guys, I have an idea that I'd like to start implementing that at the crux of it, will basically be a chat website, and will need to support multiple rooms. Quite frankly, I'm not too sure where to begin with regards to setting up a very sturdy/scalable chat system in python (or ano...
Scalable chat site in python
Hey guys, I have an idea that I'd like to start implementing that at the crux of it, will basically be a chat website, and will need to support multiple rooms. Quite frankly, I'm not too sure where to begin with regards to setting up a very sturdy/scalable chat system in python (or another language if you guys believe ...
[ "Look into XMPP. Here's the list of Python libraries.\n", "Google AppEngine supports python provides scalable framework. Probably you'll save lots of time if you use it.\n" ]
[ 0, 0 ]
[]
[]
[ "chat", "chatroom", "python" ]
stackoverflow_0002878081_chat_chatroom_python.txt
Q: What's the life-time of a thread-local value in Python? import threading mydata = threading.local() def run(): # When will the garbage collector be able to destroy the object created # here? After the thread exits from ``run()``? After ``join()`` is called? # Or will it survive the thread in which it...
What's the life-time of a thread-local value in Python?
import threading mydata = threading.local() def run(): # When will the garbage collector be able to destroy the object created # here? After the thread exits from ``run()``? After ``join()`` is called? # Or will it survive the thread in which it was created, and live until # ``mydata`` is garbage-coll...
[ "Here is my answer, since I am failing to see the conclusion in the previous answers.\nI started wondering the same thing and tried a test program that is similar to the ones in other answers and my conclusion was that they do get GCed sooner than the end of the program, which means, these references can be determi...
[ 10, 3, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001478248_multithreading_python.txt
Q: Getting pixel averages of a vector sitting atop a bitmap I'm currently involved in a hardware project where I am mapping triangular shaped LED to traditional bitmap images. I'd like to overlay a triangle vector onto an image and get the average pixel data within the bounds of that vector. However, I'm unfamiliar w...
Getting pixel averages of a vector sitting atop a bitmap
I'm currently involved in a hardware project where I am mapping triangular shaped LED to traditional bitmap images. I'd like to overlay a triangle vector onto an image and get the average pixel data within the bounds of that vector. However, I'm unfamiliar with the math needed to calculate this. Does anyone have an alg...
[ "Will this work: http://www.blackpawn.com/texts/pointinpoly/default.html ?\n", "You can do line rasterization on the lineparts to determine for each pixel at each horizontal scanline lie within your triangle. Sum and divide their RGB values to get the average.\n" ]
[ 0, 0 ]
[]
[]
[ "image_manipulation", "python" ]
stackoverflow_0002878928_image_manipulation_python.txt
Q: Django Error: NameError name 'current_datetime' is not defined I'm working through the book "The Definitive Guide to Django" and am stuck on a piece of code. This is the code in my settings.py: ROOT_URLCONF = 'mysite.urls' I have the following code in my urls.py from django.conf.urls.defaults import * from mysite...
Django Error: NameError name 'current_datetime' is not defined
I'm working through the book "The Definitive Guide to Django" and am stuck on a piece of code. This is the code in my settings.py: ROOT_URLCONF = 'mysite.urls' I have the following code in my urls.py from django.conf.urls.defaults import * from mysite.views import hello, my_homepage_view urlpatterns = patterns('', ('...
[ "Change:\nfrom mysite.views import hello, my_homepage_view\n\nTo this:\nfrom mysite.views import current_datetime, hello, my_homepage_view\n\nHere's some documentation: http://www.djangobook.com/en/1.0/chapter03/ \n" ]
[ 3 ]
[]
[]
[ "django", "django_urls", "django_views", "nameerror", "python" ]
stackoverflow_0002879170_django_django_urls_django_views_nameerror_python.txt
Q: Problem with urllib I wrote this code: import urllib proxies = {'http': 'http://112.65.135.54:8080/'} opener = urllib.FancyURLopener(proxies) r = opener.open("http://www.python.org/") print r.read() and when I execute it this program works fine, and send for me source code of python.org But when i use this: im...
Problem with urllib
I wrote this code: import urllib proxies = {'http': 'http://112.65.135.54:8080/'} opener = urllib.FancyURLopener(proxies) r = opener.open("http://www.python.org/") print r.read() and when I execute it this program works fine, and send for me source code of python.org But when i use this: import urllib proxies = {'h...
[ "Presumably, the first IP address and port points to a working proxy, while the second set does not (they're on private IPs so of course nobody else can check). So, speak with whoever handles your local network, and get the exact specs for IP and port of the HTTP proxy you're supposed to use!\nEdit: aargh, the que...
[ 1, 1 ]
[]
[]
[ "python", "sockets", "urllib" ]
stackoverflow_0002879183_python_sockets_urllib.txt
Q: Help with Django localization--doesn't seem to be working. Nothing happens Can someone help me with Localization? I put {% trans "..." %} in my template, I filled in my django.po after running "makemessages". #: templates/main_content.html:136 msgid "Go to page" msgstr "▒~C~Z▒~C▒▒~B▒▒~L~G▒~Z" #: templates/main_...
Help with Django localization--doesn't seem to be working. Nothing happens
Can someone help me with Localization? I put {% trans "..." %} in my template, I filled in my django.po after running "makemessages". #: templates/main_content.html:136 msgid "Go to page" msgstr "▒~C~Z▒~C▒▒~B▒▒~L~G▒~Z" #: templates/main_content.html:138 msgid "Page" msgstr "▒~C~Z▒~C▒▒~B▒" #: templates/main_content....
[ "Set your browser (or whatever web user agent you're using to test this site) so that its Accept-Language request header value is ja.\n" ]
[ 0 ]
[]
[]
[ "django", "internationalization", "localization", "python" ]
stackoverflow_0002878935_django_internationalization_localization_python.txt
Q: Python base classes share attributes? Code in test.py: class Base(object): def __init__(self, l=[]): self.l = l def add(self, num): self.l.append(num) def remove(self, num): self.l.remove(num) class Derived(Base): def __init__(self, l=[]): super(Derived, self).__i...
Python base classes share attributes?
Code in test.py: class Base(object): def __init__(self, l=[]): self.l = l def add(self, num): self.l.append(num) def remove(self, num): self.l.remove(num) class Derived(Base): def __init__(self, l=[]): super(Derived, self).__init__(l) Python shell session: Python 2.6....
[ "You're making a common Python newcomer mistake.\nSee my answer here:\nHow should I declare default values for instance variables in Python?\nBriefly explained, Python interprets the class definitions only once. That means everything declared in the __init__() method is only created once. Or, in another words, your...
[ 20, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002879494_python.txt
Q: Python How to make a cross-module function? I want to be able to call a global function from an imported class, for example In file PetStore.py class AnimalSound(object): def __init__(self): if 'makenoise' in globals(): self.makenoise = globals()['makenoise'] else: self.makenoise =...
Python How to make a cross-module function?
I want to be able to call a global function from an imported class, for example In file PetStore.py class AnimalSound(object): def __init__(self): if 'makenoise' in globals(): self.makenoise = globals()['makenoise'] else: self.makenoise = lambda: 'meow' def __str__(self): retu...
[ "The globals() call returns the globals of the module in which the call is lexically located; there is no intrinsic \"dynamic scoping\" in Python -- it's lexically scoped, like just about every modern language.\nThe solid, proper way to obtain the effect you desire is to explicitly pass to the initializer of Animal...
[ 5, 2 ]
[]
[]
[ "global", "module", "python" ]
stackoverflow_0002879711_global_module_python.txt
Q: Subprocess fails to catch the standard output I am trying to generate tree with fasta file input and Alignment with MuscleCommandline import sys,os, subprocess from Bio import AlignIO from Bio.Align.Applications import MuscleCommandline cline = MuscleCommandline(input="c:\Python26\opuntia.fasta") child= subprocess...
Subprocess fails to catch the standard output
I am trying to generate tree with fasta file input and Alignment with MuscleCommandline import sys,os, subprocess from Bio import AlignIO from Bio.Align.Applications import MuscleCommandline cline = MuscleCommandline(input="c:\Python26\opuntia.fasta") child= subprocess.Popen(str(cline), stdout ...
[ "A couple of things are giving problems here:\n\nYou need a child.wait() after the subprocess call so that your code will wait until the external program is done running.\nMuscle does not actually write to stdout, even though the help documentation says it does, at least with v3.6 that I have here. I believe the la...
[ 4, 2, 1, 0 ]
[]
[]
[ "biopython", "python", "subprocess" ]
stackoverflow_0002856697_biopython_python_subprocess.txt
Q: is there a twitter user login framework for gae I want to someone to be able to login using twitter, Is there a framework that you have used to do this? Thanks A: There's a simple example here. Beyond this, there's tweetapp, but it's currently not maintained; AppEngine-OAuth-Library; and, I believe, some twitte...
is there a twitter user login framework for gae
I want to someone to be able to login using twitter, Is there a framework that you have used to do this? Thanks
[ "There's a simple example here. Beyond this, there's tweetapp, but it's currently not maintained; AppEngine-OAuth-Library; and, I believe, some twitter-friendly delegated authorization framework for Django, Django-social-auth, about which, however, I don't know much beyond the name.\n", "While not exactly addres...
[ 1, 1 ]
[]
[]
[ "frameworks", "google_app_engine", "oauth", "python", "twitter" ]
stackoverflow_0002879146_frameworks_google_app_engine_oauth_python_twitter.txt
Q: Get system language in ISO 639 (3-letter codes) in Python Could someone tell me a way to get a system language in the ISO 639 (3 letter code) format in a cross platform way? Thanks. I found a list of three letter country codes. A: I'm assuming you're wanting ISO 639 2 and not ISO 639 3 here. Machine-readable dat...
Get system language in ISO 639 (3-letter codes) in Python
Could someone tell me a way to get a system language in the ISO 639 (3 letter code) format in a cross platform way? Thanks. I found a list of three letter country codes.
[ "I'm assuming you're wanting ISO 639 2 and not ISO 639 3 here. Machine-readable data is available from the Library of Congress (I'm using the \"utf-8\" encoding for this answer, see also http://www.loc.gov/standards/iso639-2/ascii_8bits.html for more info.) \nHere's an example of how you could load this:\nimport co...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002879856_python.txt
Q: Is there a ruby equivalent of "python -i"? ruby -n is the closest thing I found, but it repeats the whole script. Also it's not available for irb. A: $ cat > hello.rb $hello = 'Hello, world!' puts $hello ^D $ irb irb(main):001:0> load 'hello.rb' Hello, world! => true irb(main):002:0> $hello => "Hello, world!" A...
Is there a ruby equivalent of "python -i"?
ruby -n is the closest thing I found, but it repeats the whole script. Also it's not available for irb.
[ "\n$ cat > hello.rb\n$hello = 'Hello, world!'\nputs $hello\n^D\n$ irb\nirb(main):001:0> load 'hello.rb'\nHello, world!\n=> true\nirb(main):002:0> $hello\n=> \"Hello, world!\"\n\nA bit tedious, and local variables won't carry through. May be close enough for your usage? (This is basically like Python's execfile.)\...
[ 1, 1 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0002437582_python_ruby.txt
Q: Python rounding problem >>> num = 4.123456 >>> round(num, 3) # expecting 4.123 4.1230000000000002 I'm expecting 4.123 as a result, Am I wrong? A: This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic: http://docs.sun.com/source/806-3568/ncg_goldberg.ht...
Python rounding problem
>>> num = 4.123456 >>> round(num, 3) # expecting 4.123 4.1230000000000002 I'm expecting 4.123 as a result, Am I wrong?
[ "This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic:\nhttp://docs.sun.com/source/806-3568/ncg_goldberg.html\n", "Yep, your expectations don't match the design intent of your tools.\nCheck out this section of the Python tutorial.\n\nUsing math.round is...
[ 7, 6, 4, 2 ]
[]
[]
[ "floating_point", "math", "python" ]
stackoverflow_0002880547_floating_point_math_python.txt
Q: python VTE Terminal weirdness i'm trying to use the terminal from python VTE binding (python-vte from debian squeeze) as a virtual terminal emulator (just for ANSI/control chars text processing) in interactive python console, everything looks (almost) all right: >>> import vte >>> term = vte.Terminal() >>> term.fe...
python VTE Terminal weirdness
i'm trying to use the terminal from python VTE binding (python-vte from debian squeeze) as a virtual terminal emulator (just for ANSI/control chars text processing) in interactive python console, everything looks (almost) all right: >>> import vte >>> term = vte.Terminal() >>> term.feed("a\nb") >>> print repr(term.get_...
[ "..posting myself the solution i have found elsewhere\nproblem was that i was ignoring fact that vte.Terminal is an gtk applet, so gtk main loop has to be called.\nexample of working code:\nimport gtk\nimport vte\n\nterm = vte.Terminal()\n\nterm.feed(\"a\\r\\nb\")\n\ndef get_text(term):\n print repr(term.get_tex...
[ 3 ]
[]
[]
[ "gnome", "python", "terminal", "vte" ]
stackoverflow_0002868694_gnome_python_terminal_vte.txt
Q: Django 1.2 crash course needed I know Python but I've never used Django. What do I need to know about Django 1.2 to port my typical PHP CRUD web application in one weekend? (Yes I've read Joel Spolsky's Netscape article :-)) I'm reading this tutorial right now and it's excellent. I'm already playing around with ...
Django 1.2 crash course needed
I know Python but I've never used Django. What do I need to know about Django 1.2 to port my typical PHP CRUD web application in one weekend? (Yes I've read Joel Spolsky's Netscape article :-)) I'm reading this tutorial right now and it's excellent. I'm already playing around with inspectdb to generate my models from...
[ "The django docs is very good and you should find the answers to most of your questions http://docs.djangoproject.com/en/1.2/\nYou can google it easily but make sure that you are on the doc pages of django 1.2.\nFor schema migration, I recommed to look at south http://south.aeracode.org/\nIn my opinion south is a m...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002879698_django_python.txt
Q: writing an api for python that can be installed using setup.py method I am new at writing APIs in python, in any language for that matter. I was hoping to get pointers on how i can create an API that can be installed using setup.py method and used in other python projects. Something similar to the twitterapi. I ha...
writing an api for python that can be installed using setup.py method
I am new at writing APIs in python, in any language for that matter. I was hoping to get pointers on how i can create an API that can be installed using setup.py method and used in other python projects. Something similar to the twitterapi. I have already created and coded all the methods i want to include in the API. ...
[ "It's worth noting that this part of python is undergoing some changes right now. It's all a bit messy. The most current overview I know of is the Hitchhiker's Guide to Packaging: http://guide.python-distribute.org/\nThe current state of packaging section is important: http://guide.python-distribute.org/introductio...
[ 1, 1 ]
[]
[]
[ "api", "django", "python", "setup.py", "twitter" ]
stackoverflow_0002727348_api_django_python_setup.py_twitter.txt
Q: Python socket for receiving UDP packages from an FPGA I am trying to read the UDP packages in python, which were sent from an FPGA. I see the packages in wireshark, and they look allright. Python, however does not receive anything when I use this simple script: import socket import sys HOST, PORT = "192.168.1.1",...
Python socket for receiving UDP packages from an FPGA
I am trying to read the UDP packages in python, which were sent from an FPGA. I see the packages in wireshark, and they look allright. Python, however does not receive anything when I use this simple script: import socket import sys HOST, PORT = "192.168.1.1", 21844 sock = socket.socket(socket.AF_INET, socket.SOCK_DGR...
[ "You don't connect with a UDP server (I assume the Python code is the server), you bind.\n" ]
[ 1 ]
[]
[]
[ "fpga", "python", "udp" ]
stackoverflow_0002881219_fpga_python_udp.txt
Q: How can I make list or set translatable using gettext? I have some structure in Python: > gender=( ('0','woman'), ('1','man') ) I want to translate it before I will display it in Django template. Unfortunately, below solution doesn't work: > from django.utils.translation import > ugettext_lazy as _ > > gender=( ...
How can I make list or set translatable using gettext?
I have some structure in Python: > gender=( ('0','woman'), ('1','man') ) I want to translate it before I will display it in Django template. Unfortunately, below solution doesn't work: > from django.utils.translation import > ugettext_lazy as _ > > gender=( ('0',_('woman')), > ('1',_('man')) ) What shall I do to tra...
[ "Try like this:\ngender=( ('0',_('woman')), ('1',_('man')) )\n\nWhen you import gettext:\nfrom django.utils.translation import ugettext_lazy as _\n\nyou need to wrap the string in gettext function:\n_('some_string')\n\nIf underscore is confiusing you, this is same as writing:\nfrom django.utils.translation import u...
[ 0 ]
[]
[]
[ "django", "gettext", "python" ]
stackoverflow_0002881323_django_gettext_python.txt
Q: How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python? How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python?? My prob is similar to "ROMANs" prob,i hav seen e...
How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python?
How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python?? My prob is similar to "ROMANs" prob,i hav seen earlier in the post at this site.. Basically,i want to combine parts of different wav file into one wav file?? if there is ne other apporac...
[ "There are a few libraries you can use for handling media files in general, eg. pymedia. However if all you need is support for simple WAVs, you could probably just use the built-in wave module.\nimport wave\nwin= wave.open('sample.wav', 'rb')\nwout= wave.open('segment.wav', 'wb')\n\nt0, t1= 1.0, 2.0 # cut audio be...
[ 7 ]
[]
[]
[ "audio", "python", "wav" ]
stackoverflow_0002881012_audio_python_wav.txt
Q: Python OOP and lists I'm new to Python and it's OOP stuff and can't get it to work. Here's my code: class Tree: root = None; data = []; def __init__(self, equation): self.root = equation; def appendLeft(self, data): self.data.insert(0, data); def appendRight(self, data): ...
Python OOP and lists
I'm new to Python and it's OOP stuff and can't get it to work. Here's my code: class Tree: root = None; data = []; def __init__(self, equation): self.root = equation; def appendLeft(self, data): self.data.insert(0, data); def appendRight(self, data): self.data.append(data...
[ "The problem is that you've declared data as a class variable, so all instances of the class share the same list. Instead, put self.data = [] in your __init__.\nAlso, get rid of all those semicolons. They are unnecessary and clutter up your code.\n", "Move root and data into the definition of __init__ . As it s...
[ 11, 4, 3 ]
[]
[]
[ "class_variables", "python" ]
stackoverflow_0002878499_class_variables_python.txt
Q: Pyinotify doesn't run with pygtk I'm newbie in python and I'm trying to use pyinotify with a GUI interface using pygtk. I have two classes, my gtk class which doesn't do much, only displays stuff, and a class that handles the monitoring. When I run them separately they do their work but when I try to load the gtk ...
Pyinotify doesn't run with pygtk
I'm newbie in python and I'm trying to use pyinotify with a GUI interface using pygtk. I have two classes, my gtk class which doesn't do much, only displays stuff, and a class that handles the monitoring. When I run them separately they do their work but when I try to load the gtk class from the other one, it only runs...
[ "Per the comments, the solution appears to be to add \ngobject.threads_init()\n\nnear the top of the script. This, and other useful information about using threads with pygtk can be found in this faq.\n" ]
[ 4 ]
[]
[]
[ "pygtk", "pyinotify", "python" ]
stackoverflow_0002877124_pygtk_pyinotify_python.txt
Q: Task queue execution I'm developing a site for a customer which regularly sends email notifications, to facilitate this I have a cron job which runs at 2am to start scheduling individual tasks to send out the notications. This is all fine and work perfectly with tasks being scheduled to execute immediately, but to...
Task queue execution
I'm developing a site for a customer which regularly sends email notifications, to facilitate this I have a cron job which runs at 2am to start scheduling individual tasks to send out the notications. This is all fine and work perfectly with tasks being scheduled to execute immediately, but to assist development and te...
[ "There seems to be a timezone-related bug in the SDK that causes the eta for tasks created through the remote API to be scheduled one hour after they're added. If you explicitly set the countdown to 0, the task should be scheduled to run immediately. \n", "If you want it to execute immediately, just open the URL...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002880573_google_app_engine_python.txt
Q: getting expat to use .dtd for entity replacement in python I'm trying to read in an xml file which looks like this <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE dblp SYSTEM "dblp.dtd"> <dblp> <incollection> <author>Jos&eacute; A. Blakeley</author> </incollection> </dblp> The point that creates the problem...
getting expat to use .dtd for entity replacement in python
I'm trying to read in an xml file which looks like this <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE dblp SYSTEM "dblp.dtd"> <dblp> <incollection> <author>Jos&eacute; A. Blakeley</author> </incollection> </dblp> The point that creates the problem looks is the Jos&eacute; A. Blakeley part: The parser calls it...
[ "As I understand it, if you're using pyexpat directly, then you have to provide your own ExternalEntityRefHandler to fetch the external DTD and feed it to expat.\nSee eg. xml.sax.expatreader for example code (method external_entity_ref, line 374 in Python 2.6).\nIt would probably be better to use a higher-level int...
[ 1, 0 ]
[]
[]
[ "dtd", "entity", "expat_parser", "python", "xml" ]
stackoverflow_0002881991_dtd_entity_expat_parser_python_xml.txt
Q: How to write a custom solution using a python package, modules etc I am writing a packacge foobar which consists of the modules alice, bob, charles and david. From my understanding of Python packages and modules, this means I will create a folder foobar, with the following subdirectories and files (please correct ...
How to write a custom solution using a python package, modules etc
I am writing a packacge foobar which consists of the modules alice, bob, charles and david. From my understanding of Python packages and modules, this means I will create a folder foobar, with the following subdirectories and files (please correct if I am wrong) foobar/ __init__.py alice/alice.py bob/bob.py cha...
[ "\nCan a package be made executable and\n used in a script like I described\n above?\n\nQ1 and Q4. Yes, place your:\nif __name__ == \"__main__\":\n dosomething()\n\nin foobar/__init__.py\n\nQ2 The various modules will use code that\n I want to refactor into a common\n library. Does that mean creating a new\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002882173_python.txt
Q: bundles in java? in symfony 2.0 and django there are bundles that contain everything for a feature (html, css, js, img, php/python). so if you want to delete one feature, you basically just delete that bundle and unregister it from "main". are there java frameworks for this too? or is it different in java cause ja...
bundles in java?
in symfony 2.0 and django there are bundles that contain everything for a feature (html, css, js, img, php/python). so if you want to delete one feature, you basically just delete that bundle and unregister it from "main". are there java frameworks for this too? or is it different in java cause java is a compiling lang...
[ "Are osgi-bundles what you search ?\nhttp://en.wikipedia.org/wiki/OSGi\n", "I suppose the closest thing in Javaland is the venerable Web Application Archive (war file).\n", "In Java, libraries and programs are normally packaged in JAR files. Java does not have its own package management system to install or rem...
[ 1, 1, 1 ]
[]
[]
[ "django", "java", "php", "python", "symfony1" ]
stackoverflow_0002881825_django_java_php_python_symfony1.txt
Q: httplib2, how to set more than one cookie? As you are probably aware, more often than not, an HTTP server will send more than just a session_id cookie; however, httplib2 handles cookies with a dictionary, like this: response, content = http.request(url, 'GET', headers=headers) headers = {'Cookie': response['set-c...
httplib2, how to set more than one cookie?
As you are probably aware, more often than not, an HTTP server will send more than just a session_id cookie; however, httplib2 handles cookies with a dictionary, like this: response, content = http.request(url, 'GET', headers=headers) headers = {'Cookie': response['set-cookie']} url = 'http://www.example.com/home' ...
[ "Cookies are contained in a single HTTP header, separated by semicolons. Example:\ncookie1=value1;cookie2=value2\n\nSo you'll need to build a string from the cookies sent by the server, and then set that as the Cookie header.\nEdit: Actually, playing around a bit with httplib2 and re-reading your question, I'm not...
[ 5, 3, 2 ]
[ "Try this:\npp = re.compile('(Sun|Mon|Tue|Wed|Thu|Fri|Sat),')\npp.sub('','alpha Sun, beta')\n'alpha beta'\n\n" ]
[ -2 ]
[ "cookiejar", "cookies", "httplib2", "python" ]
stackoverflow_0001738227_cookiejar_cookies_httplib2_python.txt
Q: PyArg_ParseTuple plus cast I have a c function being called from python. Python gives the function an integer, but I would like to use it as another data type in C. I am currently using PyArg_ParseTuple (args, "i", &value) and then manually doing a cast on value. Is there a way to do this cast through PyArg? A: ...
PyArg_ParseTuple plus cast
I have a c function being called from python. Python gives the function an integer, but I would like to use it as another data type in C. I am currently using PyArg_ParseTuple (args, "i", &value) and then manually doing a cast on value. Is there a way to do this cast through PyArg?
[ "Which data type are you trying to cast the argument to in C?\nIf you want an integer type, it looks like you might be able to get it by using a different format string in PyArg_ParseType(). For example, \"b\" converts a non-negative Python integer into an unsigned char.\nunsigned char value;\nPyArg_ParseTuple (ar...
[ 0 ]
[]
[]
[ "binding", "c", "casting", "python" ]
stackoverflow_0002876283_binding_c_casting_python.txt
Q: Identifying if a data is RSS or HTML on python Is there a function or method I could call in Python That would tell me if the data is RSS or HTML? A: You could always analyze it yourself to search for an xml tag (for RSS) or html tag (for HTML). A: Filetypes should generally be determined out-of-band. eg. if...
Identifying if a data is RSS or HTML on python
Is there a function or method I could call in Python That would tell me if the data is RSS or HTML?
[ "You could always analyze it yourself to search for an xml tag (for RSS) or html tag (for HTML).\n", "Filetypes should generally be determined out-of-band. eg. if you are fetching the file from a web server, the place to look would be the Content-Type header of the HTTP response. If you're fetching a local file, ...
[ 2, 0 ]
[]
[]
[ "html", "python", "rss" ]
stackoverflow_0002882549_html_python_rss.txt
Q: Java/Python: Integration, problem with looping updating text Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the changes, so the output of the python will always be up t...
Java/Python: Integration, problem with looping updating text
Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the changes, so the output of the python will always be up to date with the window text. I'm trying to access this text in my ...
[ "I think I was able to reproduce your error by writing a simple python program to print random numbers and then sleep:\nimport random\nimport time\nimport sys\n\nrandom.seed(time.time())\n\nprint 'starting random numbers'\n#sys.stdout.flush()\nprint 'big block of text' * 2000\n#sys.stdout.flush()\n\ncount = 3\n\nwh...
[ 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002780038_java_python.txt
Q: Emacs/Python: running python-shell in line buffered vs. block buffered mode In a related question and answer here, someone hypothesized that python-shell within emacs(23.2) was block-buffered instead of line-buffered. The recommended fix was to add sys.stdout.flush() to the spot in my script where I want stdio to ...
Emacs/Python: running python-shell in line buffered vs. block buffered mode
In a related question and answer here, someone hypothesized that python-shell within emacs(23.2) was block-buffered instead of line-buffered. The recommended fix was to add sys.stdout.flush() to the spot in my script where I want stdio to flush its contents to the python-shell. Is there someway to trick python-shell (r...
[ "For those wondering, I think the relevant behavior is discussed here, in emacs \"7. Subprocesses\\ 7.3 Buffering in shells and subprocesses\".\n\"In a shell buffer, stdout is a pipe handle and so is buffered in blocks. If you would like the buffering behavior of your program to behave differently, the program itse...
[ 4 ]
[]
[]
[ "emacs", "output_buffering", "python" ]
stackoverflow_0002881346_emacs_output_buffering_python.txt
Q: Interpreted vs. Compiled vs. Late-Binding Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language. Ho...
Interpreted vs. Compiled vs. Late-Binding
Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language. How would Python be different from another interp...
[ "\nHow would Python be different from another interpreted language?\n\nThat involves hair-splitting. Interpreted languages and \"managed code\" languages like C# and virtual machine languages (like Java) form a weird continuum. There are folks who will say that all languages are \"interpreted\" -- even machine la...
[ 9, 7, 3, 2, 0 ]
[]
[]
[ "compiled", "java", "late_binding", "python" ]
stackoverflow_0002881526_compiled_java_late_binding_python.txt
Q: Converting python collaborative filtering code to use Map Reduce Using Python, I'm computing cosine similarity across items. given event data that represents a purchase (user,item), I have a list of all items 'bought' by my users. Given this input data (user,item) X,1 X,2 Y,1 Y,2 Z,2 Z,3 I build a python dictiona...
Converting python collaborative filtering code to use Map Reduce
Using Python, I'm computing cosine similarity across items. given event data that represents a purchase (user,item), I have a list of all items 'bought' by my users. Given this input data (user,item) X,1 X,2 Y,1 Y,2 Z,2 Z,3 I build a python dictionary {1: ['X','Y'], 2 : ['X','Y','Z'], 3 : ['Z']} From that dictionary,...
[ "This is not actually a \"MapReduce\" function but it should give you some significant speedup without all of the hassle.\nI would actually use numpy to \"vectorize\" the operation and make your life easier. From this you'll just need to loop through this dictionary and apply the vectorized function comparing this...
[ 6 ]
[]
[]
[ "collaborative_filtering", "hadoop", "optimization", "python", "similarity" ]
stackoverflow_0002881467_collaborative_filtering_hadoop_optimization_python_similarity.txt
Q: Running the same code for get(self) as post(self) Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of: class ListSubs(webapp.RequestHandler): def get(self):...
Running the same code for get(self) as post(self)
Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of: class ListSubs(webapp.RequestHandler): def get(self): self._run() def post(self): self....
[ "I would suggest both theoretical and practical reasons why the approach you're using (refactoring out the common code to a separate method and calling it from both post and get methods) is superior to the apparently-simpler alternative of just having one of those two methods call the other.\nFrom a theoretical vie...
[ 11, 2, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002882915_google_app_engine_python.txt
Q: Spawning a thread in python I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks. Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows. f...
Spawning a thread in python
I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks. Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows. from foobar import alice, bob char...
[ "Instead of switch-case, why not use a proper polymorphism? For example, here what you can do with duck typing in Python:\nIn, say, alice.py:\ndef do_stuff(data):\n print 'alice does stuff with %s' % data\n\nIn, say, bob.py:\ndef do_stuff(data):\n print 'bob does stuff with %s' % data\n\nThen in your client c...
[ 41, 5, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002882308_python.txt
Q: 2 different Django modules on Google App Engine I came across 2 different modules for porting Django to App Engine: http://code.google.com/p/app-engine-patch/ http://code.google.com/p/google-app-engine-django/ Both seem to be compatible with Django 1.0, The featured download of the latter is in Aug 08, whereas the...
2 different Django modules on Google App Engine
I came across 2 different modules for porting Django to App Engine: http://code.google.com/p/app-engine-patch/ http://code.google.com/p/google-app-engine-django/ Both seem to be compatible with Django 1.0, The featured download of the latter is in Aug 08, whereas the former is Feb 09. What are the relative merits? What...
[ "At the moment, the App Engine Patch is outdated.\nDjangoappengine and Django-Nonrel provide \"Native Django on App Engine\": \nhttp://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine \n", "It's a bit late to answer, but the problem I've had so far with app-engine-patch is that, while it'...
[ 6, 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000789902_django_google_app_engine_python.txt
Q: Faster Insertion of Records into a Table with SQLAlchemy I am parsing a log and inserting it into either MySQL or SQLite using SQLAlchemy and Python. Right now I open a connection to the DB, and as I loop over each line, I insert it after it is parsed (This is just one big table right now, not very experienced wi...
Faster Insertion of Records into a Table with SQLAlchemy
I am parsing a log and inserting it into either MySQL or SQLite using SQLAlchemy and Python. Right now I open a connection to the DB, and as I loop over each line, I insert it after it is parsed (This is just one big table right now, not very experienced with SQL). I then close the connection when the loop is done. T...
[ "The big thing you should try is putting a transaction around multiple inserts since it is the committing of the database to disk that really takes a long time. You'll need to decide the batching level, but a crude first attempt would be to wrap a transaction around the whole lot.\n", "Without knowing the table e...
[ 4, 3, 3 ]
[]
[]
[ "mysql", "python", "sql", "sqlalchemy", "sqlite" ]
stackoverflow_0002881890_mysql_python_sql_sqlalchemy_sqlite.txt
Q: How to parse large xml files on google app engine? I have fairly large xml file 1mb in size that i host on s3. I need to parse that xml file into my app engine datastore entirely. I have written a simple DOM parser that works fine locally but online it reaches the 30sec error and stops. I tried lowering the xml pa...
How to parse large xml files on google app engine?
I have fairly large xml file 1mb in size that i host on s3. I need to parse that xml file into my app engine datastore entirely. I have written a simple DOM parser that works fine locally but online it reaches the 30sec error and stops. I tried lowering the xml parsing by downloading the xml file into a BLOB at first b...
[ "For uploading large volumes of data, take a look at the Uploading and Downloading Data help page.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python", "sax", "xml" ]
stackoverflow_0002882732_google_app_engine_python_sax_xml.txt
Q: pyodbc on SQL Server - How can I do an insert and get the row ID back? I'm using pyodbc with SQL Server 2000. I want to be able to insert a row and get the auto incremented row id value back? Any ideas? Here's what I have so far: cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')"...
pyodbc on SQL Server - How can I do an insert and get the row ID back?
I'm using pyodbc with SQL Server 2000. I want to be able to insert a row and get the auto incremented row id value back? Any ideas? Here's what I have so far: cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')") cnxn.commit()
[ "Sorry, I asked too soon, it's addressed in their FAQ\nUse \"SELECT @@IDENTITY\". \n" ]
[ 10 ]
[]
[]
[ "django_pyodbc", "pyodbc", "python", "sql_server" ]
stackoverflow_0002883722_django_pyodbc_pyodbc_python_sql_server.txt
Q: How do I compile python extensions for Mac OS X 10.5, on Mac OS X 10.6? I'm trying to compile a variety of python extensions (pycrypto, paramiko, subvertpy...) on Mac OS X 10.6, such that they will be compatible with Mac OS X 10.5 and its built-in python 2.5, for including in a product installer targetted at Mac O...
How do I compile python extensions for Mac OS X 10.5, on Mac OS X 10.6?
I'm trying to compile a variety of python extensions (pycrypto, paramiko, subvertpy...) on Mac OS X 10.6, such that they will be compatible with Mac OS X 10.5 and its built-in python 2.5, for including in a product installer targetted at Mac OS X 10.5. I'm really not sure how to go about this. I dug around on Google an...
[ "I managed to get distutils to believe that Python was built on Leopard, by inserting the following code before the call to setup() in setup.py:\n# XXXHACK: make distutils believe that Python was built on Leopard.\nfrom distutils import sysconfig\ntheir_parse_makefile = sysconfig.parse_makefile\ndef my_parse_makefi...
[ 2 ]
[]
[]
[ "cross_compiling", "macos", "python" ]
stackoverflow_0002871013_cross_compiling_macos_python.txt
Q: Extracting and integrating data from separate lists in Python I have this code: cursor.execute( ''' SELECT id,DISTINCT tag FROM userurltag ''') tags = cursor.fetchall () T = [3,5,7,2,1,2,2,2,5,6,3,3,1,7,4] I have 7 groups names 1,...,7 . Each row in "tags" list corresponds to a row in "T" li...
Extracting and integrating data from separate lists in Python
I have this code: cursor.execute( ''' SELECT id,DISTINCT tag FROM userurltag ''') tags = cursor.fetchall () T = [3,5,7,2,1,2,2,2,5,6,3,3,1,7,4] I have 7 groups names 1,...,7 . Each row in "tags" list corresponds to a row in "T" list.the values of "T" say that for example the first row in "tags" l...
[ "cluster_to_tag = defaultdict(list)\n#May want to assert that length of tags and T is same\nfor tag,cluster in zip(tags, T):\n cluster_to_tag[cluster].append(tag)\n\n#cluster_to_tag now maps cluster ti list of tags\n\nhth\n" ]
[ 1 ]
[]
[]
[ "cluster_analysis", "list", "python" ]
stackoverflow_0002883808_cluster_analysis_list_python.txt
Q: Why is i++++++++i valid in python? I "accidentally" came across this weird but valid syntax i=3 print i+++i #outputs 6 print i+++++i #outputs 6 print i+-+i #outputs 0 print i+--+i #outputs 6 (for every even no: of minus symbol, it outputs 6 else 0, why?) Does this do anything useful? Update (Don't take it the wr...
Why is i++++++++i valid in python?
I "accidentally" came across this weird but valid syntax i=3 print i+++i #outputs 6 print i+++++i #outputs 6 print i+-+i #outputs 0 print i+--+i #outputs 6 (for every even no: of minus symbol, it outputs 6 else 0, why?) Does this do anything useful? Update (Don't take it the wrong way..I love python): One of Python's...
[ "Since Python doesn't have C-style ++ or -- operators, one is left to assume that you're negating or positivating(?) the value on the left.\nE.g. what would you expect i + +5 to be?\ni=3\nprint i + +(+i) #outputs 6\nprint i + +(+(+(+i))) #outputs 6\nprint i + -(+i) #outputs 0\nprint i + -(-(+i)) #outputs 6 \n\nNota...
[ 28, 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002883920_python.txt
Q: get expando model properties in python for google-app-engine How do I get all the properties from an expando model? (not just Model.properties()) I want to do something like this: ... recs = query.fetch( 100 ) for rec in recs: for name, value in rec.iteritem(): # figure out what, if any, expando prop...
get expando model properties in python for google-app-engine
How do I get all the properties from an expando model? (not just Model.properties()) I want to do something like this: ... recs = query.fetch( 100 ) for rec in recs: for name, value in rec.iteritem(): # figure out what, if any, expando properties are in this record but Model.iteritem() doesn't exist Th...
[ "rec.dynamic_properties() will give you a list of Expando properties\nhttp://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_dynamic_properties\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002883842_google_app_engine_python.txt
Q: Is str.replace(..).replace(..) ad nauseam a standard idiom in Python? For instance, say I wanted a function to escape a string for use in HTML (as in Django's escape filter): def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. ""...
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
For instance, say I wanted a function to escape a string for use in HTML (as in Django's escape filter): def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. """ return string.replace('&', '&amp;').replace('<', '&lt;').replace(...
[ "Do you have an application that is running too slow and you profiled it to find that a line like this snippet is causing it to be slow? Bottlenecks occur at unexpected places.\nThe current snippet traverses the string 5 times, doing one thing each time. You are suggesting traversing it once, probably doing doing f...
[ 24, 20, 13, 9, 7, 5, 3, 2, 1 ]
[]
[]
[ "idioms", "performance", "python", "replace" ]
stackoverflow_0002484156_idioms_performance_python_replace.txt
Q: pdb is not working in django doctests So I created the following file (testlib.py) to automatically load all doctests (throughout my nested project directories) into the __tests__ dictionary of tests.py: # ./testlib.py import os, imp, re, inspect from django.contrib.admin import site def get_module_list(start): ...
pdb is not working in django doctests
So I created the following file (testlib.py) to automatically load all doctests (throughout my nested project directories) into the __tests__ dictionary of tests.py: # ./testlib.py import os, imp, re, inspect from django.contrib.admin import site def get_module_list(start): all_files = os.walk(start) file_list...
[ "I was able to get pdb by tweaking it. I just put the following code at the bottom of my testlib.py file:\nimport sys, pdb\nclass TestPdb(pdb.Pdb):\n def __init__(self, *args, **kwargs):\n self.__stdout_old = sys.stdout\n sys.stdout = sys.__stdout__\n pdb.Pdb.__init__(self, *args, **kwargs)...
[ 4 ]
[]
[]
[ "django", "doctest", "pdb", "python" ]
stackoverflow_0002882885_django_doctest_pdb_python.txt
Q: tkinter integration with glib mainloop Is it possible to integrate tkinter with glib mainloop ? A: Here is one way of doing it: app=TkinterApp() def refreshApp(): app.update() return True gobject.idle_add(refreshApp) loop = gobject.MainLoop() loop.run()
tkinter integration with glib mainloop
Is it possible to integrate tkinter with glib mainloop ?
[ "Here is one way of doing it:\napp=TkinterApp()\n\ndef refreshApp():\n app.update()\n return True\n\ngobject.idle_add(refreshApp)\nloop = gobject.MainLoop()\nloop.run()\n\n" ]
[ 2 ]
[]
[]
[ "glib", "python", "tkinter" ]
stackoverflow_0002884528_glib_python_tkinter.txt
Q: Conditional operator in Mako using Pylons In PHP, I often use the conditional operator to add an attribute to an html element if it applies to the element in question. For example: <select name="blah"> <option value="1"<?= $blah == 1 ? ' selected="selected"' : '' ?>> One </option> <option value...
Conditional operator in Mako using Pylons
In PHP, I often use the conditional operator to add an attribute to an html element if it applies to the element in question. For example: <select name="blah"> <option value="1"<?= $blah == 1 ? ' selected="selected"' : '' ?>> One </option> <option value="2"<?= $blah == 2 ? ' selected="selected"' : '...
[ "If it's running Python, the \"ternary operator\" is\n# condition ? trueValue : falseValue\ntrueValue if condition else falseValue\n\n" ]
[ 5 ]
[]
[]
[ "conditional_operator", "mako", "php", "pylons", "python" ]
stackoverflow_0002884696_conditional_operator_mako_php_pylons_python.txt
Q: Writing XML from Python : Python equivalent of .NET XmlTextWriter? I have some IronPython code which makes use of XmlTextWriter which allows me to write code like self.writer = System.Xml.XmlTextWriter(filename, None) self.writer.Formatting = Formatting.Indented self.writer.WriteStartElement(name) self.writer.Writ...
Writing XML from Python : Python equivalent of .NET XmlTextWriter?
I have some IronPython code which makes use of XmlTextWriter which allows me to write code like self.writer = System.Xml.XmlTextWriter(filename, None) self.writer.Formatting = Formatting.Indented self.writer.WriteStartElement(name) self.writer.WriteString(str(text)) self.writer.WriteEndElement() ... self.writer.Close...
[ "I wrote a module named loxun to do just that: http://pypi.python.org/pypi/loxun/. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.\nExample usage:\nwith open(\"...\", \"wb\") as out:\n xml = XmlWriter(out)\n xml.addNamespace(\"xhtml\", \"http://www.w3.org/1999/xhtml\")\n xml.startT...
[ 3, 2, 2 ]
[]
[]
[ "ironpython", "jython", "python", "xml" ]
stackoverflow_0001022429_ironpython_jython_python_xml.txt
Q: Check to see if system volume is muted? I am working on a project that plays audio for part of the program. I would like to be able to display a message if the user's system volume is muted. I am using Python on Windows. A: Use the Windows Mixer API. I've found this article for you, and attached the relevant cod...
Check to see if system volume is muted?
I am working on a project that plays audio for part of the program. I would like to be able to display a message if the user's system volume is muted. I am using Python on Windows.
[ "Use the Windows Mixer API. I've found this article for you, and attached the relevant code:\n(From MS KB 181550: \"Monitor Audio Volume Levels\")\nThis is in C, but it can be \"translated\" to Python as well.\nI hope that helps. \n#include <windows.h>\n#include <mmsystem.h>\n\nMMRESULT rc; // Return c...
[ 3 ]
[]
[]
[ "mute", "python", "volume", "windows" ]
stackoverflow_0002864507_mute_python_volume_windows.txt
Q: C++ Structure within itself? I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me): typedef struct huffnode_s { struct huffnode_s *zero; struct huffnode_s *one; unsigned char val; float freq; } huffnode_t...
C++ Structure within itself?
I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me): typedef struct huffnode_s { struct huffnode_s *zero; struct huffnode_s *one; unsigned char val; float freq; } huffnode_t; What I don't get is how huffnod...
[ "huffnode_s isn't within itself, only pointers to huffnode_s are in there. Since a pointer is of known size, it's no problem.\n", "This.\nclass Huffnode(object):\n def __init__(self, zero, one, val, freq):\n \"\"\"zero and one are Huffnode's, val is a 'char' and freq is a float.\"\"\"\n self.zer...
[ 19, 11, 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "c", "c++", "huffman_code", "python" ]
stackoverflow_0002885502_c_c++_huffman_code_python.txt
Q: Python csv reader acting weird So OK if I run this wrong code: csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',') for row1 in csvReader1: print row1[0] print row1[8] category_sku = str(row[8]) if category_sku == sku: classifications["Craft"] = row[0] classifica...
Python csv reader acting weird
So OK if I run this wrong code: csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',') for row1 in csvReader1: print row1[0] print row1[8] category_sku = str(row[8]) if category_sku == sku: classifications["Craft"] = row[0] classifications["Theme"] = row[1] I get: ...
[ "The output contains results from every row because you are printing the 1st and 9th columns for every row.\nrow1[0] is out of range for whatever row that is because there aren't any items on that particular line of the file. You can't access the first item in row1 if row1 doesn't have any items to access. Check ...
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002885627_csv_python.txt
Q: SWIG: Throwing exceptions from Python to C++ We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code...
SWIG: Throwing exceptions from Python to C++
We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on ...
[ "(C)Python is written in C. It seems that it could be bad to throw exceptions \"through\" the interpreter.\nMy feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.\nThat's basically what we do here, although we're using C# instead of Python t...
[ 2 ]
[]
[]
[ "c++", "exception_handling", "python", "swig" ]
stackoverflow_0002884797_c++_exception_handling_python_swig.txt
Q: Errors when compiling mod_wsgi for python2.6 on Cent OS 5.3 I am running a website on CentOS 5.3. I understand centos will break if the default python 2.4 is upgraded. I followed this site (http://www.question-defense.com/2009/12/25/how-to-install-python-2-6-on-centos-5-without-breaking-yum) and got python 2.6 ins...
Errors when compiling mod_wsgi for python2.6 on Cent OS 5.3
I am running a website on CentOS 5.3. I understand centos will break if the default python 2.4 is upgraded. I followed this site (http://www.question-defense.com/2009/12/25/how-to-install-python-2-6-on-centos-5-without-breaking-yum) and got python 2.6 installed. Now if I run "python" it runs python2.4 and if I run "pyt...
[ "You must install the development packages for both Apache and Python. Read the instructions for installing mod_wsgi and it tells you that. See:\nhttp://code.google.com/p/modwsgi/wiki/QuickInstallationGuide\nor the README that comes with the mod_wsgi source code.\n" ]
[ 1 ]
[]
[]
[ "centos5", "mod_wsgi", "python" ]
stackoverflow_0002883514_centos5_mod_wsgi_python.txt
Q: os.walk in python not running with cmd line parameter passed as path I needed to find the number of files in a folder on the system. This is what i used: file_count = sum((len(f) for _, _, f in os.walk('path'))) This works fine when we specify the path as a string in quotes, but when I enter a variable name that...
os.walk in python not running with cmd line parameter passed as path
I needed to find the number of files in a folder on the system. This is what i used: file_count = sum((len(f) for _, _, f in os.walk('path'))) This works fine when we specify the path as a string in quotes, but when I enter a variable name that holds the path, type(file_count) is a generator object, and hence cannot ...
[ "I assume you're using walk because you want to know every single file in the directory and its subdirectories. I do not understand what happens here:\nfile_count = sum((len(f) for _, _, f in os.walk(path)))\nAssuming path contains, let's say, 'src' which is a directory in my home dir I get the number of files in t...
[ 0, 0, 0 ]
[]
[]
[ "os.walk", "python" ]
stackoverflow_0002880604_os.walk_python.txt
Q: What is ODBC and how can I take advantage of it (Linux)? I am creating a master database using SQLite. This single file contains a dozen tables. I want everybody in my group to have access to it (either through Python or through the SQLite command line) and I was thinking of simply putting the file in a group read...
What is ODBC and how can I take advantage of it (Linux)?
I am creating a master database using SQLite. This single file contains a dozen tables. I want everybody in my group to have access to it (either through Python or through the SQLite command line) and I was thinking of simply putting the file in a group readable directory and calling it 'master.db'. Now, the buzz word ...
[ "If it's only small numbers of people who access you db then you should be ok. However, SQlite sucks at large numbers of concurrent accesses - I switched over from sqlite to mysql when I had lots of concurrent access because the db kept getting locked.\nFor many concurrent accesses, you need something in between it...
[ 1, 0 ]
[]
[]
[ "odbc", "python" ]
stackoverflow_0002885495_odbc_python.txt
Q: how to re-invoke python script within itself I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285. The START_CTX is created at http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbit...
how to re-invoke python script within itself
I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285. The START_CTX is created at http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86. The code is relying on sys.argv[0] a...
[ "I think the real issue here is that the gunicorn/arbiter.py code wants to execute the Python script with the exact same environment every time. This is important because the Python script being invoked is an unknown and it is important for it be called exactly the same way every time.\nMy feeling is that the probl...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002846416_python.txt
Q: what does 'cgi.parse_qs' mean i find this code : def _oauth_parse_response(body): p = cgi.parse_qs(body, keep_blank_values=False) but i don't know what is mean thanks A: It means "look on the cgi object for an attribute called parse_qs, and call it as a function with body as a positional argument and keep...
what does 'cgi.parse_qs' mean
i find this code : def _oauth_parse_response(body): p = cgi.parse_qs(body, keep_blank_values=False) but i don't know what is mean thanks
[ "It means \"look on the cgi object for an attribute called parse_qs, and call it as a function with body as a positional argument and keep_blank_values as a keyword argument with the value of False\".\nFor the definition of cgi look further up, but it probably is the stdlib module of the same name.\n", "docs.pyth...
[ 5, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002886611_python.txt
Q: Streaming audio (YouTube) I'm writing a CLI for a music-media-platform. One of the features is going to be that you can directly play YouTube videos from the CLI. I don't really have an idea of how to do it, but this one sounded the most reasonable: I'm going to use of those sites where you can download music from...
Streaming audio (YouTube)
I'm writing a CLI for a music-media-platform. One of the features is going to be that you can directly play YouTube videos from the CLI. I don't really have an idea of how to do it, but this one sounded the most reasonable: I'm going to use of those sites where you can download music from YouTube, for example, http://k...
[ "You need two things to be able to download a YouTube video, the video id, which is represented by the v= section of the URL, and a hidden field t= which is present in the page source. I have no idea what this t value is, but it's what you need :)\nYou can then download the video using a URL in the format;\nhttp://...
[ 2, 0 ]
[]
[]
[ "audio", "python", "stream", "youtube" ]
stackoverflow_0002884588_audio_python_stream_youtube.txt
Q: Scrapy Could not find spider Error I have been trying to get a simple spider to run with scrapy, but keep getting the error: Could not find spider for domain:stackexchange.com when I run the code with the expression scrapy-ctl.py crawl stackexchange.com. The spider is as follow: from scrapy.spider import BaseSpide...
Scrapy Could not find spider Error
I have been trying to get a simple spider to run with scrapy, but keep getting the error: Could not find spider for domain:stackexchange.com when I run the code with the expression scrapy-ctl.py crawl stackexchange.com. The spider is as follow: from scrapy.spider import BaseSpider from __future__ import absolute_import...
[ "try running python yourproject/spiders/domain.py to see if there are any syntax error. I don't think you should enable absolute import as scrapy relies on relatives imports.\n" ]
[ 2 ]
[]
[]
[ "dns", "python", "scrapy" ]
stackoverflow_0002886503_dns_python_scrapy.txt
Q: Cookies with urllib This will probably seem like a really simple question, and I am quite confused as to why this is so difficult for me. I would like to write a function that takes three inputs: [url, data, cookies] that will use urllib (not urllib2) to get the contents of the requested url. I figured it'd be sim...
Cookies with urllib
This will probably seem like a really simple question, and I am quite confused as to why this is so difficult for me. I would like to write a function that takes three inputs: [url, data, cookies] that will use urllib (not urllib2) to get the contents of the requested url. I figured it'd be simple, so I wrote the follo...
[ "You didn't say what went wrong when you tried it, or what http server you're testing with. Did the request complete? Did the server fail to recognize your cookies? One thing that jumps out at me is that you're potentially joining multiple cookies into a single header field. Does it work if you use separate Coo...
[ 1 ]
[]
[]
[ "cookies", "python", "urllib" ]
stackoverflow_0002886573_cookies_python_urllib.txt
Q: how to import a 'zip' file to my .py when i use http://github.com/joshthecoder/tweepy-examples , i find : import tweepy in the appengine\oauth_example\handlers.py but i can't find a tweepy file or tweepy's 'py' file, except a tweepy.zip file, i don't think this is right,cauz i never import a zip file, i find th...
how to import a 'zip' file to my .py
when i use http://github.com/joshthecoder/tweepy-examples , i find : import tweepy in the appengine\oauth_example\handlers.py but i can't find a tweepy file or tweepy's 'py' file, except a tweepy.zip file, i don't think this is right,cauz i never import a zip file, i find this in app.py: import sys sys.path.insert(0,...
[ "The name of the zip file is irrelevent when searching for modules - this allows you to include version numbers in the file name, such as my_b_package.1.2.3.zip. \nTo import from a zip file, you need to replicate the full package structure within it. In this case, you need a package b, with the __init__.py and c.p...
[ 11, 3 ]
[]
[]
[ "import", "python", "zip" ]
stackoverflow_0002886850_import_python_zip.txt
Q: Django Barcode for store sales I am in process of converting Visual Basic app into Python Django. Currently, it has barcode functionality to process sales at a store. Can this be achieved with python django. A: If your definition of barcode functionality is the ability to read and write barcodes, you should keep...
Django Barcode for store sales
I am in process of converting Visual Basic app into Python Django. Currently, it has barcode functionality to process sales at a store. Can this be achieved with python django.
[ "If your definition of barcode functionality is the ability to read and write barcodes, you should keep in mind two things.\n\nBarcodes are actually read by barcode readers, and from the computers' point of view they are just input devices, just like keyboards. When the reader reads a barcode, it just \"types\" it ...
[ 9 ]
[]
[]
[ "django", "python", "vb6" ]
stackoverflow_0002887045_django_python_vb6.txt