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: Is there a portable way of finding if a path is absolute, using Python? Is there some built-in function that tells me if a path is absolute or not? I'd like something that is platform independent. A: The os.path.isabs function does this.
Is there a portable way of finding if a path is absolute, using Python?
Is there some built-in function that tells me if a path is absolute or not? I'd like something that is platform independent.
[ "The os.path.isabs function does this.\n" ]
[ 13 ]
[]
[]
[ "absolute_path", "python" ]
stackoverflow_0001513155_absolute_path_python.txt
Q: Python optparse defaults vs function defaults I'm writing a python script which I would like to be able to both call from the command line and import as a library function. Ideally the command line options and the function should use the same set of default values. What is the best way to allow me to reuse a singl...
Python optparse defaults vs function defaults
I'm writing a python script which I would like to be able to both call from the command line and import as a library function. Ideally the command line options and the function should use the same set of default values. What is the best way to allow me to reuse a single set of defaults in both places? Here's the curren...
[ "I'd handle it by introspecting the function of interest to set options and defaults appropriately. For example:\nimport inspect\nfrom optparse import OptionParser\nimport sys\n\ndef do_stuff(opt0, opt1=\"a\", opt2=\"b\", opt3=\"c\"):\n print opt0, opt1, opt2, opt3\n\nif __name__ == \"__main__\":\n parser = ...
[ 3, 2, 2 ]
[]
[]
[ "dry", "optparse", "python" ]
stackoverflow_0001512242_dry_optparse_python.txt
Q: verifiedEmail AOL OpenID I can't seem to fetch the verifiedEmail field when trying to login to AOLs OpenID on my site. Every other provider that I know of provides this property, but not AOL. I realize that AOL somehow uses an old OpenID version, although is it feasible to just assume that their e-mail ends in @ao...
verifiedEmail AOL OpenID
I can't seem to fetch the verifiedEmail field when trying to login to AOLs OpenID on my site. Every other provider that I know of provides this property, but not AOL. I realize that AOL somehow uses an old OpenID version, although is it feasible to just assume that their e-mail ends in @aol.com? I'm using the RPXNow li...
[ "I believe that OpenID lets the user decide how much information to \"share\" during the login process. I can't say that I am an expert on the subject, but I know that my identity at myopenid.com lets me specify precisely what information to make available.\nIs it possible that the AOL default is to share nothing?...
[ 0 ]
[]
[]
[ "openid", "python", "rpxnow" ]
stackoverflow_0001513543_openid_python_rpxnow.txt
Q: can't install lxml (python 2.6.3, osx 10.6 snow leopard) I try to: easy_install lxml and I get this error: File "build/bdist.macosx-10.3-fat/egg/setuptools/command/build_ext.py", line 85, in get_ext_filename KeyError: 'etree' any hints? A: Due to incompatible changes in the 2.6.3 version of python's dist...
can't install lxml (python 2.6.3, osx 10.6 snow leopard)
I try to: easy_install lxml and I get this error: File "build/bdist.macosx-10.3-fat/egg/setuptools/command/build_ext.py", line 85, in get_ext_filename KeyError: 'etree' any hints?
[ "Due to incompatible changes in the 2.6.3 version of python's distutils, the old easy_install from setuptools no longer works. You need to replace it with easy_install from Distribute. Follow the instructions there, basically:\n$ curl -O http://nightly.ziade.org/distribute_setup.py\n$ python distribute_setup.py\n...
[ 7, 3 ]
[]
[]
[ "lxml", "macos", "osx_leopard", "port", "python" ]
stackoverflow_0001512530_lxml_macos_osx_leopard_port_python.txt
Q: Python Pypi: what is your process for releasing packages for different Python versions? (Linux) I've got several eggs I maintain on Pypi but up until now I've always focused on Python 2.5x. I'd like to release my eggs under both Python 2.5 & Python 2.6 in an automated fashion i.e. running tests generating doc pr...
Python Pypi: what is your process for releasing packages for different Python versions? (Linux)
I've got several eggs I maintain on Pypi but up until now I've always focused on Python 2.5x. I'd like to release my eggs under both Python 2.5 & Python 2.6 in an automated fashion i.e. running tests generating doc preparing eggs uploading to Pypi How do you guys achieve this? A related question: how do I tag an egg...
[ "You don't need to release eggs for anything else than Windows, and then only if your package uses C extensions so that they have compiled parts. Otherwise you simply release one source distribution. That will be enough for all Python versions on all platforms.\nRunning the tests for different versions automated is...
[ 1, 0 ]
[]
[]
[ "pypi", "python", "release_management" ]
stackoverflow_0001512644_pypi_python_release_management.txt
Q: Why MySQLdb for Mac has to have MySQL installed to install? I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? MySQLdb suppose ...
Why MySQLdb for Mac has to have MySQL installed to install?
I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? MySQLdb suppose to be a client module for the client who wants to connect to the ...
[ "Just to complete the fine answers, here's a small how-to for installing MySQLdb on MacOS X 10.6. This was posted on my blog and you might check that out for maybe more info (and links as I'm a new user on stackoverflow, can only add one).\n\nDownload MySQL MacOS X 10.5 (x86_64) tar ball. For v10.5 currently, until...
[ 3, 1, 1, 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001483024_mysql_python.txt
Q: Installing python module I'm new to python and is trying to install the pyimage module. http://code.google.com/p/pyimage/ I'm on Windows, and have downloaded and installed 2.6 and 3.1. I downloaded pyimage, and used cmd and cd to get to its dir. I then got this: C:\Users\Jourkey\Desktop\pyimage-0.8.13\pyimage-0.8....
Installing python module
I'm new to python and is trying to install the pyimage module. http://code.google.com/p/pyimage/ I'm on Windows, and have downloaded and installed 2.6 and 3.1. I downloaded pyimage, and used cmd and cd to get to its dir. I then got this: C:\Users\Jourkey\Desktop\pyimage-0.8.13\pyimage-0.8.13>python setup.py install 'py...
[ "It is giving you that error because Python is not in your path. By default, the Python executable is not added to the path. You will have to do it manually. An in-depth tutorial endorsed by the Python website may be found\nhere.\n", "To put Python on your system's environment PATH variable, so that running pytho...
[ 4, 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0001514371_module_python.txt
Q: Python 3 and open source: Are there any good projects? I've been studying Python 3 recently and I have come across a conundrum: I want to expand my abilities by working on an open source project, but I seem to have trouble finding any specifically for Python 3. I know that this question has been asked before: Such...
Python 3 and open source: Are there any good projects?
I've been studying Python 3 recently and I have come across a conundrum: I want to expand my abilities by working on an open source project, but I seem to have trouble finding any specifically for Python 3. I know that this question has been asked before: Such as here, And here, Unfortunately these all seem to be using...
[ "If you want to help out with Python 3, find some libraries that haven't been ported yet and help port them. Projects that depend on these libraries can't make the switch until the libraries do. \n", "Major point releases of languages take an exceedingly long time for wide adoption. Python 3 will not die -- event...
[ 7, 4, 0 ]
[]
[]
[ "open_source", "python", "python_3.x" ]
stackoverflow_0001462282_open_source_python_python_3.x.txt
Q: Writing Cocoa applications in Python 3 It looks like PyObjC is not ported to Python 3 yet. Meanwhile is there a way to write Cocoa applications using Python 3? I am intending to start a new MacOSX GUI application project and though5 would want to use Python 3.x instead of Python 2.x. A: For full-blown Cocoa, I t...
Writing Cocoa applications in Python 3
It looks like PyObjC is not ported to Python 3 yet. Meanwhile is there a way to write Cocoa applications using Python 3? I am intending to start a new MacOSX GUI application project and though5 would want to use Python 3.x instead of Python 2.x.
[ "For full-blown Cocoa, I think PyObjC is pretty much the only game in town. If you are coming to Cocoa from a Python background rather than to Python from an Obj-C Cocoa background, surely the learning curve of the Cocoa APIs is much steeper than the differences between Python 2.x and Python 3.x. So I think, at t...
[ 3 ]
[]
[]
[ "cocoa", "pyobjc", "python", "python_3.x" ]
stackoverflow_0001514638_cocoa_pyobjc_python_python_3.x.txt
Q: How to get a http page using mechanize cookies? There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need ...
How to get a http page using mechanize cookies?
There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need to get body string of another page, nothing else). So...
[ "And the correct answer:\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.br._ua_handlers[\"_cookies\"].cookiejar))\nopener.open(imgurl)\n\n", "No idea whether this will work, but why don't you try deepcopying the mechanize instance, eg\nfrom copy import deepcopy\nbr = Browser()\nbr.open(\"http://w...
[ 5, 2, 2 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001513823_mechanize_python.txt
Q: Why my code is getting NZEC run time error? Question source: SPOJ.. ORDERS def swap(ary,idx1,idx2): tmp = ary[idx1] ary[idx1] = ary[idx2] ary[idx2] = tmp def mkranks(size): tmp = [] for i in range(1, size + 1): tmp = tmp + [i] return tmp def permutations(ordered, movements): s...
Why my code is getting NZEC run time error?
Question source: SPOJ.. ORDERS def swap(ary,idx1,idx2): tmp = ary[idx1] ary[idx1] = ary[idx2] ary[idx2] = tmp def mkranks(size): tmp = [] for i in range(1, size + 1): tmp = tmp + [i] return tmp def permutations(ordered, movements): size = len(ordered) for i in range(1, size): #...
[ "Having made your code a bit more Pythonic (but without altering its flow/algorithm):\ndef swap(ary, idx1, idx2):\n ary[idx1], ary[idx2] = [ary[i] for i in (idx2, idx1)]\n\ndef permutations(ordered, movements):\n size = len(ordered)\n for i in range(1, len(ordered)):\n for j in range(movements[i]):\...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001515019_python.txt
Q: Is it reasonable to save data as python modules? This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into...
Is it reasonable to save data as python modules?
This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure. Is this reasonable? Are there ...
[ "By operating this way, you may gain some modicum of convenience, but you pay many kinds of price for that. The space it takes to save your data, and the time it takes to both save and reload it, go up substantially; and your security exposure is unbounded -- you must ferociously guard the paths from which you relo...
[ 7, 3, 3, 3, 3 ]
[]
[]
[ "data_persistence", "dynamic_import", "python" ]
stackoverflow_0001514228_data_persistence_dynamic_import_python.txt
Q: Upgrading Google Application Engine program to use unicode I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users wh...
Upgrading Google Application Engine program to use unicode
I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.)
[ "Alexander Kojevnikov said: \"The datastore internally keeps all strings in unicode.\"\nIn other words, your application is already using unicode everywhere. Thank the google folks for a sensible API. No further work required.\n", "The datastore internally keeps all strings in unicode.\n", "When storing to a db...
[ 2, 1, 1 ]
[]
[]
[ "google_app_engine", "python", "unicode" ]
stackoverflow_0000245094_google_app_engine_python_unicode.txt
Q: is there any latest version of pyUIQ? i have tried to install python for symbian uiq 3..i have tried signed and unsigned version,but both installation failed..anyone faced same problem?so,do you have any solution? i am using sony ericsson G900.. A: The latest release version of PyUIQ is 0.2, from YEARS ago, avai...
is there any latest version of pyUIQ?
i have tried to install python for symbian uiq 3..i have tried signed and unsigned version,but both installation failed..anyone faced same problem?so,do you have any solution? i am using sony ericsson G900..
[ "The latest release version of PyUIQ is 0.2, from YEARS ago, available here. No sources in the CVS repo on sourceforge, either... looks pretty much like a dead project to me:-(. What do you need exactly?\n", "Even though the pyUIQ version available is very old, you should be able to install it if you sign it pro...
[ 1, 0 ]
[]
[]
[ "python", "symbian" ]
stackoverflow_0001515630_python_symbian.txt
Q: Display Pretty Code in Django I'm looking for something I can use within django to display preformatted code. Ideally this would include out-of-the-box syntax highlighting for various programming languages, although just starting with something that displayed html and xml well would be a good starting point. Does...
Display Pretty Code in Django
I'm looking for something I can use within django to display preformatted code. Ideally this would include out-of-the-box syntax highlighting for various programming languages, although just starting with something that displayed html and xml well would be a good starting point. Does something like this exist? Basic...
[ "You could use Pygments to do the syntax highlighting and get HTML to display.\nExample code :\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\nhighlighted = highlight('# Some Python code', PythonLexer(), HtmlFormatter())\n\nAlso see the offi...
[ 8, 2 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0001514874_django_html_python.txt
Q: Does C++ have an equivilent to Python's __setitem__ Just as the title asks, does C++ have the equivalent of Python's setitem and getitem for classes? Basically it allows you to do something like the following. MyClass anObject; anObject[0] = 1; anObject[1] = "foo"; A: basically, you overload the subscript opera...
Does C++ have an equivilent to Python's __setitem__
Just as the title asks, does C++ have the equivalent of Python's setitem and getitem for classes? Basically it allows you to do something like the following. MyClass anObject; anObject[0] = 1; anObject[1] = "foo";
[ "basically, you overload the subscript operator (operator[]), and it returns a reference (so it can be read as well as written to)\n", "You can overload the [] operator, but it's not quite the same as a separate getitem/setitem method pair, in that you don't get to specify different handling for getting and setti...
[ 7, 6, 1, 1 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0001515899_c++_python.txt
Q: List sorting with multiple attributes and mixed order I have to sort a list with multiple attributes. I can do that in ascending order for ALL attributes easily with L.sort(key=operator.attrgetter(attribute)).... but the problem is, that I have to use mixed configurations for ascending/descending... I have to "im...
List sorting with multiple attributes and mixed order
I have to sort a list with multiple attributes. I can do that in ascending order for ALL attributes easily with L.sort(key=operator.attrgetter(attribute)).... but the problem is, that I have to use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By where you can do something li...
[ "If your attributes are numeric, you have this.\ndef mixed_order( a ):\n return ( a.attribute1, -a.attribute2 )\n\nsomeList.sort( key=mixed_order )\n\nIf your attributes includes strings or other more complex objects, you have some choices.\nThe .sort() method is stable: you can do multiple passes. This is perh...
[ 33, 7, 6 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0001516249_list_python_sorting.txt
Q: python varargs before function name? I'm doing some Python coding in a clients code base and I stumbled on a line of code that looks something like this (the variable names have been changed to protect the innocent): reply = function1(a=foo, **function2(bar, b=baz)) Normally ** in the argument list collects remai...
python varargs before function name?
I'm doing some Python coding in a clients code base and I stumbled on a line of code that looks something like this (the variable names have been changed to protect the innocent): reply = function1(a=foo, **function2(bar, b=baz)) Normally ** in the argument list collects remaining keyword arguments but what do they do...
[ "I'd say that this is just calling a function that returns a dict-like object and therefor the asterisks just convert the returned dict into the keyword arguments for function1, just as usual.\n" ]
[ 11 ]
[]
[]
[ "python", "variadic_functions" ]
stackoverflow_0001516467_python_variadic_functions.txt
Q: chess AI for GAE I am looking for a Chess AI that can be run on Google App Engine. Most chess AI's seem to be written in C and so can not be run on the GAE. It needs to be strong enough to beat a casual player, but efficient enough that it can calculate a move within a single request (less than 10 secs). Ideally i...
chess AI for GAE
I am looking for a Chess AI that can be run on Google App Engine. Most chess AI's seem to be written in C and so can not be run on the GAE. It needs to be strong enough to beat a casual player, but efficient enough that it can calculate a move within a single request (less than 10 secs). Ideally it would be written in ...
[ "What's wrong with PyChess? It's pure Python, fairly mature, and will certainly be able to beat a casual player.\nIt's been a while since I've used PyChess, but a quick glance through some of the source\ndoes indicate that you can set a time limit on how long to search for a move.\nThe PyChess engine that is writt...
[ 5, 1 ]
[]
[]
[ "artificial_intelligence", "chess", "google_app_engine", "python" ]
stackoverflow_0001516223_artificial_intelligence_chess_google_app_engine_python.txt
Q: sqlite3 in Python How do I check if the database file already exists or not? And, if the it exists, how do I check if it already has a specific table or not? A: To see if a database exists, you can sqlite3.connect to the file that you think contains the database, and try running a query on it. If it is not a d...
sqlite3 in Python
How do I check if the database file already exists or not? And, if the it exists, how do I check if it already has a specific table or not?
[ "To see if a database exists, you can sqlite3.connect to the file that you think contains the database, and try running a query on it. If it is not a database, you will get this error:\n>>> c.execute(\"SELECT * FROM tbl\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nsqlite3.Databa...
[ 10 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001516508_python_sqlite.txt
Q: Displaying integers in a wxpython listctrl I have a wxPython ListCtrl with five columns. Four of these hold strings, the last one has integer values. I have been storing these as strings (i.e. '4', '17', etc.). However, now that I have added a ColumnSorterMixin to let me sort specific columns in the list, I'm find...
Displaying integers in a wxpython listctrl
I have a wxPython ListCtrl with five columns. Four of these hold strings, the last one has integer values. I have been storing these as strings (i.e. '4', '17', etc.). However, now that I have added a ColumnSorterMixin to let me sort specific columns in the list, I'm finding, of course, that the integer column is being...
[ "I think that the most robust way of doing custom sort is to use SortItems() function in wx.ListCtrl. Note that you have to provide item data for each item (using SetItemData()) \nJust provide your own callback, say:\ndef sortColumn(item1, item2):\n try: \n i1 = int(item1)\n i2 = int(item2)\n ex...
[ 2 ]
[]
[]
[ "listctrl", "python", "wxpython" ]
stackoverflow_0001516742_listctrl_python_wxpython.txt
Q: How to remove existing background color of text when highlighting? I'm writing a small utility in Python that does some pattern matching of text. Text that matches the pattern the user has entered gets highlighted yellow. I'm achieving this using a Tkinter Text widget, and setting up a tag on the Text widget na...
How to remove existing background color of text when highlighting?
I'm writing a small utility in Python that does some pattern matching of text. Text that matches the pattern the user has entered gets highlighted yellow. I'm achieving this using a Tkinter Text widget, and setting up a tag on the Text widget named "match" that gives any text with the tag name "match" a yellow backg...
[ "Tags have priority. Tags with a high priority have preference over those that have a lower priority. When you select a range of text it is given the tag \"sel\". You simply need to raise the priority of the \"sel\" tag to be above the priority of your \"match\" tag:\nw.tag_raise(\"sel\")\n\nAlex Martelli writes in...
[ 3, 0 ]
[]
[]
[ "background", "colors", "highlight", "python", "tkinter" ]
stackoverflow_0001515809_background_colors_highlight_python_tkinter.txt
Q: Python's insert returning None? #!/usr/bin/python numbers = [1, 2, 3, 5, 6, 7] clean = numbers.insert(3, 'four') print clean # desire results [1, 2, 3, 'four', 5, 6, 7] I am getting "None". What am I doing wrong? A: Mutating-methods on lists tend to return None, not the modified list as you expect -- such me...
Python's insert returning None?
#!/usr/bin/python numbers = [1, 2, 3, 5, 6, 7] clean = numbers.insert(3, 'four') print clean # desire results [1, 2, 3, 'four', 5, 6, 7] I am getting "None". What am I doing wrong?
[ "Mutating-methods on lists tend to return None, not the modified list as you expect -- such metods perform their effect by altering the list in-place, not by building and returning a new one. So, print numbers instead of print clean will show you the altered list.\nIf you need to keep numbers intact, first you mak...
[ 18, 10, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001516889_list_python.txt
Q: Using Django as a Backend for Cappuccino I'm new to both Django and Cappuccino. I have a Django site setup and running through Apache via mod_wsgi. I want to use Django as the backend for a Cappuccino application, but a VirtualHost setup in Apache and mod_wsgi to serve a Django application serves static files out ...
Using Django as a Backend for Cappuccino
I'm new to both Django and Cappuccino. I have a Django site setup and running through Apache via mod_wsgi. I want to use Django as the backend for a Cappuccino application, but a VirtualHost setup in Apache and mod_wsgi to serve a Django application serves static files out of a different location than the normal web ro...
[ "Have you read:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines\nThis goes into various aspects of using WSGIScriptAlias for mod_wsgi and Alias directives for static files.\nI'd suggest you ensure your read that, or reread it, and then post what configuration you have tried already as that will help ...
[ 1, 0 ]
[]
[]
[ "apache", "cappuccino", "django", "mod_wsgi", "python" ]
stackoverflow_0001515578_apache_cappuccino_django_mod_wsgi_python.txt
Q: how to run both python 2.6 and 3.0 on the same windows XP box? What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine? A: No problem, each version is installed in its own directory. On my Windows box, I have C:\Python26\ and C:\Python31\. The Start Menu items are also ...
how to run both python 2.6 and 3.0 on the same windows XP box?
What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?
[ "No problem, each version is installed in its own directory. On my Windows box, I have C:\\Python26\\ and C:\\Python31\\. The Start Menu items are also distinct. Just use the standard installers from the Python Programming Language Official Website, or the ready-to-install distributions from ActiveState.\nA direct ...
[ 9, 1, 1, 1, 0 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0001515850_python_windows_xp.txt
Q: monitor service for "failure" I'm developing a script which monitors a service for failure and launches another a different action depending on if failure is present or not. I require a python script to monitor the output from a python program "monitor-services" and parsing the output search for an occurance of t...
monitor service for "failure"
I'm developing a script which monitors a service for failure and launches another a different action depending on if failure is present or not. I require a python script to monitor the output from a python program "monitor-services" and parsing the output search for an occurance of the word "failure". If present, the ...
[ "#!/usr/bin/python\nfrom subprocess import Popen, PIPE\nimport sys\n\ndata = Popen([\"monitor-services\"], stdout=PIPE).communicate()[0]\n\nsys.exit(\"failure\" in data)\n\nThis does everything you want, except for the 30s wait (which I don't understand). Notice that it returns 0 if failure is not found, 1 if it is...
[ 1 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0001516943_python_scripting.txt
Q: Compound UniqueConstraint with a function A quick SQLAlchemy question... I have a class "Document" with attributes "Number" and "Date". I need to ensure that there's no duplicated number for the same year, is there a way to have a UniqueConstraint on "Number + year(Date)"? Should I use a unique Index instead? H...
Compound UniqueConstraint with a function
A quick SQLAlchemy question... I have a class "Document" with attributes "Number" and "Date". I need to ensure that there's no duplicated number for the same year, is there a way to have a UniqueConstraint on "Number + year(Date)"? Should I use a unique Index instead? How would I declare the functional part? (SQLAlc...
[ "You should use a functional unique index to apply this constraint. Unfortunately the database generic database independent schema definition machinery in SQLAlchemy doesn't abstract functional indexes yet. You'll have to use the DDL construct to register custom schema definition clauses. If you are using the decla...
[ 4 ]
[ "I'm pretty sure that unique constraints can only be applied on columns that already have data in them, and not on runtime-calculated expressions. Hence, you would need to create an extra column which contains the year part of your date, over which you could create a unique constraint together with number. To best ...
[ -1 ]
[ "constraints", "python", "sqlalchemy" ]
stackoverflow_0001510018_constraints_python_sqlalchemy.txt
Q: Cutting text from IPython shell using Ctrl-X is broken I use IPython very frequently and happily. Somehow, cutting text from the shell using the keyboard shortcut, Ctrl + X, is broken. Actually, I have a few different installations of IPython. In some of the installations, the shortcut works; in the others, it doe...
Cutting text from IPython shell using Ctrl-X is broken
I use IPython very frequently and happily. Somehow, cutting text from the shell using the keyboard shortcut, Ctrl + X, is broken. Actually, I have a few different installations of IPython. In some of the installations, the shortcut works; in the others, it doesn't work. What might be the reason for this? Where should I...
[ "You say you have multiple instances installed -- are these all on different machines? What operating system(s) are they running? If you access them remotely, what operating system are you running?\nDo you get to them using ssh? Do you run something like screen, either locally or remotely, or both? There are lots o...
[ 2 ]
[]
[]
[ "ipython", "keyboard_shortcuts", "python" ]
stackoverflow_0001517259_ipython_keyboard_shortcuts_python.txt
Q: In Django, how do I filter based on all entities in a many-to-many relation instead of any? I have a model like this: class Task(models.model): TASK_STATUS_CHOICES = ( (u"P", u'Pending'), (u"A", u'Assigned'), (u"C", u'Complete'), (u"F", u'Failed') ) status = models.CharF...
In Django, how do I filter based on all entities in a many-to-many relation instead of any?
I have a model like this: class Task(models.model): TASK_STATUS_CHOICES = ( (u"P", u'Pending'), (u"A", u'Assigned'), (u"C", u'Complete'), (u"F", u'Failed') ) status = models.CharField(max_length=2, choices=TASK_STATUS_CHOICES) prerequisites = models.ManyToManyField('self'...
[ "For your first question -- 'all tasks whose prerequisites are all complete':\n>>> Task.objects.exclude(prerequisites__status__in=['A','P','F'])\n\nThis will also include tasks with no prerequisites (as they have no incomplete prerequisites). As a doctest (using your model definition), the following passes:\n>>> a...
[ 4 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0001516795_django_orm_python.txt
Q: How to space a write file Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file. So for example the user inputs the word "...
How to space a write file
Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file. So for example the user inputs the word "Hello" The user will see the ou...
[ "You can do this without the loop using Python list comprehension and the join method to add the spaces between the ascii values.\n\" \".join([str(ord(c)) for c in message])\n\nThis will evaluate to a string of ascii values separated by spaces.\n", "just manually add a space:\noutfile.write(str(ascii) + \" \")\n\...
[ 5, 3, 0 ]
[]
[]
[ "file", "python", "spacing" ]
stackoverflow_0001517456_file_python_spacing.txt
Q: Closing sockets in python I'm modifying Python code that have this form: def foo(self): try: connect socket except Exception, e: some error reporting stuff return an error use the socket do some other stuff if some condition: return do some more stuff ...
Closing sockets in python
I'm modifying Python code that have this form: def foo(self): try: connect socket except Exception, e: some error reporting stuff return an error use the socket do some other stuff if some condition: return do some more stuff socket.close() return norma...
[ "You can use a try-finally block, which was added in Python 2.5:\ntry:\n open socket\n do stuff with socket\nfinally:\n close socket\n\nOr you can use the with statement, which was added in Python 2.6 (and can be used in 2.5 with a from __future__ import with_statement declaration):\nwith open_the_socket()...
[ 12, 1, 0 ]
[]
[]
[ "python", "sockets", "try_catch" ]
stackoverflow_0001517418_python_sockets_try_catch.txt
Q: Linux packaging abstraction layer written in Python? I'm looking for a way to generate .deb and .rpm packages from my build scripts, containing the resulting products. Since everything is written in Python, I'm wondering if anyone knows of an abstraction layer that would allow me to drive both RPM and Deb constru...
Linux packaging abstraction layer written in Python?
I'm looking for a way to generate .deb and .rpm packages from my build scripts, containing the resulting products. Since everything is written in Python, I'm wondering if anyone knows of an abstraction layer that would allow me to drive both RPM and Deb construction from the same code?
[ "Distutils in python's standard library has a bdist_rpm command to build rpms and the third-paty stdeb module adds a command for producing debs.\n" ]
[ 2 ]
[]
[]
[ "deb", "packaging", "python", "rpm" ]
stackoverflow_0001517495_deb_packaging_python_rpm.txt
Q: About Python's built in sort() method What algorithm is the built in sort() method in Python using? Is it possible to have a look at the code for that method? A: Sure! The code's here, starting with function islt and proceeding for QUITE a while;-). As Chris's comment suggests, it's C code. You'll also want to...
About Python's built in sort() method
What algorithm is the built in sort() method in Python using? Is it possible to have a look at the code for that method?
[ "Sure! The code's here, starting with function islt and proceeding for QUITE a while;-). As Chris's comment suggests, it's C code. You'll also want to read this text file for a textual explanation, results, etc etc.\nIf you prefer reading Java code than C code, you could look at Joshua Bloch's implementation of t...
[ 146, 40, 10 ]
[]
[]
[ "algorithm", "python", "python_internals", "sorting" ]
stackoverflow_0001517347_algorithm_python_python_internals_sorting.txt
Q: Basic cocoa application using dock in Python, but not Xcode and all that extras It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would have to use Xcode and the GUI builder (w/ PyObjC). The application I am intending to write is largely concerned with algorithms and...
Basic cocoa application using dock in Python, but not Xcode and all that extras
It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would have to use Xcode and the GUI builder (w/ PyObjC). The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly related to Apple specific stuff. Basically the appli...
[ "Install the latest py2app, then make a new directory -- cd to it -- in it make a HelloWorld.py file such as:\n# generic Python imports\nimport datetime\nimport os\nimport sched\nimport sys\nimport tempfile\nimport threading\nimport time\n\n# need PyObjC on sys.path...:\nfor d in sys.path:\n if 'Extras' in d:\n ...
[ 9, 2, 0 ]
[]
[]
[ "cocoa", "dock", "pyobjc", "python" ]
stackoverflow_0001517342_cocoa_dock_pyobjc_python.txt
Q: Is Google App Engine a worthy platform for a Lifestreaming app? I'm building a Lifestreaming app that will involve pulling down lots of feeds for lots of users, and performing data-mining, and machine learning algorithms on the results. GAE's load balanced and scalable hosting sounds like a good fit for a system t...
Is Google App Engine a worthy platform for a Lifestreaming app?
I'm building a Lifestreaming app that will involve pulling down lots of feeds for lots of users, and performing data-mining, and machine learning algorithms on the results. GAE's load balanced and scalable hosting sounds like a good fit for a system that could eventually be moving around a LOT of data, but it's lack of...
[ "It might change when they offer paid plans, but as it stands, App Engine is not good for CPU intensive apps. It is designed to scale to handle a large number of requests, not necessarily a large amount of calculation per request. I am running into this issue with fairly minor calculations, and I fear I may have ...
[ 3, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python", "web_applications" ]
stackoverflow_0000135169_django_google_app_engine_python_web_applications.txt
Q: Putting in extra restrictions when filtering on foreignkey in django-admin When getting members based on Unit, I only want to get the ones who are actually in that unit as of now. I've got a model looking like this: class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToMan...
Putting in extra restrictions when filtering on foreignkey in django-admin
When getting members based on Unit, I only want to get the ones who are actually in that unit as of now. I've got a model looking like this: class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToManyField(Unit, through='Membership') class Membership(models.Model): member =...
[ "So you're trying to get the members of a specific Unit, right?\nunit = Unit.objects.select_related().get(id=some_id)\n\nThis will pull the unit out of the database for you, along with the Memberships and Users that belong to it. You can access and filter the users by:\nfor member in unit.membership__set.filter(sto...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_admin", "filter", "many_to_many", "python" ]
stackoverflow_0001485103_django_django_admin_filter_many_to_many_python.txt
Q: Python Image Library ellipse with wide outline When creating an ellipse with PIL, is it possible to have a thicker/wider outline? Currently, I'm trying to do canvas.ellipse(box, outline=colour, fill=None), but would like to be able to give the outline parameter a width. A: You could use the aggdraw advanced-grap...
Python Image Library ellipse with wide outline
When creating an ellipse with PIL, is it possible to have a thicker/wider outline? Currently, I'm trying to do canvas.ellipse(box, outline=colour, fill=None), but would like to be able to give the outline parameter a width.
[ "You could use the aggdraw advanced-graphics add-on module to PIL -- with it, the method to draw an ellipse, like others, takes a pen object which you can make with your favorite width (as well as color and opacity).\n" ]
[ 1 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0001517778_image_python_python_imaging_library.txt
Q: Can anyone point out the pros and cons of TG2 over Django? Django is my favorite python web framework. I've tried out others like pylons, web2py, nevow and others. But I've never looked into TurboGears with much enthusiasm. Now with TG2 out of beta I may give it a try. I'd like to know what are some of the pros an...
Can anyone point out the pros and cons of TG2 over Django?
Django is my favorite python web framework. I've tried out others like pylons, web2py, nevow and others. But I've never looked into TurboGears with much enthusiasm. Now with TG2 out of beta I may give it a try. I'd like to know what are some of the pros and cons compared to Django.
[ "TG2 has several advantages that I think are important: \n\nMulti-database support\nsharding/data partitioning support\nlongstanding support for aggregates, multi-column primary keys\na transaction system that handles multi-database transactions for you\nan admin system that works with all of the above\nout of the ...
[ 15, 14, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "django", "python", "turbogears", "turbogears2" ]
stackoverflow_0000640877_django_python_turbogears_turbogears2.txt
Q: Django: How to modify a text field before showing it in admin I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin. I was expecting to see signal equivalent of post_load but it doesn't seem to exist. To be more specific: I h...
Django: How to modify a text field before showing it in admin
I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin. I was expecting to see signal equivalent of post_load but it doesn't seem to exist. To be more specific: I have a text field that takes user input. In this text field there is...
[ "Have a look into Providing your own form for the admin pages. \nOnce you have your own form, you can use the default param in the form to provide the initial value you want. See the docs on the Initial param for the form field. As this link will show you, it is possible to use a callable or a constant as your init...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "django_signals", "python" ]
stackoverflow_0001517626_django_django_models_django_signals_python.txt
Q: Using Embedded Dictionary for iterative character replacement I'm trying to understand an iterative function that that takes a string "12345" and returns all the possible misspellings based upon a dictionary of keys close to each character in the string. outerDic = {} Dict1 = {'1':'2','2':'q'} outerDic['1'] = Dict...
Using Embedded Dictionary for iterative character replacement
I'm trying to understand an iterative function that that takes a string "12345" and returns all the possible misspellings based upon a dictionary of keys close to each character in the string. outerDic = {} Dict1 = {'1':'2','2':'q'} outerDic['1'] = Dict1 Dict1 = {'1':'1','2':'q','3':'w','4':'3'} outerDic['2'] = Dict1 D...
[ "I'm not sure what the inner dicts, all with keys '1', '2', etc, signify -- are they basically just stand-ins for lists presenting possible typos? But then some (but not all) would also include the \"right\" character... a non-typo...?! Sorry, but you're really being extremely confusing in this presentation -- th...
[ 1 ]
[]
[]
[ "function", "iteration", "python" ]
stackoverflow_0001518358_function_iteration_python.txt
Q: Python - Google App Engine I'm just starting learning google app engine. When I enter the following code below, all I got is "Hello world!" I think the desired result is "Hello, webapp World!" What am I missing? I even try copying the google framework folder to live in the same folder as my app. Thanks. from googl...
Python - Google App Engine
I'm just starting learning google app engine. When I enter the following code below, all I got is "Hello world!" I think the desired result is "Hello, webapp World!" What am I missing? I even try copying the google framework folder to live in the same folder as my app. Thanks. from google.appengine.ext import webapp fr...
[ "Running exactly this code DOES give me the desired output. I suspect you must be erroneously running some other code, since there's absolutely no way this code as given could possibly emit what you observe.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001518383_python.txt
Q: Declaring Unknown Type Variable in Python? I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case ma...
Declaring Unknown Type Variable in Python?
I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need ...
[ "def fivetimes(anylist):\n return anylist * 5\n\nAs you see, if you're given a list argument, there's no need for any assignment whatsoever in order to \"multiply it a given number of times and return the output\". You talk about a given list; how is it given to you, if not (the most natural way) as an argument t...
[ 7, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0001515412_python_types.txt
Q: How to parse Youtube search results? When a user submits a query, I would like to append this to search results in Youtube and download this "page" on the backend of my code (Python-Django). What is the best way to do this? Do you suggest that I do this manually? And create a custom parser? Scanning each line for...
How to parse Youtube search results?
When a user submits a query, I would like to append this to search results in Youtube and download this "page" on the backend of my code (Python-Django). What is the best way to do this? Do you suggest that I do this manually? And create a custom parser? Scanning each line for a certain pattern... Or is there an easie...
[ "The preferred way is probably with the YouTube API\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001518481_python.txt
Q: Is it possible to save a list of values into a SQLite column? I want 3 columns to have 9 different values, like a list in Python. Is it possible? If not in SQLite, then on another database engine? A: You must serialize the list (or other Python object) into a string of bytes, aka "BLOB";-), through your favorite...
Is it possible to save a list of values into a SQLite column?
I want 3 columns to have 9 different values, like a list in Python. Is it possible? If not in SQLite, then on another database engine?
[ "You must serialize the list (or other Python object) into a string of bytes, aka \"BLOB\";-), through your favorite means (marshal is good for lists of elementary values such as numbers or strings &c, cPickle if you want a very general solution, etc), and deserialize it when you fetch it back. Of course, that basi...
[ 18, 13, 4 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001517771_python_sqlite.txt
Q: How to install numpy and scipy on Windows XP I have a problem installing Numpy and Scipy from http://www.scipy.org/Installing_SciPy/Windows I went to download page and downloaded .exe files for Python26. I have Python26 on my machine. After installation, I tried >>> import nympy, scipy Traceback (most recent call...
How to install numpy and scipy on Windows XP
I have a problem installing Numpy and Scipy from http://www.scipy.org/Installing_SciPy/Windows I went to download page and downloaded .exe files for Python26. I have Python26 on my machine. After installation, I tried >>> import nympy, scipy Traceback (most recent call last): File "<stdin>", line 1, in <module> Import...
[ "try with numpy instead of nympy\n" ]
[ 6 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0001518779_numpy_python_scipy.txt
Q: String manipulation in Python docstrings I've been trying to do the following: #[...] def __history_dependent_simulate(self, node, iterations=1, *args, **kwargs): """ For history-dependent simulations only: """ + self.simulate.__doc___ What I tried ...
String manipulation in Python docstrings
I've been trying to do the following: #[...] def __history_dependent_simulate(self, node, iterations=1, *args, **kwargs): """ For history-dependent simulations only: """ + self.simulate.__doc___ What I tried to accomplish here is to have the same documen...
[ "A better solution is probably to use a decorator, eg:\ndef add_docs_for(other_func): \n def dec(func): \n func.__doc__ = other_func.__doc__ + \"\\n\\n\" + func.__doc__\n return func\n return dec\n\ndef foo():\n \"\"\"documentation for foo\"\"\"\n pass\n\n@add_docs_for(foo)\ndef bar():\n...
[ 9, 2 ]
[]
[]
[ "documentation", "python", "string" ]
stackoverflow_0001519029_documentation_python_string.txt
Q: Combine two lists: aggregate values that have similar keys I have two lists or more than . Some thing like this: listX = [('A', 1, 10), ('B', 2, 20), ('C', 3, 30), ('D', 4, 30)] listY = [('a', 5, 50), ('b', 4, 40), ('c', 3, 30), ('d', 1, 20), ('A', 6, 60), ('D', 7, 70]) i want to get the result that mov...
Combine two lists: aggregate values that have similar keys
I have two lists or more than . Some thing like this: listX = [('A', 1, 10), ('B', 2, 20), ('C', 3, 30), ('D', 4, 30)] listY = [('a', 5, 50), ('b', 4, 40), ('c', 3, 30), ('d', 1, 20), ('A', 6, 60), ('D', 7, 70]) i want to get the result that move the duplicate elements like this: my result is to get all the ...
[ "This is pretty easy if you use a dictionary.\ncombined = {}\nfor item in listX + listY:\n key = item[0] \n if key in combined:\n combined[key][0] += item[1]\n combined[key][1] += item[2]\n else:\n combined[key] = [item[1], item[2]]\n\nresult = [(key, value[0], value[1]) for key, value...
[ 8, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001518858_python.txt
Q: Learning to write reusable libraries We need to write simple scripts to manipulate the configuration of our load balancers (ie, drain nodes from pools, enabled or disable traffic rules). The load balancers have a SOAP API (defined through a bunch of WSDL files) which is very comprehensive but using it is quite low...
Learning to write reusable libraries
We need to write simple scripts to manipulate the configuration of our load balancers (ie, drain nodes from pools, enabled or disable traffic rules). The load balancers have a SOAP API (defined through a bunch of WSDL files) which is very comprehensive but using it is quite low-level with a lot of manual error checking...
[ "\"I don't really know where to start\"\nClearly false. You provided an excellent example. Just do more of that. It's that simple.\n\"There are a lot of things I'm not sure about: how to handle errors, how to deal with 20-odd WSDL files (a SOAPpy/suds instance for each?) and how much boilerplate translation from...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001518948_python.txt
Q: Stripping code for production So I want to physically get rid of debugging code before deploying it to appengine. What I'm doing right now is a simple check: settings.py: DEBUG = os.environ['HTTP_HOST'] == 'localhost' from settings import DEBUG if DEBUG: #ensure I haven't screwed smth up during refactoring B...
Stripping code for production
So I want to physically get rid of debugging code before deploying it to appengine. What I'm doing right now is a simple check: settings.py: DEBUG = os.environ['HTTP_HOST'] == 'localhost' from settings import DEBUG if DEBUG: #ensure I haven't screwed smth up during refactoring But this check will be consuming CPU...
[ "No, there isn't clean way. \nConditional compilation in Python\nDifferrent question, similar goals.\n", "If you are worried about the code and able to do this, you could use a decorator approach to inject the debugs, and then for production code, redefine the decorator functions to be no-ops. \nHonestly, I would...
[ 3, 2, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001518484_google_app_engine_python.txt
Q: How can I interact with the android scripting environment from an android app? I'd like to use python scripts as plugins for an app I'm developing. This seems to be possible by interacting with android-scripting-environment (ASE), as is done by Locale, but I haven't found any documentation about this. How you exec...
How can I interact with the android scripting environment from an android app?
I'd like to use python scripts as plugins for an app I'm developing. This seems to be possible by interacting with android-scripting-environment (ASE), as is done by Locale, but I haven't found any documentation about this. How you execute ASE scripts from your own app?
[ "It looks like the Locale \"plugin\" is just recieving a broadcasted Intent to com.twofortyfouram.locale.intent.action.FIRE_SETTING which includs the script as an Extra with the name com.google.ase.extra.SCRIPT_NAME.\nThe relevant bits are in com.google.ase.locale.LocaleReceiver.\n" ]
[ 0 ]
[]
[]
[ "android", "android_scripting", "ase", "python" ]
stackoverflow_0001517372_android_android_scripting_ase_python.txt
Q: Windows Mobile development in Python What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance? A: Python CE Python port for ...
Windows Mobile development in Python
What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?
[ "Python CE\nPython port for Windows CE (Pocket PC) devices. Intended to be as close to desktop version as possible (console, current directory support, testsuite passed). \n\n(source: sourceforge.net) \n\n", "(I used to write customer apps for Windows Mobile.)\nForget about python. Even if it's technically possib...
[ 9, 9, 1, 1 ]
[]
[]
[ "python", "windows_mobile" ]
stackoverflow_0000060446_python_windows_mobile.txt
Q: In managed code, how do I achieve good locality of reference? Since RAM seems to be the new disk, and since that statement also means that access to memory is now considered slow similarly to how disk access has always been, I do want to maximize locality of reference in memory for high performance applications. F...
In managed code, how do I achieve good locality of reference?
Since RAM seems to be the new disk, and since that statement also means that access to memory is now considered slow similarly to how disk access has always been, I do want to maximize locality of reference in memory for high performance applications. For example, in a sorted index, I want adjacent values to be close (...
[ "\nIn .NET, elements of an array are certainly contiguous. In Java I'd expect them to be in most implementations, but it appears not to be guaranteed.\nI think it's reasonable to assume that the memory used by an instance for fields is in a single block... but don't forget that some of those fields may be reference...
[ 10, 4, 2, 2, 2 ]
[ "If you need to optimise to that level then I suspect a VM based language is not for you ;)\n" ]
[ -3 ]
[ "c#", "java", "memory_management", "optimization", "python" ]
stackoverflow_0001518915_c#_java_memory_management_optimization_python.txt
Q: NumPy and memmap: [Errno 24] Too many open files I am working with large matrixes, so I am using NumPy's memmap. However, I am getting an error as apparently the file descriptors used by memmap are not being closed. import numpy import tempfile counter = 0 while True: temp_fd, temporary_filename = tempfile.mk...
NumPy and memmap: [Errno 24] Too many open files
I am working with large matrixes, so I am using NumPy's memmap. However, I am getting an error as apparently the file descriptors used by memmap are not being closed. import numpy import tempfile counter = 0 while True: temp_fd, temporary_filename = tempfile.mkstemp(suffix='.memmap') map = numpy.memmap(tempora...
[ "Since the memmap does not take the open file descriptor, but the file name, I suppose you leak the temp_fd file descriptor. Does os.close(temp_fd) help?\n\nGreat that it works.\nSince you can pass numpy.memmap a file-like object, you could create one from the file descriptor you already have, temp_fd.\nfobj = os.f...
[ 5 ]
[]
[]
[ "memory_management", "numpy", "python" ]
stackoverflow_0001519956_memory_management_numpy_python.txt
Q: Python SQLAlchemy/Elixer Question I am trying to define a SQLAlchemy/Elixer model that can describe the following relationship. I have an SSP table, which has multiple Foreign Keys to the POC table. I've defined the ManyToOne relationships correctly within the SSP object (allowing me to SSP.get(1).action.first_nam...
Python SQLAlchemy/Elixer Question
I am trying to define a SQLAlchemy/Elixer model that can describe the following relationship. I have an SSP table, which has multiple Foreign Keys to the POC table. I've defined the ManyToOne relationships correctly within the SSP object (allowing me to SSP.get(1).action.first_name correctly). What I would also like to...
[ "Try the following:\nclass POC(Entity):\n # ...\n #declare the one-to-many relationships\n csas = OneToMany('SSP')\n actions = OneToMany('SSP')\n # ...\n\nclass SSP(Entity):\n # ...\n #Tell Elixir how to disambiguate POC/SSP relationships by specifying\n #the inverse explicitly.\n csa = ManyToOne('POC', co...
[ 1 ]
[]
[]
[ "orm", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0001520031_orm_python_python_elixir_sqlalchemy.txt
Q: Drupal or Wordpress CMS as a Social Network? I am making a community for web-comic artist who will be able to sync their existing website to this site. However, I am in debate for what CMS I should use: Drupal or Wordpress. I have heard great things about Drupal, where it is really aimed for Social Networking. I a...
Drupal or Wordpress CMS as a Social Network?
I am making a community for web-comic artist who will be able to sync their existing website to this site. However, I am in debate for what CMS I should use: Drupal or Wordpress. I have heard great things about Drupal, where it is really aimed for Social Networking. I actually got to play a little bit in the back end o...
[ "Difficult decision. Normally I would say 'definitely Drupal' without hesitation, as Drupal was build as a System for community sites from the beginning, whereas Wordpress still shows its heritage as a blogging solution, at least that's what I hear quite often. But then I'm working with Drupal all the time recently...
[ 9, 8, 3, 2, 2, 1 ]
[]
[]
[ "content_management_system", "drupal", "python", "social_networking", "wordpress" ]
stackoverflow_0001513062_content_management_system_drupal_python_social_networking_wordpress.txt
Q: How do you know when two objects can communicate? class GuiMaker(Frame): #more code def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) # make frame stretchable self.start() # for subclass: set menu/toolBa...
How do you know when two objects can communicate?
class GuiMaker(Frame): #more code def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) # make frame stretchable self.start() # for subclass: set menu/toolBar self.makeMenuBar() # don...
[ "Does GuiMaker inherit from TextEditor somewhere? In other words is Frame a descendant of TextEditor? That would cause TextEditor's start method to be called.\nOther than that, I don't see any way for the code (as written) to have GuiMaker.start call TextEditor.start\n" ]
[ 5 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0001521368_class_object_python.txt
Q: What is a good size (in bytes) for a log file? I am using the python logging modules RotatingFileHandler, and you can set the maximum size of each log file. What is a good maximum size for a log file? Please give your answer in bytes. A: My default logging setup: RotatingFileHandler(filename, maxBytes=10*1024*1...
What is a good size (in bytes) for a log file?
I am using the python logging modules RotatingFileHandler, and you can set the maximum size of each log file. What is a good maximum size for a log file? Please give your answer in bytes.
[ "My default logging setup:\nRotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5)\n\n", "As the other answers have said, there is a no hard and fast answer. It depends so much on your app and your environment. Here's some guidelines I use.\nFor a multi-user app on a typical server:\nConfigure your ...
[ 32, 17, 9, 3 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001521082_logging_python.txt
Q: Using Python's isinstance The following usage of isinstance doesn't seem to work in Python 2.5.2 or 2.6.2: class BananaCake: def __init__(self): print 'Banana Cake' class ChocolateCake: def __init__(self): print 'Chocolate Cake' class CakeFactory: @staticmethod def create(name): ...
Using Python's isinstance
The following usage of isinstance doesn't seem to work in Python 2.5.2 or 2.6.2: class BananaCake: def __init__(self): print 'Banana Cake' class ChocolateCake: def __init__(self): print 'Chocolate Cake' class CakeFactory: @staticmethod def create(name): if name == 'banana': ...
[ "You're returning a class instead of an instance.\n\n>>> banana_cake is BananaCake\nTrue\n\nI believe you want this:\nclass CakeFactory:\n @staticmethod\n def create(name):\n if name == 'banana':\n return BananaCake() # call the constructor\n elif name == 'chocolate':\n ...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001521655_python.txt
Q: How to prevent log file truncation with python logging module? I need to use python logging module to print debugging info to a file with statements like: logging.debug(something) The file is truncated (i am assuming - by the logging module) and the messages get deleted before I can see them - how can that be pre...
How to prevent log file truncation with python logging module?
I need to use python logging module to print debugging info to a file with statements like: logging.debug(something) The file is truncated (i am assuming - by the logging module) and the messages get deleted before I can see them - how can that be prevented? Here is my logging config: logging.basicConfig( level = ...
[ "logging\n\nIf you run the script repeatedly, the additional log messages are appended to the file. To create a new file each time, you can pass a filemode argument to basicConfig() with a value of 'w'. Rather than managing the file size yourself, though, it is simpler to use a RotatingFileHandler.\n\nTo prevent ov...
[ 13 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001521681_logging_python.txt
Q: How can you extract Hardware ID using Python? How do you extract an HD and Bios Unique ID, using python script? A: Go Get Microsoft's Scriptomatic Run it, Select the appropriate class from the dropdown (WIN32_BIOS) It will produce the necessary Python/WMI code for you. (It will also generate VBScript, Perl, and ...
How can you extract Hardware ID using Python?
How do you extract an HD and Bios Unique ID, using python script?
[ "Go Get Microsoft's Scriptomatic\nRun it, Select the appropriate class from the dropdown (WIN32_BIOS)\nIt will produce the necessary Python/WMI code for you.\n(It will also generate VBScript, Perl, and JScript)\n", "Solutions that come to my mind:\n\nuse Win32 Python Extensions and call Windows APIs to do that di...
[ 3, 2, 1, 1 ]
[]
[]
[ "extract", "hardware", "python" ]
stackoverflow_0000227222_extract_hardware_python.txt
Q: Python and indentation, having trouble getting started. I have just started learning python and am getting caught up. I come from mostly C background. class Alarm: def timer(): def main(): print ("Timer has Started") main() I always get a silly error when I try to run this code: alarm > p...
Python and indentation, having trouble getting started.
I have just started learning python and am getting caught up. I come from mostly C background. class Alarm: def timer(): def main(): print ("Timer has Started") main() I always get a silly error when I try to run this code: alarm > python alarm.py File "alarm.py", line 5 def main(): ...
[ "You have an empty def\ndef timer():\n\nuse\ndef timer():\n pass\n\ninstead.\n", "Learn about the pass statement, main is usually not part of the class.\nA global (module level) main() function is simpler than an Alarm.main() class method. Usually, main() functions come at module level.\nclass Alarm:\n\n de...
[ 11, 3, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001518659_python.txt
Q: How can I specify date and time in Python? What is the object used in Python to specify date (and time) in Python? For instance, to create an object that holds a given date and time, (let's say '05/10/09 18:00'). As per S.Lott's request, so far I have: class Some: date = I stop there. After the "=" sign for, ...
How can I specify date and time in Python?
What is the object used in Python to specify date (and time) in Python? For instance, to create an object that holds a given date and time, (let's say '05/10/09 18:00'). As per S.Lott's request, so far I have: class Some: date = I stop there. After the "=" sign for, I realize I didn't knew what the right object wa...
[ "Simple example:\n>>> import datetime\n# 05/10/09 18:00\n>>> d = datetime.datetime(2009, 10, 5, 18, 00)\n>>> print d.year, d.month, d.day, d.hour, d.second\n2009 10 5 18 0\n>>> print d.isoformat(' ')\n2009-10-05 18:00:00\n>>> \n\n", "Nick D has the official way of handling your problem. If you want to pass in a ...
[ 99, 8, 4, 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001521906_datetime_python.txt
Q: How to fix such ClientForm bug? from mechanize import Browser br = Browser() page = br.open('http://wow.interzet.ru/news.php?readmore=23') br.form = br.forms().next() print br.form gives me the following error: Traceback (most recent call last): File "C:\Users\roddik\Desktop\mech.py", line 6, in ...
How to fix such ClientForm bug?
from mechanize import Browser br = Browser() page = br.open('http://wow.interzet.ru/news.php?readmore=23') br.form = br.forms().next() print br.form gives me the following error: Traceback (most recent call last): File "C:\Users\roddik\Desktop\mech.py", line 6, in <module> br.form = br.forms().nex...
[ "The problem is caused by urls like this\nhttp://wow.zet/forum/index.php?showtopic=1197&pid=30419&st=0&#entry30419\n\nClientForm is looking for an integer after the &#\nIt is ok to have the # in the url, but it should be escaped in the html\nas &# means a character encoding\n" ]
[ 1 ]
[]
[]
[ "clientform", "mechanize", "python" ]
stackoverflow_0001522125_clientform_mechanize_python.txt
Q: map string position to line number in regex output I'm working on a "grep-like" utility in Python for searching Oracle source code files. Coding standards have changed over time, so trying to find something like "all deletes from table a.foo" could span multiple lines, or not, depending on the age of that piece o...
map string position to line number in regex output
I'm working on a "grep-like" utility in Python for searching Oracle source code files. Coding standards have changed over time, so trying to find something like "all deletes from table a.foo" could span multiple lines, or not, depending on the age of that piece of code: s = """-- multiline DDL statement DELETE a.f...
[ "lineno = s.count(\"\\n\",0,m.start())+1\n\n" ]
[ 8 ]
[]
[]
[ "grep", "multiline", "python", "regex" ]
stackoverflow_0001522510_grep_multiline_python_regex.txt
Q: Get partial stdout and stderr from Popen that runs indefinitely Possible Duplicate: Bypassing buffering of subprocess output with popen in C or Python I'm building a wrapper around a server cmd line script that should run indefinitely. What I need to do is to get the current stout without waiting for the subproc...
Get partial stdout and stderr from Popen that runs indefinitely
Possible Duplicate: Bypassing buffering of subprocess output with popen in C or Python I'm building a wrapper around a server cmd line script that should run indefinitely. What I need to do is to get the current stout without waiting for the subprocess to finish. I mean, if I run the following, everything works fine...
[]
[]
[ "i would guess that read() returns the entire contents? If you read a fixed size chunk in a loop you may get better results.\n" ]
[ -1 ]
[ "python", "subprocess" ]
stackoverflow_0001522542_python_subprocess.txt
Q: Problem running a very simple Python program Why is my program giving me an error here? import random TheNumber = random.randrange(1,200,1) NotGuessed = True Tries = 0 GuessedNumber = int(input("Take a guess at the magic number!: ")) while NotGuessed == True: if GuessedNumber < TheNumber: ...
Problem running a very simple Python program
Why is my program giving me an error here? import random TheNumber = random.randrange(1,200,1) NotGuessed = True Tries = 0 GuessedNumber = int(input("Take a guess at the magic number!: ")) while NotGuessed == True: if GuessedNumber < TheNumber: print("Your guess is a bit too low.") ...
[ "In your last line, replace string with str -- that should take care of the error python is complaining about, at least.\n", "it's str, not string. but your infinite loop is a bigger problem. auto-increment is written like this:\nTries += 1\n\nGeneral comment: you could improve your code slightly:\nthe_number = r...
[ 3, 2 ]
[]
[]
[ "ide", "python", "python_idle" ]
stackoverflow_0001522708_ide_python_python_idle.txt
Q: How do I get the module instance for a class in Python? I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called install_path. I would like to obtain the __path__ for t...
How do I get the module instance for a class in Python?
I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called install_path. I would like to obtain the __path__ for the __module__ for self (which in this case will be the subcla...
[ "The sys.modules dict contains all imported modules, so you can use:\nmod = sys.modules[__module__]\n\n", "How about Importing modules\n\nX = __import__(‘X’) works like import\n X, with the difference that you 1)\n pass the module name as a string, and\n 2) explicitly assign it to a variable\n in your current...
[ 14, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001522651_python.txt
Q: how to apply "catch-all" exception clause to complex python web-scraping script? I've got a list of 100 websites in CSV format. All of the sites have the same general format, including a large table with 7 columns. I wrote this script to extract the data from the 7th column of each of the websites and then write t...
how to apply "catch-all" exception clause to complex python web-scraping script?
I've got a list of 100 websites in CSV format. All of the sites have the same general format, including a large table with 7 columns. I wrote this script to extract the data from the 7th column of each of the websites and then write this data to file. The script below partially works, however: opening the output file ...
[ "Make the body of your for loop into:\nfor url in urls:\n try:\n ...the body you have now...\n except Exception, e:\n print>>sys.stderr, \"Url %r not processed: error (%s) % (url, e)\n\n(Or, use logging.error instead of the goofy print>>, if you're already using the logging module of the standard library [a...
[ 2, 1 ]
[]
[]
[ "exception_handling", "list", "loops", "python", "urllib2" ]
stackoverflow_0001522823_exception_handling_list_loops_python_urllib2.txt
Q: Python: List comprehension to assign different values I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] so it should return something like: [[1,1,1], [1,1,1], [2,2,2]] H...
Python: List comprehension to assign different values
I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] so it should return something like: [[1,1,1], [1,1,1], [2,2,2]] How might I go about doing this? Thanks for your help.
[ "It appears as though you're looking for something like this:\n[[1 if j <= 1 else 2 for i in range(3)] for j in range(3)]\n\nThe Python conditional expression is a bit different from what you might be used to if you're coming from something like C or Java:\n\nThe expression x if C else y first evaluates C (not x); ...
[ 14, 14, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001522960_list_comprehension_python.txt
Q: python: how do you setup your workspace on Ubuntu? Lets say I have my workspace (on Eclipse) where I develop my Python modules and I would like to "link" my working files to system Python paths. I know I can drop .pth files etc. but I would like to get the community's wisdom as to the best practices. A: One thi...
python: how do you setup your workspace on Ubuntu?
Lets say I have my workspace (on Eclipse) where I develop my Python modules and I would like to "link" my working files to system Python paths. I know I can drop .pth files etc. but I would like to get the community's wisdom as to the best practices.
[ "One thing you can try is creating a virtual environment and then pointing pydev at the interpreter inside the virtual environment.\n$ virtualenv --no-site-packages myProject\n$ cd myProject\n$ source bin/activate\n(myproject)$\n\nat that point you have a python interpreter that will reference libraries in ~/myProj...
[ 1 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0001522867_eclipse_python.txt
Q: Could someone recommend video tutorial websites for beginners? I'm not sure what it is about me but I seem to learn and retain information better through a classroom setting where what's being shown is explained clearly and easy to understand examples are presented. I rarely do my own reading or research, but I d...
Could someone recommend video tutorial websites for beginners?
I'm not sure what it is about me but I seem to learn and retain information better through a classroom setting where what's being shown is explained clearly and easy to understand examples are presented. I rarely do my own reading or research, but I do occasionally stumble upon some neat things. Maybe I'm just used t...
[ "MIT has a great Intro to Computer Science course using Python.\nMIT 6.00 Introduction to Computer Science and Programming\n", "For Django (Python MVC framework) try here\nFor CSS try here\nFor jQuery try here\nFor DHTML try here\nMy advice don't go for eclipse if oyu are beginner use a texteditor. Eclispes featu...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "ajax", "python", "video" ]
stackoverflow_0001522237_ajax_python_video.txt
Q: How do I do this in Python? List to function def getStuff(x): return 'stuff'+x def getData(x): return 'data'+x thefunctions = [] thefunctions.append("getStuff") thefunctions.append("getData") for i in thefunctions: print i('abc') Is this possible? Thank you. A: thefunctions = [ getStuff, getData ]...
How do I do this in Python? List to function
def getStuff(x): return 'stuff'+x def getData(x): return 'data'+x thefunctions = [] thefunctions.append("getStuff") thefunctions.append("getData") for i in thefunctions: print i('abc') Is this possible? Thank you.
[ "thefunctions = [ getStuff, getData ]\nfor f in thefunctions:\n print f('shazam')\n\nOnce you've done a def statement, you've associated a name with a function. Just use that name to refer to the function.\n" ]
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0001523348_python.txt
Q: python sax: is there a way to halt the parsing from inside a content handler? Is there a way to halt the parsing from inside a content handler? Or is throwing an exception the only way? Note that I am using xml.sax.parseString. A: The complete API for Python's SAX content handlers is documented here: as you can...
python sax: is there a way to halt the parsing from inside a content handler?
Is there a way to halt the parsing from inside a content handler? Or is throwing an exception the only way? Note that I am using xml.sax.parseString.
[ "The complete API for Python's SAX content handlers is documented here: as you can see, the information flow is entirely one-way, parser to handler -- no way for the handler to supply info back to the parser (such as whether the parse should be terminated).\nTherefore, as you had surmised and the commenters confirm...
[ 4 ]
[]
[]
[ "python", "sax" ]
stackoverflow_0001523225_python_sax.txt
Q: Put bar at the end of every line that includes foo I have a list with a large number of lines, each taking the subject-verb-object form, eg: Jane likes Fred Chris dislikes Joe Nate knows Jill To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I wi...
Put bar at the end of every line that includes foo
I have a list with a large number of lines, each taking the subject-verb-object form, eg: Jane likes Fred Chris dislikes Joe Nate knows Jill To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a co...
[ "It sounds like you will want to research dictionaries and string formatting. In general, if you need help programming, just break down any problem you have into extremely small, discrete chunks, search those chunks independently, and then you should be able to formulate it all into a larger answer. Stack Overflow...
[ 5, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0001522386_python_text_processing.txt
Q: Python module search path problem I am trying to work on a dev environment but am find problems in that python seems to be using modules from the site-packages directory. I want it to be using the modules from my dev directory. sys.path returns a bunch of dirs, like this ['', '/usr/lib/python26.zip', '/usr/lib/pyt...
Python module search path problem
I am trying to work on a dev environment but am find problems in that python seems to be using modules from the site-packages directory. I want it to be using the modules from my dev directory. sys.path returns a bunch of dirs, like this ['', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux...
[ "You mention that there's a foo directory under your current directory, but you don't tell us whether foo/__init__.py exists (even possibly empty): if it doesn't, this tells Python that foo is not a package. Similarly for foo/bar/__init__.py -- if that file doesn't exist, even if foo/__init__.py does, then foo.bar...
[ 3, 0 ]
[]
[]
[ "module", "path", "python", "search" ]
stackoverflow_0001523551_module_path_python_search.txt
Q: Python: Running command line application to the script. Sending parameters in files I want to try to use a command line script with my python application. The task is the following, my database stores some initial data for the script and I need to execute a command line application in a following way: $ applicatio...
Python: Running command line application to the script. Sending parameters in files
I want to try to use a command line script with my python application. The task is the following, my database stores some initial data for the script and I need to execute a command line application in a following way: $ application -parameter1 -file1 Here file1 is a file which contains my initial data, and parameter1...
[ "You can use the subprocess modul\nsomething like that: \nimport subprocess\nbufsize =1024\ninitial_data = get_initial_data_from_db()\np = subprocess.Popen(\"application -parameter1\", shell=True, bufsize=bufsize,\n stdin=subprocess.PIPE, close_fds=True)\n\np.stdin.write(initial_data)\nprint p.communicat...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001520442_python.txt
Q: Why do I get encoding error in python warnings.formatwarning on format string? I get encoding error on this line: s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128) I tried to reproduce ...
Why do I get encoding error in python warnings.formatwarning on format string?
I get encoding error on this line: s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128) I tried to reproduce this error by passing all combinations of parameters to string format, but closest I...
[ "This happens when Python tries to coerce an argument:\ns = u\"\\u00fc\"\nprint str(s)\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xfc' in position 0: ordinal not in range(128)\n\nThis happens because one of your arguments is an object (not a string of any kind) and Python calls str() on it. There...
[ 8, 8, 1 ]
[]
[]
[ "encoding", "python", "warnings" ]
stackoverflow_0001524262_encoding_python_warnings.txt
Q: Is an applet a proper solution for hardware detection and driver install? Can I use applets to inform me which hardware is installed on client system (fingerprint reader)? And if it is installed, can it tell me its version, so that it can download the proper plugin from a site? So that after everything is OK, the ...
Is an applet a proper solution for hardware detection and driver install?
Can I use applets to inform me which hardware is installed on client system (fingerprint reader)? And if it is installed, can it tell me its version, so that it can download the proper plugin from a site? So that after everything is OK, the user can use his fingerprint reader to authenticate himself?
[ "Applet should be better if your application is not depended on IE.\nIf for IE only then use COM/ActiveX\n" ]
[ 0 ]
[]
[]
[ "c#", "python", "ruby" ]
stackoverflow_0001524606_c#_python_ruby.txt
Q: How do I display images at different times on webpage I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it A: You'll need a template tag which checks the time of day and outputs the relevant HTML. How you do that depends on how you want to determ...
How do I display images at different times on webpage
I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it
[ "You'll need a template tag which checks the time of day and outputs the relevant HTML. How you do that depends on how you want to determine which image is for what time of day. For example, you could have a model which records a change_time and an image path, and the tag would get the image with the most recent ch...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001524713_django_python.txt
Q: An ALGORITHM to create one list from "X" nested lists in Python What is the simplest way to create this list in Python? First, suppose I have this nested list: oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] I want a function to spit out: newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'}...
An ALGORITHM to create one list from "X" nested lists in Python
What is the simplest way to create this list in Python? First, suppose I have this nested list: oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] I want a function to spit out: newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] Well, this could be done manually. However, what if there are thr...
[ "Recursive solutions are simplest, but limited to at most a few thousand levels of nesting before you get an exception about too-deep recursion. For real generality, you can eliminate recursion by keeping your own stack; iterators are good things to keep on said stack, and the whole function's best written as a gen...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001523675_python.txt
Q: Reasons to use distutils when packaging C/Python project I have an open source project containing both Python and C code. I'm wondering that is there any use for distutils for me, because I'm planning to do a ubuntu/debian package. The C code is not something that I could or want to use as Python extension. C and ...
Reasons to use distutils when packaging C/Python project
I have an open source project containing both Python and C code. I'm wondering that is there any use for distutils for me, because I'm planning to do a ubuntu/debian package. The C code is not something that I could or want to use as Python extension. C and Python programs communicate with TCP/IP through localhost. So ...
[ "distutils can be used to install end user programs, but it's most useful when using it for Python libraries, as it can create source packages and also install them in the correct place. For that I would say it's more or less required.\nBut for an end user Python program you can also use make or whatever you like a...
[ 1, 1 ]
[]
[]
[ "c", "distutils", "packaging", "python" ]
stackoverflow_0001523874_c_distutils_packaging_python.txt
Q: Boo vs C# vs Python? Compared to C#, Boo feels a bit more Pythonic but it's also compiled down to .NET MSIL. I liked its syntax, even more than C#'s syntax. But I couldn't find a single book teaching Boo. And I really don't know, if learning Boo is better than C# or learning C# is better than Boo. I just want to u...
Boo vs C# vs Python?
Compared to C#, Boo feels a bit more Pythonic but it's also compiled down to .NET MSIL. I liked its syntax, even more than C#'s syntax. But I couldn't find a single book teaching Boo. And I really don't know, if learning Boo is better than C# or learning C# is better than Boo. I just want to use some Python-like data t...
[ "I have found Boo to be very useful in creating simple one-off scripts, while retaining my Pythonic source style. And since it compiles to runnable EXE or DLL, I can package up a single EXE with all the needed DLLs (including Boo.Lang.dll) using ILMerge, and then send that off to a client, usually for some kind of...
[ 15, 5, 3, 2, 0 ]
[]
[]
[ "boo", "c#", "programming_languages", "python" ]
stackoverflow_0001524609_boo_c#_programming_languages_python.txt
Q: PyQt context menu I'm adding a contextmenu to a QTableWidget dynamically: playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable) playlistContenxt.setData(currentData) self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction) self.musicTable.addAction(playlistContenxt)...
PyQt context menu
I'm adding a contextmenu to a QTableWidget dynamically: playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable) playlistContenxt.setData(currentData) self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction) self.musicTable.addAction(playlistContenxt) currentItem.text() is...
[ "The correct way is to use signal mapper: You can assign data to each of the senders and get a signal with that data.\n", "You can use QAction.setData to set some data, so that the slot knows which playlist to add to. Then from the slot you can call self.sender() to get the action that triggered the signal, and u...
[ 5, 3 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0001524349_pyqt4_python_qt.txt
Q: Creating files on AppEngine I'm trying to store some data in a binary file: import os, pickle o = some_object() file = open('test', 'wb') #this causes the error pickle.dump(o, file) file.close() I get this error: IOError: invalid mode: wb It doesn't work (neither on test server or GAE itself), apparantly because...
Creating files on AppEngine
I'm trying to store some data in a binary file: import os, pickle o = some_object() file = open('test', 'wb') #this causes the error pickle.dump(o, file) file.close() I get this error: IOError: invalid mode: wb It doesn't work (neither on test server or GAE itself), apparantly because it does't have the write permiss...
[ "GAE is readonly, you can only store stuff in the datastore\nhere is a link to the docs\n", "I think the short answer is you shouldn't. I suggest you store this info in BigTable as a Blob and serve it up that way.\n" ]
[ 5, 1 ]
[]
[]
[ "file", "google_app_engine", "io", "python" ]
stackoverflow_0001525625_file_google_app_engine_io_python.txt
Q: How to fix encoding in Python Mechanize? here is the sample code: from mechanize import Browser br = Browser() page = br.open('http://hunters.tclans.ru/news.php?readmore=2') br.form = br.forms().next() print br.form The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the...
How to fix encoding in Python Mechanize?
here is the sample code: from mechanize import Browser br = Browser() page = br.open('http://hunters.tclans.ru/news.php?readmore=2') br.form = br.forms().next() print br.form The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the encoding of the current page in mechanize? Er...
[ "I don't know about Mechanize, but you could hack codecs to accept wrong encoding names that have both ‘windows’ and ‘cp’:\n>>> def fixcp(name):\n... if name.lower().startswith('windows-cp'):\n... try:\n... return codecs.lookup(name[:8]+name[10:])\n... except LookupError:\n... ...
[ 3, 2 ]
[]
[]
[ "encoding", "mechanize", "python" ]
stackoverflow_0001525295_encoding_mechanize_python.txt
Q: (Python) Passing a threading.Thread object through a function? I have a timer function: # This is a class that schedules tasks. It will call it's ring() function # when the timer starts, and call it's running() function when within the # time limit, and call it's over() function when the time is up. # This class ...
(Python) Passing a threading.Thread object through a function?
I have a timer function: # This is a class that schedules tasks. It will call it's ring() function # when the timer starts, and call it's running() function when within the # time limit, and call it's over() function when the time is up. # This class uses SYSTEM time. import time, threading import settings from obje...
[ "You show us tons of code but not the key parts -- the Scheduler part (and what's that peculiar upper-case-O Object class...?). Anyway, to answer your question, passing instances of Thread subclasses through functions, adding them to lists, etc etc, is perfectly fine (though other things you're doing may not be --...
[ 1, 0 ]
[]
[]
[ "class", "inheritance", "multithreading", "python" ]
stackoverflow_0001522409_class_inheritance_multithreading_python.txt
Q: Python Table engine binding for Tokyo Cabinet I am looking for python bindings for Table engine of Tokyo cabinet. I tried Pytc but can only find Hash and B-tree engine support. Is there any other bindings available? A: Here is an implementation of search of table engine using PyTyrant: http://github.com/ericflo/...
Python Table engine binding for Tokyo Cabinet
I am looking for python bindings for Table engine of Tokyo cabinet. I tried Pytc but can only find Hash and B-tree engine support. Is there any other bindings available?
[ "Here is an implementation of search of table engine using PyTyrant:\nhttp://github.com/ericflo/pytyrant/tree/master\n", "I was in contact with the author of tc and he told me the following:\n\nCurrently, the table (tdb) driver\n exist in the master branch (unit\n tests) and the fdb driver is\n being developed...
[ 7, 4, 2, 2, 1 ]
[]
[]
[ "python", "tokyo_cabinet" ]
stackoverflow_0000601865_python_tokyo_cabinet.txt
Q: How to disable URL redirection in Python when using M2Crypto SSL? This is what my code looks like: url_object = urlparse(url) hostname = url_object.hostname port = url_object.port uri = url_object.path if url_object.path else '/' ctx = SSL.Context() if ctx.load_verify_locations(cafile='ca-bundle.crt') != 1: raise...
How to disable URL redirection in Python when using M2Crypto SSL?
This is what my code looks like: url_object = urlparse(url) hostname = url_object.hostname port = url_object.port uri = url_object.path if url_object.path else '/' ctx = SSL.Context() if ctx.load_verify_locations(cafile='ca-bundle.crt') != 1: raise Exception("Could not load CA certificates.") ctx.set_verify(SSL.verify...
[ "httpslib.HTTPSConnection does not redirect automatically. Like Lennart says in the comment, it subclasses from httplib.HTTPConnection which does not redirect either. It is easy to test with httplib:\nimport httplib\n\nc = httplib.HTTPConnection('www.heikkitoivonen.net', 80)\nc.request('GET', '/deadwinter/disclaime...
[ 0 ]
[]
[]
[ "m2crypto", "python", "redirect", "url" ]
stackoverflow_0001523654_m2crypto_python_redirect_url.txt
Q: Extracting data from a CSV file in Python I just got my data and it is given to me as a csv file. It looks like this in data studio(where the file was taken). Counts frequency 300 1 302 5 303 7 Excel can't handle the computations so that's why I'm trying to load it in python(it has scipy :D). I want ...
Extracting data from a CSV file in Python
I just got my data and it is given to me as a csv file. It looks like this in data studio(where the file was taken). Counts frequency 300 1 302 5 303 7 Excel can't handle the computations so that's why I'm trying to load it in python(it has scipy :D). I want to load the data in an array: Counts = [300, 30...
[ "Use the Python csv module.\n", "import csv\n\ncounts = []\nfrequencies = []\n\nfor d in csv.DictReader(open('yourfile.csv'), delimiter='\\t'):\n counts.append(int(d['Counts']))\n frequencies.append(int(d['frequency']))\n\nprint 'Counts = ', counts\nprint 'frequency = ', frequencies\n\n" ]
[ 9, 7 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001526607_csv_python.txt
Q: redirect() Not Actually Redirecting (Routes for Pylons) I am constructing a table of routes in my Pylons app. I can't get redirect() to work the way that it should work. I'm not sure what I'm doing wrong. Here is an example of redirect() usage from the Routes documentation: map.redirect("/home/index", "/", _re...
redirect() Not Actually Redirecting (Routes for Pylons)
I am constructing a table of routes in my Pylons app. I can't get redirect() to work the way that it should work. I'm not sure what I'm doing wrong. Here is an example of redirect() usage from the Routes documentation: map.redirect("/home/index", "/", _redirect_code="301 Moved Permanently") Here is what appears in...
[ "That syntax works, so there must be something else going on.\nRoutes is sensitive to order. Is there another route above the redirect that would match /view to a controller that would return a 404?\nRoutes is also sensitive to trailing slashes. Did you accidentally type a trailing slash in the browser but not in t...
[ 1 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0001523613_pylons_python_routes.txt
Q: I'm trying to figure out how to get python to simply post the lyrics to a song I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics. This old man, he played one He played knick-knack on my thumb Knick-knack paddywhack, give your dog a bone ...
I'm trying to figure out how to get python to simply post the lyrics to a song
I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics. This old man, he played one He played knick-knack on my thumb Knick-knack paddywhack, give your dog a bone This old man came rolling home This old man, he played two He played knick-knack o...
[ "Hint: You will need to use a loop\nI would look at the Python Flow Control documentation. Also note the range() function.\nYou can grab the n'th element from an array like this:\nval = some_array[n]\n\nAnd remember that in Python, arrays start counting at 0, not 1.\n", "There is in fact a more Pythonic answer to...
[ 5, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001527097_python.txt
Q: How to do a Post Request in Python? Hi I'm sitting in a Greyhound Bus with Wifi and want to connect a second Device to the Network. But I have to accept an onscreen contract and the device does not have a browser. To accept the contract the following form has to be accepted. The device has no CURL but all the sta...
How to do a Post Request in Python?
Hi I'm sitting in a Greyhound Bus with Wifi and want to connect a second Device to the Network. But I have to accept an onscreen contract and the device does not have a browser. To accept the contract the following form has to be accepted. The device has no CURL but all the standard python 2.6. libraries. <form metho...
[ "I think this should do the trick:\nimport urllib\ndata = urllib.urlencode({\"mode_login\":\"Agree\",\"redirect\":\"http://stackoverflow.com\"})\nresult = urllib.urlopen(\"http://192.168.100.1:5280/\",data).read()\nprint result\n\n" ]
[ 2 ]
[]
[]
[ "http_post", "networking", "python" ]
stackoverflow_0001527337_http_post_networking_python.txt
Q: How does Google Books work? Are there any open source alternatives? I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. Is the process is basically "high quality scanning"? are there any open source solution to "mass generation...
How does Google Books work? Are there any open source alternatives?
I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you have an origin...
[ "Unfortunately Google uses a patented technique for scanning it's books, so you will probably have to stick to traditional methods.\n\nGoogle created some seriously nifty\n infrared camera technology that\n detects the three-dimensional shape\n and angle of book pages when the book\n is placed in the scanner. T...
[ 4, 1, 0 ]
[]
[]
[ "image_processing", "python", "watermark" ]
stackoverflow_0001527549_image_processing_python_watermark.txt
Q: How do I convert Perl's pack 'Nc*' format to struct.pack for Python? I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack o...
How do I convert Perl's pack 'Nc*' format to struct.pack for Python?
I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration. example: pack('Nc*',$some_integer,$long_array_of_int...
[ "How about this?\nstruct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)\n\n", "Perl's pack is using the '*' character similar to in regular expressions--meaning a wildcard for more of the same. Here, of course, it means more signed ints.\nIn Python, you'd just loop through the string and...
[ 7, 1 ]
[]
[]
[ "pack", "perl", "python", "struct" ]
stackoverflow_0001527534_pack_perl_python_struct.txt
Q: Get records before and after current selection in Django query It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my Photo model) on the page but I also want to show the image b...
Get records before and after current selection in Django query
It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my Photo model) on the page but I also want to show the image before it in the stream and the image after it. If I were only sortin...
[ "I see the following possibilities:\n\nYour URL query parameters contain the sort/filtering information and some kind of 'item number', which is the item number within your filtered queryset. This is the simple case - previous and next are item number minus one and plus one respectively (plus some bounds checking)...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "python", "sql" ]
stackoverflow_0001527710_django_django_models_django_queryset_python_sql.txt
Q: Creating tables with pylons and SQLAlchemy I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory. For example I have a profile class and a profile table which are defined and mapp...
Creating tables with pylons and SQLAlchemy
I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory. For example I have a profile class and a profile table which are defined and mapped in /model/profile.py To create the tables I r...
[ "I ran into the same problem with my first real Pylons project. The solution that worked for me was this:\n\nDefine tables and classes in your profile.py file\nIn your __init__.py add from profile import * after your def init_model\nI then added all of my mapper definitions afterwards. Keeping them all in the ini...
[ 5, 0, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0001482627_pylons_python_sqlalchemy.txt
Q: Constant instance variables? I use @property to ensure that changes to an objects instance variables are wrapped by methods where I need to. What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a PID attribute ...
Constant instance variables?
I use @property to ensure that changes to an objects instance variables are wrapped by methods where I need to. What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a PID attribute that will frequently be accessed b...
[ "Prepend name of the variable with __, and create read-only property, Python will take care of exceptions, and variable itself will be protected from accidental overwrite.\nclass foo(object):\n def __init__(self, bar):\n self.__bar = bar\n\n @property\n def bar(self):\n return self.__bar\n\nf...
[ 9, 3, 1, 1 ]
[]
[]
[ "instance", "instance_variables", "properties", "python", "setter" ]
stackoverflow_0001527395_instance_instance_variables_properties_python_setter.txt
Q: Does Python have a "compile only" switch like Perl's -c? Perl has the -c switch to compile the code without running it. This is convenient for debugging compile errors in Perl. Does Python have a similar switch? A: You can say python -m py_compile script_to_check.py However, this will have the side effect of c...
Does Python have a "compile only" switch like Perl's -c?
Perl has the -c switch to compile the code without running it. This is convenient for debugging compile errors in Perl. Does Python have a similar switch?
[ "You can say\npython -m py_compile script_to_check.py\n\nHowever, this will have the side effect of creating a compiled script_to_check.pyc file in the same directory as your script. This feature is designed to speed up later uses of a module rather than to make sure that your syntax is correct, though you could c...
[ 22, 9, 0 ]
[]
[]
[ "compiler_construction", "python" ]
stackoverflow_0001528346_compiler_construction_python.txt
Q: Regex for extraction in Python I have a string like this: "a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more". I would like to get this as an output: (("bla", 123, 456), ("bli", 789, 123), ("blu", 789)) I haven't been able to find the proper python regex to achieve that. A: You...
Regex for extraction in Python
I have a string like this: "a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more". I would like to get this as an output: (("bla", 123, 456), ("bli", 789, 123), ("blu", 789)) I haven't been able to find the proper python regex to achieve that.
[ "You need a lot of escapes in your regular expression since {, } and | are special characters in them. A first step to extract the relevant parts of the string would be this:\nregex = re.compile(r'\\{\\{(.*?)\\|(.*?)(?:\\|(.*?))?\\}\\}')\nregex.findall(line)\n\nFor the example this gives:\n[('bla', '123', '456'), (...
[ 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001528016_python_regex.txt
Q: Best Visual-Studio Like tool for Linux Development I need to write a few programs for a project I'm currently working on and I'm very much used to Visual Studio 2008 and I do not mind programming in Python but I need to have a comfortable GUI programming ontop of the language itself, and it has to be well integrat...
Best Visual-Studio Like tool for Linux Development
I need to write a few programs for a project I'm currently working on and I'm very much used to Visual Studio 2008 and I do not mind programming in Python but I need to have a comfortable GUI programming ontop of the language itself, and it has to be well integrated and fast. I know that's a lot to ask for but is there...
[ "Since you have already discarded MonoDevelop the next thing that comes to my mind is: Netbeans it has a very nice GUI builder\nalt text http://www.netbeans.org/images/v6/7/screenshots/swing-gui-builder-cut.png\nThe l&f for linux is quite accurate for most apps. Java Swing it in it self a bit harder to grasp than o...
[ 7, 2, 1, 1, 1, 1 ]
[]
[]
[ ".net", "ide", "linux", "python", "visual_studio" ]
stackoverflow_0001528535_.net_ide_linux_python_visual_studio.txt