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: Problem using super(python 2.5.2) I'm writing a plugin system for my program and I can't get past one thing: class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper im...
Problem using super(python 2.5.2)
I'm writing a plugin system for my program and I can't get past one thing: class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper import loadClasses classList=loa...
[ "‘super’ is a builtin. Unless you went out of your way to delete builtins, you shouldn't ever see “global name 'super' is not defined”.\nI'm looking at your user web link where there is a dump of IntrospectionHelper. It's very hard to read without the indentation, but it looks like you may be doing exactly that:\nb...
[ 20, 0 ]
[]
[]
[ "introspection", "python", "python_datamodel" ]
stackoverflow_0000612468_introspection_python_python_datamodel.txt
Q: What is a good strategy for constructing a directed graph for a game map (in Python)? I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this...
What is a good strategy for constructing a directed graph for a game map (in Python)?
I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is not necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) T...
[ "First, you need some sense of Location. Your various objects occupy some amount of coordinate space.\nYou have to decide how regular these various things are. In the trivial case, you can drop them into your coordinate space as simple rectangles (or rectangular solids) to make locations simpler to plan out.\nIf ...
[ 7, 2 ]
[]
[]
[ "graph", "procedural_generation", "python" ]
stackoverflow_0000610892_graph_procedural_generation_python.txt
Q: Why do I get wrong results for hmac in Python but not Perl? I'm trying to compute hmac using sha-512. The Perl code: use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; and gives the correct hash of 87aa7cdea5ef619d4ff0b4241a1d6c...
Why do I get wrong results for hmac in Python but not Perl?
I'm trying to compute hmac using sha-512. The Perl code: use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; and gives the correct hash of 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3...
[ "yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. \nbelow run on a Penryn-based MBP...\n$ **uname -a**\nDarwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386\ndpc@lizard-wifi:~$ **which python**\n/usr/bin/python\n...
[ 9, 1, 0, 0 ]
[]
[]
[ "hash", "hmac", "perl", "python" ]
stackoverflow_0000613111_hash_hmac_perl_python.txt
Q: Python one-liner to print every file in the current directory How can I make the following one liner print every file through Python? python -c "import sys;print '>>',sys.argv[1:]" | dir *.* Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted. A: python -c "import os; ...
Python one-liner to print every file in the current directory
How can I make the following one liner print every file through Python? python -c "import sys;print '>>',sys.argv[1:]" | dir *.* Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.
[ "python -c \"import os; print os.listdir('.')\"\n\nIf you want to apply some formatting like you have in your question,\npython -c \"import os; print '\\n'.join(['>>%s' % x for x in os.listdir('.')])\"\n\nIf you want to use a pipe, use xargs:\nls | xargs python -c \"import sys; print '>>', sys.argv[1:]\"\n\nor back...
[ 6, 5, 4, 3, 2, 1 ]
[]
[]
[ "cmd", "cygwin", "pipe", "python" ]
stackoverflow_0000613007_cmd_cygwin_pipe_python.txt
Q: Adding twisted code to a pygtk app I have a simple pygtk app using urllib2, what changes should I make to add working twisted code? The pbgtk2.py example it's confusing A: You switch from using the gtk mainloop to the right Twisted reactor. Or you decide to run Twisted in a separate thread using reactor.run(inst...
Adding twisted code to a pygtk app
I have a simple pygtk app using urllib2, what changes should I make to add working twisted code? The pbgtk2.py example it's confusing
[ "You switch from using the gtk mainloop to the right Twisted reactor. Or you decide to run Twisted in a separate thread using reactor.run(installSignalHandlers=0), and stay with the gtk mainloop.\nYou decide if you want to defer the urllib2 call to its own thread, or if you want to rewrite that code using Twisted's...
[ 4 ]
[]
[]
[ "pygtk", "python", "twisted" ]
stackoverflow_0000613777_pygtk_python_twisted.txt
Q: Why is the regular expression returning an error in python? Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?<=[WORD])\w+',str(line)) m.group(0) i get the following ...
Why is the regular expression returning an error in python?
Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?<=[WORD])\w+',str(line)) m.group(0) i get the following error: AttributeError: 'NoneType' object has no attribute 'group'...
[ "This is happening because the regular expression wasn't matched. Therefore m is None and of course you can't access group[0]. You need to first test that the search was successful, before trying to access group members.\n", "Two issues:\n\nyour pattern does not match, therefore m is set to None, and None has no ...
[ 5, 5, 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000614205_python_regex.txt
Q: Big images with cairo I have to render a very big image (>50.000² pixel) with cairo. To do this without running out of memory I render parts of the image (<1.000² pixel) one after another and merge them together later. Create 1000x1000 Surface Translate to position of the current part Draw image (calling the draw...
Big images with cairo
I have to render a very big image (>50.000² pixel) with cairo. To do this without running out of memory I render parts of the image (<1.000² pixel) one after another and merge them together later. Create 1000x1000 Surface Translate to position of the current part Draw image (calling the drawing instructions using pyca...
[ "First of all, using C or Vala instead of Python will probably speed things up.\nAs for memory usage, I would try writing to my own stream, rather than a file (see write_to_png_stream). This could allow you to (I didn't try this) control memory usage, assuming Cairo doesn't call your function only once after everyt...
[ 2 ]
[]
[]
[ "cairo", "python" ]
stackoverflow_0000614949_cairo_python.txt
Q: Best Python templating library to facilitate code generation Instead of me spending the next day (or year) reading about them all, are there any suggestions for templating engines that I should look into in more detail? A: Best suggestion: try them all. It won't take long. My favourite: Jinja2 (by a mile) It has...
Best Python templating library to facilitate code generation
Instead of me spending the next day (or year) reading about them all, are there any suggestions for templating engines that I should look into in more detail?
[ "Best suggestion: try them all. It won't take long.\nMy favourite: Jinja2 (by a mile)\nIt has decent syntax, can trace errors through it, and is sandboxable.\n", "If you're doing code generation, you might find Cog useful - it's specifically for code generation, rather than being a generally applicable templating...
[ 29, 17, 10, 3, 1, 1, 1 ]
[]
[]
[ "code_generation", "python", "templates" ]
stackoverflow_0000612788_code_generation_python_templates.txt
Q: How to copy a directory and its contents to an existing location using Python? I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the...
How to copy a directory and its contents to an existing location using Python?
I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the destination path not exist beforehand. The exact result I'm looking for is to copy ...
[ "distutils.dir_util.copy_tree does what you want.\n\nCopy an entire directory tree src to a\n new location dst. Both src and dst\n must be directory names. If src is not\n a directory, raise DistutilsFileError.\n If dst does not exist, it is created\n with mkpath(). The end result of the\n copy is that every ...
[ 43, 0, 0, 0 ]
[]
[]
[ "copy", "filesystems", "operating_system", "python" ]
stackoverflow_0000512173_copy_filesystems_operating_system_python.txt
Q: Tool/library for calculating intervals like "last thursday of the month" I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above...
Tool/library for calculating intervals like "last thursday of the month"
I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever ...
[ "Neither mxDateTime nor Datejs nor that webservice support \"last thursday of the month\". The OP wants to know all of the last thursdays of the month for, say, a full year.\nmxDateTime supports the operations, but the question must be posed in Python code, not as a string.\nThe best I could figure is parsedatetime...
[ 7, 3, 3, 2, 1, 1 ]
[ "If this is for a web app take a look at Datejs, it may be easier to use that in your form then just pass it's date object's value to Python.\nIf you end up writing one yourself the source may be helpful too.\n" ]
[ -1 ]
[ "date", "datetime", "python" ]
stackoverflow_0000614518_date_datetime_python.txt
Q: How to detect errors from compileall.compile_dir? How do I detect an error when compiling a directory of python files using compile_dir? Currently I get something on stderr, but no way to detect it in my app. py_compile.compile() takes a doraise argument, but nothing here. Or is there a better way to do this from ...
How to detect errors from compileall.compile_dir?
How do I detect an error when compiling a directory of python files using compile_dir? Currently I get something on stderr, but no way to detect it in my app. py_compile.compile() takes a doraise argument, but nothing here. Or is there a better way to do this from a python script? Edit: I fixed it with os.walk and call...
[ "I don't see a better way. The code is designed to support the command-line program, and the API doesn't seem fully meant to be used as a library.\nIf you really had to use the compileall then you could fake it out with this hack, which notices that \"quiet\" is tested for boolean-ness while in the caught exception...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000615632_python.txt
Q: Framework/Language for new web 2.0 sites (2008 and 2009) I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: It is now October 2008. I ...
Framework/Language for new web 2.0 sites (2008 and 2009)
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: It is now October 2008. I want to start writing an application for January 2009. I am w...
[ "Django!\nLook up the DjangoCon talks on Google/Youtube - Especially \"Reusable Apps\" (www.youtube.com/watch?v=A-S0tqpPga4)\nI've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with excellent examples, and it's modul...
[ 16, 9, 7, 5, 4, 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "merb", "python", "ruby_on_rails" ]
stackoverflow_0000184049_django_merb_python_ruby_on_rails.txt
Q: Is it possible to remove recursion from this function? I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function. def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 ...
Is it possible to remove recursion from this function?
I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function. def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = x-i ...
[ "Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. \nI don't know python well enough to give you an i...
[ 22, 16, 2 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0000616416_python_recursion.txt
Q: Iterative version of Python's deepcopy Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime. EDIT I did track...
Iterative version of Python's deepcopy
Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime. EDIT I did track this down: http://code.activestate.com/reci...
[ "I'm not sure this would make sense. Isn't the whole point of deepcopy that each object will ask its children to copy themselves?\nPresumably you know exactly what kind of object you're copying and what its children look like as well, so if I were you, I'd just write my own function to copy it. Shouldn't be too har...
[ 1, 0 ]
[]
[]
[ "iteration", "python", "recursion" ]
stackoverflow_0000617097_iteration_python_recursion.txt
Q: Python Popen, closing streams and multiple processes I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is: compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE) encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout) Th...
Python Popen, closing streams and multiple processes
I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is: compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE) encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout) The way I feed data to the compressor is through compressor....
[ "I suspect the issue is with the order in which you open the pipes. UUEncode is funny is that it will whine when you launch it if there's no incoming pipe in just the right way (try launching the darn thing on it's own in a Popen call to see the explosion with just PIPE as the stdin and stdout)\nTry this:\nencoder ...
[ 4, 3, 1 ]
[]
[]
[ "eof", "popen", "python", "stream" ]
stackoverflow_0000617308_eof_popen_python_stream.txt
Q: How do I make this python command line an alias in bash? I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work? alias myip='python -c "from urllib import urlopen; print urlopen("http://wh...
How do I make this python command line an alias in bash?
I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work? alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'
[ "alias myip=\"python -c 'from urllib import urlopen; print urlopen(\\\"http://whatismyip.appjet.net\\\").read()[:-1]'\"\n\nYou need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias...
[ 7, 6, 5 ]
[]
[]
[ "alias", "bash", "python" ]
stackoverflow_0000617952_alias_bash_python.txt
Q: Issue with Regular expressions in python Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', ...
Issue with Regular expressions in python
Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) When i run this in python reg ex. test...
[ "This question has been asked in several forms over the last few days, so I'm going to say this very clearly.\nQ: How do I parse HTML with Regular Expressions?\nA: Please Don't.\nUse BeautifulSoup, html5lib or lxml.html. Please.\n", "Parsing things with regular expressions works for regular languages. HTML is not...
[ 23, 4, 2, 2, 2, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0000090052_html_python_regex.txt
Q: Python regex split a string by one of two delimiters I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space. And I thought it would be pretty straight-forward : sep = re.compile('(\s*,*)+') print sep.split("""a@b.com, c@d.com e@f.com,,g@h.com""") But...
Python regex split a string by one of two delimiters
I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space. And I thought it would be pretty straight-forward : sep = re.compile('(\s*,*)+') print sep.split("""a@b.com, c@d.com e@f.com,,g@h.com""") But it isn't. I can't find a regex that won't leave some empt...
[ "Doh!\nIt's just this.\nsep = re.compile('[\\s,]+')\n\n", "without re\nline = 'e@d , f@g, 7@g'\n\naddresses = line.split(',') \naddresses = [ address.strip() for address in addresses ]\n\n", "I like the following...\n>>> sep= re.compile( r',*\\s*' )\n>>> sep.split(\"\"\"a@b.com, c@d.com\n\n e@f.com,,g@h.co...
[ 14, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000618551_python_regex.txt
Q: dateutil.rrule.rrule.between() gives only dates after now From the IPython console: In [16]: b Out[16]: datetime.datetime(2008, 3, 1, 0, 0) In [17]: e Out[17]: datetime.datetime(2010, 5, 2, 0, 0) In [18]: rrule(MONTHLY).between(b, e, inc=True) Out[18]: [datetime.datetime(2009, 3, 6, 14, 42, 1), datetime.datetim...
dateutil.rrule.rrule.between() gives only dates after now
From the IPython console: In [16]: b Out[16]: datetime.datetime(2008, 3, 1, 0, 0) In [17]: e Out[17]: datetime.datetime(2010, 5, 2, 0, 0) In [18]: rrule(MONTHLY).between(b, e, inc=True) Out[18]: [datetime.datetime(2009, 3, 6, 14, 42, 1), datetime.datetime(2009, 4, 6, 14, 42, 1), datetime.datetime(2009, 5, 6, 14, 42...
[ "You need to pass b into rrule, like this:\nrrule(MONTHLY, dtstart = b).between(b, e, inc=True)\n\nFrom these docs (http://labix.org/python-dateutil), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying between to. T...
[ 15 ]
[]
[]
[ "python", "python_dateutil", "rrule" ]
stackoverflow_0000618910_python_python_dateutil_rrule.txt
Q: Python build/release system I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended. I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basic...
Python build/release system
I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended. I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does ...
[ "Probably the best answer is to use Ant as-is... that is, use the Java version. My second suggestion would be to use scons. It won't take much time using scons before you're asking, \"Who ever thought of using XML to script a build?\"\n", "Its not completely comparable but I tend to use fabric. Its more geared ...
[ 6, 2, 2, 0 ]
[]
[]
[ "ant", "build_automation", "python" ]
stackoverflow_0000618958_ant_build_automation_python.txt
Q: Set the size of wx.GridBagSizer dynamically I'm creating an app where I drag button widgets into a panel. I would like to have a visible grid in the panel where i drop the widgets so the widgets will be aligned to the grid. I guess it isn't hard making a grid where the squares are 15x15 pixels using a GridBagSizer...
Set the size of wx.GridBagSizer dynamically
I'm creating an app where I drag button widgets into a panel. I would like to have a visible grid in the panel where i drop the widgets so the widgets will be aligned to the grid. I guess it isn't hard making a grid where the squares are 15x15 pixels using a GridBagSizer(since the widgets will span between multiple cel...
[ "Don't use a sizer at all for this. Just position the buttons yourself, with whatever co-ordinate rounding you like. (using wxWindow::SetSize()).\n(The point of a sizer is that the buttons will get moved and/or resized when the window is resized. As you don't want that behaviour, then you shouldn't use a sizer.)...
[ 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000619163_python_wxpython_wxwidgets.txt
Q: (Python) socket.gaierror on every addres...except http://www.reddit.com? I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code: import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.conne...
(Python) socket.gaierror on every addres...except http://www.reddit.com?
I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code: import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' p...
[ "\nsock.connect((url[0] + '://' + url[1],80))\n\n\nDo not do that, instead do this:\nsock.connect((url[1], 80))\n\nconnect expects a hostname, not a URL.\nActually, you should probably use something higher-level than sockets to do HTTP. Maybe httplib.\n", "Please please please please please please please don't do...
[ 3, 3, 2, 1, 0 ]
[]
[]
[ "http", "python", "sockets" ]
stackoverflow_0000303726_http_python_sockets.txt
Q: What does PyPy have to offer over CPython, Jython, and IronPython? From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platform...
What does PyPy have to offer over CPython, Jython, and IronPython?
From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of ...
[ "PyPy is really two projects:\n\nAn interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc)\nAn implementation of Python in RPython\n\nThese two projects allow for many things.\n\nM...
[ 38, 4, 0, 0 ]
[]
[]
[ "interpreter", "pypy", "python" ]
stackoverflow_0000619437_interpreter_pypy_python.txt
Q: Will python provide enough performance for a proxy? I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to pr...
Will python provide enough performance for a proxy?
I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can c...
[ "As long as the bulk of the processing uses Python's built-in modules it should be fine as far as performance. The biggest strength of Python is its clear syntax and ease of testing/maintainability. If you find that one section of your code is slowing down the process, you can rewrite that section and use it as a C...
[ 4, 2, 2, 2 ]
[]
[]
[ "performance", "proxy", "python" ]
stackoverflow_0000619575_performance_proxy_python.txt
Q: Do Django custom authentication backends need to take a password? Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user b...
Do Django custom authentication backends need to take a password?
Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user back, we call a stored procedure in the university's database that takes...
[ "The Django docs say this:\n\nEither way, authenticate should check\n the credentials it gets, and it should\n return a User object that matches\n those credentials, if the credentials\n are valid. If they're not valid, it\n should return None.\n\nThe 'Either way' refers to whether the authenticate() method ta...
[ 6 ]
[]
[]
[ "authentication", "custom_backend", "django", "django_authentication", "python" ]
stackoverflow_0000619620_authentication_custom_backend_django_django_authentication_python.txt
Q: Python's PubSub/observer Pattern for C++? i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it. A: Perhaps you misunderstand what signals a...
Python's PubSub/observer Pattern for C++?
i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it.
[ "Perhaps you misunderstand what signals and slots are. With signals and slots you don't have to know who sends signals. Your \"client\" class just declares slots, and an outside manager can connect signals to them.\nI recommend you to check out Qt. It's an amazing cross-platform library with much more than just GUI...
[ 2, 2, 2 ]
[]
[]
[ "c++", "observer_pattern", "publish_subscribe", "python" ]
stackoverflow_0000605629_c++_observer_pattern_publish_subscribe_python.txt
Q: Using pixel fonts in PIL I am creating images using PIL that contain numerous exactly placed text strings. My first attempt was to convert pixel fonts into the pil-compatible format as described here. For example, I download the Silkscreen font and convert it: otf2bdf -p 8pt -o fonts/slkscr.bdf fonts/slkscr.ttf ...
Using pixel fonts in PIL
I am creating images using PIL that contain numerous exactly placed text strings. My first attempt was to convert pixel fonts into the pil-compatible format as described here. For example, I download the Silkscreen font and convert it: otf2bdf -p 8pt -o fonts/slkscr.bdf fonts/slkscr.ttf pilfont.py fonts/slkscr.bdf ...
[ "Eureka!\nJust needed to specify a resolution of 72 dpi (default is 100) for otf2bdf:\notf2bdf -p 8 -r 72 -o fonts/slkscr.bdf fonts/slkscr.ttf\n\nNow, looks great!\n" ]
[ 4 ]
[]
[]
[ "imaging", "python" ]
stackoverflow_0000619618_imaging_python.txt
Q: Supplying password to wrapped-up MySQL Greetings. I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architect...
Supplying password to wrapped-up MySQL
Greetings. I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, prov...
[ "You could simply build a my.cnf file and point to that on the mysql command. Obviously you'll want to protect that file with permissions/acls. But it shouldn't be really an more/less secure then having the password in your python script, or the config for your python script.\nSo you would do something like \nmys...
[ 6, 3, 2, 0 ]
[]
[]
[ "mysql", "python", "subprocess" ]
stackoverflow_0000619804_mysql_python_subprocess.txt
Q: Where can I find a GUI designer for Python? Does anyone know of any GUI designer for python like Glade but for windows? A: Glade/Gtk+ for Windows is exactly like Glade but for Windows. A: I would suggest using PyQt and the Qt-designer(WYSIWYG gui designer) for making cross platform gui apps. Qt has even gone ...
Where can I find a GUI designer for Python?
Does anyone know of any GUI designer for python like Glade but for windows?
[ "Glade/Gtk+ for Windows is exactly like Glade but for Windows.\n", "I would suggest using PyQt and the Qt-designer(WYSIWYG gui designer) for making cross platform gui apps.\nQt has even gone LGPL, making it even more attractive.\nYou can find PyQt at:\nhttp://www.riverbankcomputing.co.uk/software/pyqt/download\n"...
[ 13, 4, 2, 2, 1, 1 ]
[]
[]
[ "glade", "python", "user_interface" ]
stackoverflow_0000561283_glade_python_user_interface.txt
Q: Django labels and translations - Model Design Lets say I have the following Django model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) Each label has an ID number, the label text, and...
Django labels and translations - Model Design
Lets say I have the following Django model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels ...
[ "Another option you might consider, depending on your application design of course, is to make use of Django's internationalization features. The approach they use is quite common to the approach found in desktop software. \nI see the question was edited to add a reference to Django internationalization, so you do ...
[ 3, 2, 1, 0 ]
[]
[]
[ "django", "django_models", "localization", "python" ]
stackoverflow_0000616187_django_django_models_localization_python.txt
Q: Programmatically restart windows to make system logs think user logged out I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want ...
Programmatically restart windows to make system logs think user logged out
I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart a...
[ "The shutdown command in batch will shutdown the computer\n-s to turn it off,\n-f to force it,\n-t xx to have it shutdown in x seconds,\nuse the subprocess module in python to call it.\nSince you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the...
[ 10, 1, 1 ]
[]
[]
[ "automation", "python", "windows" ]
stackoverflow_0000620154_automation_python_windows.txt
Q: SQLAlchemy Obtain Primary Key With Autoincrement Before Commit When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing? I would like to place two operations inside a tr...
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing? I would like to place two operations inside a transaction however one of the operations will depend on what primary ...
[ "You don't need to commit, you just need to flush. Here's some sample code. After the call to flush you can access the primary key that was assigned. Note this is with SQLAlchemy v1.3.6 and Python 3.7.4.\nfrom sqlalchemy import *\nimport sqlalchemy.ext.declarative\n\nBase = sqlalchemy.ext.declarative.declarative...
[ 93 ]
[ "You can use multiple transactions and manage it within scope.\n" ]
[ -4 ]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0000620610_python_sql_sqlalchemy.txt
Q: Why do I get unexpected behavior in Python isinstance after pickling? Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle: from __future__ import with_statement import pickle # Simpl...
Why do I get unexpected behavior in Python isinstance after pickling?
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle: from __future__ import with_statement import pickle # Simple class definition class myclass(object): def __init__(self, data): ...
[ "The obvious answer, because its not the same class.\nIts a similar class, but not the same.\nclass myclass(object):\n pass\n\nx = myclass()\n\nclass myclass(object):\n pass\n\ny = myclass()\n\n\nassert id(x.__class__) == id(y.__class__) # Will fail, not the same object\n\nx.__class__.foo = \"bar\"\n\nassert ...
[ 5, 5, 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0000620844_pickle_python.txt
Q: What's the best way to find the closest matching type to an existing type? I've got a registry of classes and types in Python 2.5, like so: class ClassA(object): pass class ClassB(ClassA): pass MY_TYPES = { basestring : 'A string', int : 'An integer', ClassA : 'This is ClassA or a subclass',...
What's the best way to find the closest matching type to an existing type?
I've got a registry of classes and types in Python 2.5, like so: class ClassA(object): pass class ClassB(ClassA): pass MY_TYPES = { basestring : 'A string', int : 'An integer', ClassA : 'This is ClassA or a subclass', } I'd like to be able to pass types to a function, and have it look up the clo...
[ "from inspect import getmro\n[st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]\n\n['This is ClassA or a subclass']\n\nor if you're only interested in first match(es) generator version:\n(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))\n\n", "To get the superclasses of a class, use __b...
[ 4, 2, 1, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0000620530_python_types.txt
Q: What does re.compile(r'[[]]') match? With Python's re module, why do the following act differently: >>> r = re.compile(r'[][]') >>> r.findall(r'[]') ['[', ']'] >>> r = re.compile(r'[[]]') >>> r.findall(r'[]') ['[]'] >>> r.findall(r'][') [] A: The regular expression "[[]]" matches the substring "[]". The first [ ...
What does re.compile(r'[[]]') match?
With Python's re module, why do the following act differently: >>> r = re.compile(r'[][]') >>> r.findall(r'[]') ['[', ']'] >>> r = re.compile(r'[[]]') >>> r.findall(r'[]') ['[]'] >>> r.findall(r'][') []
[ "The regular expression \"[[]]\" matches the substring \"[]\". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is \"any of the characters in \"[\", followed by a \"]\".\n"...
[ 16, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000621560_python_regex.txt
Q: Unable to import python-mysqldb I installed python-mysqldb using sudo apt-get install python-mysqldb I have tried to use it unsuccessfully. The following commands do not work in Python prompt: import python-mysqldb Or import mysqldb How can I solve this problem? A: The package name is "MySQLdb". Case counts....
Unable to import python-mysqldb
I installed python-mysqldb using sudo apt-get install python-mysqldb I have tried to use it unsuccessfully. The following commands do not work in Python prompt: import python-mysqldb Or import mysqldb How can I solve this problem?
[ "The package name is \"MySQLdb\". Case counts.\n" ]
[ 11 ]
[]
[]
[ "import", "mysql", "python" ]
stackoverflow_0000621968_import_mysql_python.txt
Q: Is there a Django apps pattern equivalent in Google App Engine? Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. Th...
Is there a Django apps pattern equivalent in Google App Engine?
Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. They let you build up large projects by gathering together a collection...
[ "The Django implementation of apps is closely tied to Django operation as a framework - I mean plugging application using Django url mapping features (for mapping urls to view functions) and Django application component discovery (for discovering models and admin configuration). There is no such mechanisms in WebAp...
[ 3, 2 ]
[]
[]
[ "design_patterns", "django", "django_apps", "google_app_engine", "python" ]
stackoverflow_0000588342_design_patterns_django_django_apps_google_app_engine_python.txt
Q: .cgi problem with web server The code #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor()...
.cgi problem with web server
The code #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM ...
[ "I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with \" and '. Do you have any more luck with the following? Can you run it from a terminal just by typing python test.cgi?\n#!/usr/bin/env python\n\nimport MySQLdb\n\nprint \"Content-Type: text/html\"\nprint\nprint ...
[ 2, 2, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000621874_cgi_python.txt
Q: Django Forms Newbie Question Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a lin...
Django Forms Newbie Question
Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this ...
[ "Yeah I have to agree the documentation and examples are really lacking here. The is no out of the box solution for the case you are describing because it goes three layers deep: quiz->question->answer.\nDjango has model inline formsets which solve the problem for two layers deep. What you will need to do to genera...
[ 6, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0000621121_django_forms_python.txt
Q: Granularity of Paradigm Mixing When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code ...
Granularity of Paradigm Mixing
When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool ...
[ "Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place.\nIt is impossible to purely program with one paradigm. You may think you have a single one in mind...
[ 2, 2, 1, 0 ]
[]
[]
[ "coding_style", "python", "ruby" ]
stackoverflow_0000543140_coding_style_python_ruby.txt
Q: pycurl cancel a transfer and try & except How do i cancel a transfer in pycurl? i use to return -1 in libcurl but pycurl doesnt seem to like that ("pycurl.error: invalid return value for write callback -1 17") return 0 doesnt work either, i get "error: (23, 'Failed writing body')" . Also how do i do a try/except w...
pycurl cancel a transfer and try & except
How do i cancel a transfer in pycurl? i use to return -1 in libcurl but pycurl doesnt seem to like that ("pycurl.error: invalid return value for write callback -1 17") return 0 doesnt work either, i get "error: (23, 'Failed writing body')" . Also how do i do a try/except with pycurl? i dont see any examples online nor ...
[ "Example code would help here. Judging from the error message, and grepping for it in the source code, you've set up a write callback. This is configured, I think, by CURLOPT_WRITEFUNCTION, and the documentation for that says:\n\nReturn the number of bytes actually\n taken care of. If that amount differs\n from t...
[ 3 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0000526325_pycurl_python.txt
Q: Why doesn't Python have static variables? There is a questions asking how to simulate static variables in python. Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support static variables in methods? Is this considere...
Why doesn't Python have static variables?
There is a questions asking how to simulate static variables in python. Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Pyt...
[ "The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.\nIf you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class non...
[ 80, 19, 8, 6, 5, 4, 0, 0 ]
[ "From one of your comments: \"I'd like to use them to cache things loaded from disk. I think it clutters the instance less, if I could assign them to the function\"\nUse a caching class then, as a class or instance attribute to your other class. That way, you can use the full feature set of classes without clutteri...
[ -1 ]
[ "python" ]
stackoverflow_0000592931_python.txt
Q: How to change cursor position of wxRichTextCtrl in event handler? I have a RichTextCtrl in my application, that has a handler for EVT_KEY_DOWN. The code that is executed is the following : def move_caret(self): pdb.set_trace() self.rich.GetCaret().Move((0,0)) self.Refresh() def onClick(self,event): ...
How to change cursor position of wxRichTextCtrl in event handler?
I have a RichTextCtrl in my application, that has a handler for EVT_KEY_DOWN. The code that is executed is the following : def move_caret(self): pdb.set_trace() self.rich.GetCaret().Move((0,0)) self.Refresh() def onClick(self,event): self.move_caret() event.Skip() rich is my RichTextCtrl. Here ...
[ "Apparently, there are two problems with your code:\n\nYou listen on EVT_KEY_DOWN, which is probably handled before EVT_TEXT, whose default handler sets the cursor position.\nYou modify the Caret object instead of using SetInsertionPoint method, which both moves the caret and makes the next character appear in give...
[ 3 ]
[]
[]
[ "events", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000622417_events_python_wxpython_wxwidgets.txt
Q: How can I insert RTF into a wxpython RichTextCtrl? Is there a way to directly insert RTF text in a RichTextCtrl, ex:without going through BeginTextColour? I would like to use pygments together with the RichTextCtrl. A: No. As authors admit in wxRichTextCtrl roadmap: This is a list of some of the features that h...
How can I insert RTF into a wxpython RichTextCtrl?
Is there a way to directly insert RTF text in a RichTextCtrl, ex:without going through BeginTextColour? I would like to use pygments together with the RichTextCtrl.
[ "No. As authors admit in wxRichTextCtrl roadmap:\n\nThis is a list of some of the features that have yet to be implemented. Help with them will be appreciated.\n\nRTF input and output \n\n\n" ]
[ 2 ]
[]
[]
[ "python", "richtextctrl", "rtf", "wxpython" ]
stackoverflow_0000623384_python_richtextctrl_rtf_wxpython.txt
Q: For my app, how many threads would be optimal? I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once...
For my app, how many threads would be optimal?
I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is,...
[ "You will probably find your application is bandwidth limited not CPU or I/O limited.\nAs such, add as many as you like until performance begins to degrade.\nYou may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent...
[ 13, 7, 3, 3, 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000623054_multithreading_python.txt
Q: Increment Page Hit Count in Django I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3's hit_count column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id = 3 Can I do this ...
Increment Page Hit Count in Django
I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3's hit_count column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id = 3 Can I do this with the standard Django Model conventio...
[ "If you use Django 1.1+, just use F expressions:\nfrom django.db.models import F\n...\nMyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)\n\nThis will perform a single atomic database query.\nAs gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't cl...
[ 33, 4, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000622652_django_django_models_python.txt
Q: django login middleware not working as expected A quickie, and hopefully an easy one. I'm following the docs at http://docs.djangoproject.com/en/dev/topics/auth/ to get just some simple user authentication in place. I don't have any special requirements at all, I just need to know if a user is logged in or not, th...
django login middleware not working as expected
A quickie, and hopefully an easy one. I'm following the docs at http://docs.djangoproject.com/en/dev/topics/auth/ to get just some simple user authentication in place. I don't have any special requirements at all, I just need to know if a user is logged in or not, that's about it. I'm using the login_required decorator...
[ "I believe I fixed it:\nRight:\nurl(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'})\n\nWrong:\nurl(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'})\n\nMeh.\n" ]
[ 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0000624043_django_django_authentication_python.txt
Q: Upgrading Python on OS X 10.4.11 I downloaded a package installer for Python 2.6.1, but when I use the python command in terminal (bash) Apple's shipped 2.3.5 version loads up. How can I get 2.6.1 to load up instead? A: You probably need to edit your ~/.profile file. It contains your PATH variable, which tells...
Upgrading Python on OS X 10.4.11
I downloaded a package installer for Python 2.6.1, but when I use the python command in terminal (bash) Apple's shipped 2.3.5 version loads up. How can I get 2.6.1 to load up instead?
[ "You probably need to edit your ~/.profile file. It contains your PATH variable, which tells the command line where to find things. You can do so like this:\nexport PATH=/path/to/new/python:$PATH\n\nThat puts your new path as the first place to look.\n", "I am running Leopard, 10.5.5. The python binary, /usr/bi...
[ 4, 4, 1, 0, 0 ]
[]
[]
[ "bash", "macos", "python", "terminal" ]
stackoverflow_0000616480_bash_macos_python_terminal.txt
Q: How do I make a Django ModelForm menu item selected by default? I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) I...
How do I make a Django ModelForm menu item selected by default?
I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) I am using a ModelForm to generate a "new user" HTML form. My Google-f...
[ "If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:\nform = MyModelForm (initial={'gender':'M'})\n\n-OR-\nYou can override certain attributes of a ModelForm using the declarative nature of the Forms...
[ 16, 8 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000624265_django_django_forms_python.txt
Q: Why am I getting an invalid syntax easy_install error? I need to use easy_install to install a package. I installed the enthought distribution, and popped into IDLE to say: >>> easy_install SQLobject SyntaxError: invalid syntax What am I doing wrong? easy_install certainly exists, as does the package. help('e...
Why am I getting an invalid syntax easy_install error?
I need to use easy_install to install a package. I installed the enthought distribution, and popped into IDLE to say: >>> easy_install SQLobject SyntaxError: invalid syntax What am I doing wrong? easy_install certainly exists, as does the package. help('easy_install') gives me some basic help. import easy_install...
[ "easy_install is a shell command. You don't need to put it in a python script.\neasy_install SQLobject\n\nType that straight into a bash (or other) shell, as long as easy_install is in your path.\n" ]
[ 19 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0000624492_easy_install_python.txt
Q: Setting up a Python web development environment on OS X I'm running Mac OS X Leopard and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future. I've been trying to ...
Setting up a Python web development environment on OS X
I'm running Mac OS X Leopard and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future. I've been trying to get mod_wsgi installed and configured to work with Django and...
[ "Most Python applications are moving away from mod_python. It can vary by framework or provider, but most development effort is going into mod_wsgi.\nUsing the WSGI standard will make your Python application server agnostic, and allow for other nice additions like WSGI middleware. Other providers may only provide C...
[ 2, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "apache", "macos", "mysql", "python" ]
stackoverflow_0000266114_apache_macos_mysql_python.txt
Q: Why aren't signals simply called events? From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc? A: Actually, "signals" have been around longer than events have....
Why aren't signals simply called events?
From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?
[ "Actually, \"signals\" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the na...
[ 24, 4, 2, 1 ]
[]
[]
[ "django_signals", "python", "signals" ]
stackoverflow_0000624844_django_signals_python_signals.txt
Q: Best Resource for mysql + python 2.6 programming I need a great resource for interacting with MySql (version 5.0.45) with Python2.6. I'm using cherrypy, mako, the standard library, and nothing else. The resources can be blogs, howtos, books (online of offline), whatever. Additional information: The python mysql mo...
Best Resource for mysql + python 2.6 programming
I need a great resource for interacting with MySql (version 5.0.45) with Python2.6. I'm using cherrypy, mako, the standard library, and nothing else. The resources can be blogs, howtos, books (online of offline), whatever. Additional information: The python mysql module, MySQLdb, is compatible with Python DB-API 2.0 . ...
[ "Python connectivity to DBs is accomplished (most of the times) through the DBI (Python Database API). \nThe Python DBI has 2 versions and their documentation is the place for you to start:\nv.1 and v.2. You must check what version is supported by the MySQL connector and use the corresponding spec version.\nFor mor...
[ 3, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000623276_mysql_python.txt
Q: Unable to install python-setuptools: ./configure: No such file or directory The question is related to the answer to "Unable to install Python without sudo access". I need to install python-setuptools to install python modules. I have extracted the installation package. I get the following error when configuring [...
Unable to install python-setuptools: ./configure: No such file or directory
The question is related to the answer to "Unable to install Python without sudo access". I need to install python-setuptools to install python modules. I have extracted the installation package. I get the following error when configuring [~/wepapps/pythonModules/setuptools-0.6c9]# ./configure --prefix=/home/masi/.local...
[ "As Noah states, setuptools isn't an automake package so doesn't use ‘./configure’. Instead it's a pure-Python-style ‘setup.py’ (distutils) script.\nYou shouldn't normally need to play with .pydistutils.cfg, as long as you run it with the right version of Python. So if you haven't added the .local/bin folder to PAT...
[ 2, 1 ]
[]
[]
[ "failed_installation", "python", "setuptools" ]
stackoverflow_0000624671_failed_installation_python_setuptools.txt
Q: python conditional lock How can I implement conditional lock in threaded application, for instance I haw 30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If val...
python conditional lock
How can I implement conditional lock in threaded application, for instance I haw 30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If value for input is repeated and ...
[ "Try this: have a lock in the module where your function is, and if the input to the function is such that locking is required, acquire the lock inside the function. Otherwise don't.\nl = threading.RLock()\n\ndef fn(arg):\n if arg == arg_that_needs_lock:\n l.acquire()\n try:\n # do stuff...
[ 6, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000625491_multithreading_python.txt
Q: How can I pass all the parameters to a decorator? I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ...
How can I pass all the parameters to a decorator?
I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value...
[ "This line is incorrect:\nret_val = func(args)\n\nYou're forgetting to expand the argument list when you're passing it on. It should be:\nret_val = func(*args)\n\nSample output with this modification in place:\n>>> class Test2:\n... @trace\n... def test3(self, a, b):\n... pass\n... \n>>> t = Test2()\...
[ 6 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000625786_decorator_python.txt
Q: wxpython auinotebook close tab event What event is used when I close a tab in an auinotebook? I tested with EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work. I would also like to fire a right click on the tab itself event. Where can I find all the events that can be used with the aui manager/notebook? Might just be m...
wxpython auinotebook close tab event
What event is used when I close a tab in an auinotebook? I tested with EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work. I would also like to fire a right click on the tab itself event. Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't find ...
[ "This is the bind command you want:\nself.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb)\n\nTo detect a right click on the tab (e.g. to show a custom context menu):\nself.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb)\n\nHere's a list of the aui notebook events:\nEVT_AUINOTEBOOK_PAG...
[ 8 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000625714_python_wxpython_wxwidgets.txt
Q: Using Django admin look and feel in my own application I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application. (I think that I've read something like that somewhere, but now I cannot find the page again.) (edited: wh...
Using Django admin look and feel in my own application
I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application. (I think that I've read something like that somewhere, but now I cannot find the page again.) (edited: what I am looking for is a way to do it automatically by exten...
[ "Are you sure you want to take every bit of admin-site's look & feel??\nI think you would need to customize some, as in header footer etc.\nTo do that, just copy base.html from \n\n\"djangosrc/contrib/admin/templates/admin/\"\n\nand keep it in \n\n\"your_template_dir/admin/base.html\" or\n \"your_template_dir/admi...
[ 4, 4 ]
[]
[]
[ "django", "django_admin", "look_and_feel", "python", "styles" ]
stackoverflow_0000624535_django_django_admin_look_and_feel_python_styles.txt
Q: Store Django form.cleaned_data in null model field? I have a django model, which has a int field (with null=True, blank=True). Now when I get a form submit from the user, I assign it like so: my_model.width= form.cleaned_data['width'] However sometimes I get an error: ValueError: invalid literal for int() with ba...
Store Django form.cleaned_data in null model field?
I have a django model, which has a int field (with null=True, blank=True). Now when I get a form submit from the user, I assign it like so: my_model.width= form.cleaned_data['width'] However sometimes I get an error: ValueError: invalid literal for int() with base 10: '' I was wandering if it's the blank ('') string ...
[ "No, it doesn't. If you want to assign NULL, use Python's None. Otherwise Django will try to parse a number from the string and that fails for the empty string. \nYou can use the or construct to achieve this:\nmy_model.width = form.cleaned_data['width'] or None\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000625977_django_python.txt
Q: Loading bundled python framework dependencies using only python I've come across this question but I don't like the solution that is presented. Shell scripting is operating system dependent. Is there a python solution to this problem? I'm not looking for python to machine code compilers, just a way to modify the ...
Loading bundled python framework dependencies using only python
I've come across this question but I don't like the solution that is presented. Shell scripting is operating system dependent. Is there a python solution to this problem? I'm not looking for python to machine code compilers, just a way to modify the include paths with python.
[ "Generally speaking, python follows the paths in sys.path when trying to resolve library dependencies. sys.path is a list, and it is searched in order. If your application modified sys.path on load to put its own library paths at the front, this should do the trick.\nThis section from the python docs has a good exp...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000626157_python.txt
Q: Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter? Apropos of This question, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by sys._getframe(). The frame objects appear to be read o...
Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter?
Apropos of This question, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by sys._getframe(). The frame objects appear to be read only, but I can't find anything obvious in the docs that explicitly states this. Can someone confirm whether these objects are writeab...
[ "From CPython source, Objects/frameobject.c:\nstatic PyMemberDef frame_memberlist[] = {\n {\"f_back\", T_OBJECT, OFF(f_back), RO},\n {\"f_code\", T_OBJECT, OFF(f_code), RO},\n {\"f_builtins\", T_OBJECT, OFF(f_builtins),RO},\n {\"f_globals\", T_OBJECT, OFF(f_glo...
[ 13, 1 ]
[]
[]
[ "frame", "introspection", "python", "sys" ]
stackoverflow_0000626835_frame_introspection_python_sys.txt
Q: File editing in python I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories. The problem is I'm not replacing in place. I'm opening ...
File editing in python
I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories. The problem is I'm not replacing in place. I'm opening files, passing the contents ...
[ "I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of how you are modifying them.\nMaybe you are accidentally editing files in the .svn directory? In .svn/text-base, Subversion ...
[ 8, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0000626617_python_svn.txt
Q: Select mails from inbox alone via poplib I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too. How do I select emails only from inbox? I dont want to use any gmail specific libraries. A: POP3 h...
Select mails from inbox alone via poplib
I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too. How do I select emails only from inbox? I dont want to use any gmail specific libraries.
[ "POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email.\nPerhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server.\n", "I assume you hav...
[ 4, 3, 2 ]
[]
[]
[ "gmail", "pop3", "poplib", "python" ]
stackoverflow_0000625148_gmail_pop3_poplib_python.txt
Q: wx's idle and UI update events in PyQt wx (and wxPython) has two events I miss in PyQt: EVT_IDLE that's being sent to a frame. It can be used to update the various widgets according to the application's state EVT_UPDATE_UI that's being sent to a widget when it has to be repainted and updated, so I can compute it...
wx's idle and UI update events in PyQt
wx (and wxPython) has two events I miss in PyQt: EVT_IDLE that's being sent to a frame. It can be used to update the various widgets according to the application's state EVT_UPDATE_UI that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler Now, PyQt doesn't se...
[ "The use of EVT_UPDATE_UI in wxWidgets seems to highlight one of the fundamental differences in the way wxWidgets and Qt expect developers to handle events in their code.\nWith Qt, you connect signals and slots between widgets in the user interface, either handling \"business logic\" in each slot or delegating it t...
[ 5, 2, 1, 1 ]
[]
[]
[ "pyqt", "python", "qt", "wxpython" ]
stackoverflow_0000624050_pyqt_python_qt_wxpython.txt
Q: Form Field API? I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ? Thanks A: Have a look at the class for each field on your form: for f_name, f_type in my_form_instanc...
Form Field API?
I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ? Thanks
[ "Have a look at the class for each field on your form:\nfor f_name, f_type in my_form_instance.fields.items():\n print \"I am a \",type(f_type)\n # or f_type.__class__\n\nThis will produce output similar to <class 'django.forms.fields.BooleanField'>.\nYou can get the name as a simple string, if you prefer tha...
[ 3, 1 ]
[ "Presuming you're using HTML here... Because it isn't very clear.\nHow about giving it an extra class.\nAnd if you didn't know allready, the class attribute will recognise this:\nclass=\"hello there you\"\n\nas having 3 classes. The class 'hello', the class 'there', and the class 'you'.\nSo if they allready have a ...
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0000627583_django_django_forms_python.txt
Q: Python dlopen/dlfunc/dlsym wrappers Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python? A: Would ctypes do what you want? A: The module is called dl: >>> import dl >>> dl.open("libfoo.so") <dl.dl object at 0xb7f580c0> >>> dl.open("libfoo.so").sym('bar') 1400...
Python dlopen/dlfunc/dlsym wrappers
Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python?
[ "Would ctypes do what you want?\n", "The module is called dl:\n>>> import dl\n>>> dl.open(\"libfoo.so\")\n<dl.dl object at 0xb7f580c0>\n>>> dl.open(\"libfoo.so\").sym('bar')\n1400432\n\n... though it's nasty and you might want to consider using ctypes or an extension module.\nEdit\nApparently, dl is deprecated in...
[ 8, 2 ]
[]
[]
[ "dlopen", "linker", "python" ]
stackoverflow_0000627786_dlopen_linker_python.txt
Q: Validating a Unicode Name In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical. But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string? (ideally in Python) A: Maybe the unicodedata module...
Validating a Unicode Name
In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical. But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string? (ideally in Python)
[ "Maybe the unicodedata module is useful for this task. Especially the category() function. For existing unicode categories look at unicode.org. You can then filter on punctuation characters etc.\n", "Just convert bytestring (your utf-8) to unicode objects and check if all characters are alphabetic:\ns.isalpha()\n...
[ 5, 5, 1, 1, 0 ]
[]
[]
[ "character_properties", "python", "unicode", "validation" ]
stackoverflow_0000626697_character_properties_python_unicode_validation.txt
Q: How can I use named arguments in a decorator? If I have the following function: def intercept(func): # do something here @intercept(arg1=20) def whatever(arg1,arg2): # do something here I would like for intercept to fire up only when arg1 is 20. I would like to be able to pass named parameters to the functi...
How can I use named arguments in a decorator?
If I have the following function: def intercept(func): # do something here @intercept(arg1=20) def whatever(arg1,arg2): # do something here I would like for intercept to fire up only when arg1 is 20. I would like to be able to pass named parameters to the function. How could I accomplish this? Here's a little co...
[ "Remember that\n@foo\ndef bar():\n pass\n\nis equivalent to:\ndef bar():\n pass\nbar = foo(bar)\n\nso if you do:\n@foo(x=3)\ndef bar():\n pass\n\nthat's equivalent to:\ndef bar():\n pass\nbar = foo(x=3)(bar)\n\nso your decorator needs to look something like this:\ndef foo(x=1):\n def wrap(f):\n ...
[ 19, 12, 4 ]
[]
[]
[ "decorator", "language_features", "python" ]
stackoverflow_0000627501_decorator_language_features_python.txt
Q: How to implement a function to cover both single and multiple values Say you have a value like this: n = 5 and a function that returns the factorial of it, like so: factorial(5) How do you handle multiple values: nums = [1,2,3,4,5] factorial (nums) so it returns the factorials of all these values as a list? Wha...
How to implement a function to cover both single and multiple values
Say you have a value like this: n = 5 and a function that returns the factorial of it, like so: factorial(5) How do you handle multiple values: nums = [1,2,3,4,5] factorial (nums) so it returns the factorials of all these values as a list? What's the cleanest way to handle this, without writing 2 methods? Does Pytho...
[ "def Factorial(arg):\n try:\n it = iter(arg)\n except TypeError:\n pass\n else:\n return [Factorial(x) for x in it]\n return math.factorial(arg)\n\nIf it's iterable, apply recursivly. Otherwise, proceed normally.\nAlternatively, you could move the last return into the except block.\...
[ 13, 9, 7, 6, 3, 3 ]
[]
[]
[ "function", "list", "python", "vectorization" ]
stackoverflow_0000628162_function_list_python_vectorization.txt
Q: Using Python to get Windows system internals info I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a...
Using Python to get Windows system internals info
I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a code sample would be appreciated)
[ "I think WMI is the resource to use. Especially, look at the Win32_PerfFormattedData* classes in the MSDN.\nA quick search turned this up (among others):\nhttp://timgolden.me.uk/python/wmi.html\n", "The MS Scriptomatic tool can generate WMI scripts in Python as well as VBScript, JScript and Perl.\n" ]
[ 4, 0 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0000627596_python_windows_xp.txt
Q: Decoding HTML Entities With Python The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin". import urllib2 from BeautifulSoup import BeautifulStoneSoup URL = ("http://www.librarything.com/services/rest/1.0/" "?method=librarythi...
Decoding HTML Entities With Python
The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin". import urllib2 from BeautifulSoup import BeautifulStoneSoup URL = ("http://www.librarything.com/services/rest/1.0/" "?method=librarything.ck.getwork&id=1907912" "&...
[ "In the source of the web page it looks like this: The Children of H&Atilde;&ordm;rin. So the encoding is already broken somewhere on their side before it even gets converted to XML...\nIf it's a general issue with all the books and you need to work around it, this seems to work:\nunicode(title_field.find('fact').s...
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0000628332_beautifulsoup_encoding_python_unicode_utf_8.txt
Q: Django Form Preview - How to work with 'cleaned_data' Thanks to Insin for answering a previous question related to this one. His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it? class RegistrationFormPreview(FormPreview): preview_templat...
Django Form Preview - How to work with 'cleaned_data'
Thanks to Insin for answering a previous question related to this one. His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it? class RegistrationFormPreview(FormPreview): preview_template = 'workshops/workshop_register_preview.html' form_...
[ "I've never tried what you're doing here with a ModelForm before, but you might be able to use the ** operator to expand your cleaned_data dictionary into the keyword arguments expected for your Registration constructor:\n registration = Registration (**cleaned_data)\n\nThe constructor to your model classes take ...
[ 10 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0000628132_django_django_forms_django_models_python.txt
Q: Is Google data source JSON not valid? I am implementing a Google data source using their Python library. I would like the response from the library to be able to be imported in another Python script using the simplejson library. However, even their example doesn't validate in JSONLint: {cols: [{id:'name',label...
Is Google data source JSON not valid?
I am implementing a Google data source using their Python library. I would like the response from the library to be able to be imported in another Python script using the simplejson library. However, even their example doesn't validate in JSONLint: {cols: [{id:'name',label:'Name',type:'string'}, {id:'salary',l...
[ "It is considered to be invalid JSON without the string keys.\n{id:'name',label:'Name',type:'string'}\n\nmust be:\n{'id':'name','label':'Name','type':'string'}\n\nAccording to the Google Data Source page, they're returning invalid JSON. They don't specifically say it, but all their examples lack quotes on the keys...
[ 8 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0000628505_python_simplejson.txt
Q: Difference between the use of double quote and quotes in python Is there any difference between the use of double quotes to single quotes in Python? "A string with double quotes" 'A string with single quotes' Are they identical? Are there differences in how python interprets these strings? A: Short answer: alm...
Difference between the use of double quote and quotes in python
Is there any difference between the use of double quotes to single quotes in Python? "A string with double quotes" 'A string with single quotes' Are they identical? Are there differences in how python interprets these strings?
[ "Short answer: almost no difference except stylistically.\nShort blurb: If you don't want to escape the quote characters inside your string, use the other type. eg:\nstring1 = \"He turned to me and said, \\\"Hello there\\\"\"\n\nwould be slightly more unsightly than saying\nstring2 = 'He turned to me and said, \"He...
[ 25, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000628657_python.txt
Q: Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 conc...
Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice
I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 concurrent requests for about 500 loops, it starts to give errors like AttributeError: '_ThreadData' object has no attribute 'sc...
[ "If you look at plugins.ThreadManager.acquire_thread, you'll see the line self.bus.publish('start_thread', i), where i is the array index of the seen thread. Any listener subscribed to the start_thread channel needs to accept that i value as a positional argument. So rewrite your connect function to read: def conne...
[ 1, 0 ]
[]
[]
[ "cherrypy", "lighttpd", "python", "sqlalchemy" ]
stackoverflow_0000625288_cherrypy_lighttpd_python_sqlalchemy.txt
Q: How would you translate this from Perl to Python? I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique: sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_lette...
How would you translate this from Perl to Python?
I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique: sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestam...
[ "Look at this answer for a robust method to convert a number to an alphanumeric id\nThe code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id\nfrom string import uppercase as up\nimport itertools\n\ndef to_base(q, alphabet):\n if q < 0:...
[ 7, 5, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0000604721_perl_python.txt
Q: How to run an operation on a collection in Python and collect the results? How to run an operation on a collection in Python and collect the results? So if I have a list of 100 numbers, and I want to run a function like this for each of them: Operation ( originalElement, anotherVar ) # returns new number. and col...
How to run an operation on a collection in Python and collect the results?
How to run an operation on a collection in Python and collect the results? So if I have a list of 100 numbers, and I want to run a function like this for each of them: Operation ( originalElement, anotherVar ) # returns new number. and collect the result like so: result = another list... How do I do it? Maybe using la...
[ "List comprehensions. In Python they look something like:\na = [f(x) for x in bar]\n\nWhere f(x) is some function and bar is a sequence.\nYou can define f(x) as a partially applied function with a construct like:\ndef foo(x):\n return lambda f: f*x\n\nWhich will return a function that multiplies the parameter b...
[ 12, 1, 0 ]
[]
[]
[ "lambda", "list", "python" ]
stackoverflow_0000628150_lambda_list_python.txt
Q: How do i write a regular expression for the following pattern in python? How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of ...
How do i write a regular expression for the following pattern in python?
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of the "=" sign Mine is like this, but only works for one of the cases! m=re.sear...
[ "if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on = and strip (or even lstrip) last element of a resulting tuple:\n>>> case = 'str = str2'\n>>> case.partition('=')[2].lstrip()\n'str2'\n\nit'll be much faster than regexps. and just to show how fast i'v...
[ 8, 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0000614458_python_regex_string.txt
Q: How do you get the text from an HTML 'datacell' using BeautifulSoup I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell': here is my HTML snippet: headerRows[0][10].contents [<font size="+0"><font f...
How do you get the text from an HTML 'datacell' using BeautifulSoup
I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell': here is my HTML snippet: headerRows[0][10].contents [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3"> </fon...
[ "The BeautifulSoup documentation should cover everything you need - in this case it looks like you want to use findNext:\nheaderRows[0][10].findNext('b').string\n\nA more generic solution which doesn't rely on the <b> tag would be to use the text argument to findAll, which allows you to search only for NavigableStr...
[ 5, 3, 0 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0000223328_beautifulsoup_html_parsing_python.txt
Q: BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding? I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: Oxfam International’s report entitled “Offside! http://www.coopamerica.org/programs/responsibleshopper/com...
BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding?
I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: Oxfam International’s report entitled “Offside! http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271 In particular, the single and double quotes look fine. They look html symbols rather than ascii, thou...
[ "That's one seriously messed up page, encoding-wise :-)\nThere's nothing really wrong with your approach at all. I would probably tend to do the conversion before passing it to BeautifulSoup, just because I'm persnickity:\nimport urllib\nhtml = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/...
[ 8, 4 ]
[]
[]
[ "beautifulsoup", "html", "python", "unicode" ]
stackoverflow_0000629999_beautifulsoup_html_python_unicode.txt
Q: How can I use python's telnetlib to fetch data from a device for a fixed period of time? I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a...
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number. So my question is this: if I connect to this device using python's telnetlib, how can...
[ "From your description I'm not clear if you're using telnetlib because the device you're connecting to requires terminal setup provided by telnet or because it seemed like the right thing to do.\nIf the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the...
[ 5, 2, 2, 1 ]
[]
[]
[ "python", "telnet" ]
stackoverflow_0000630217_python_telnet.txt
Q: Why avoid CGI for Python with LAMP hosting? I have been using PHP for years. Lately I've come across numerous forum posts stating that PHP is outdated, that modern programming languages are easier, more secure, etc. etc. So, I decided to start learning Python. Since I'm used to using PHP, I just started building p...
Why avoid CGI for Python with LAMP hosting?
I have been using PHP for years. Lately I've come across numerous forum posts stating that PHP is outdated, that modern programming languages are easier, more secure, etc. etc. So, I decided to start learning Python. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with: addtype...
[ "Classic CGI isn't the best way to use anything at all. With classic CGI server has to spawn a new process for every request.\nAs for Python, you have few alternatives:\n\nmod_wsgi\nmod_python\nfastcgi\nstandalone Python web server (built-in, CherryPy, Tracd )\nstandalone Python web server on non-standard port and ...
[ 13, 5, 3, 3, 2, 2 ]
[]
[]
[ ".htaccess", "cgi", "php", "python" ]
stackoverflow_0000629919_.htaccess_cgi_php_python.txt
Q: Detect whether charset exists in python Is it possible to check in Python whether a given charset exists/is installed. For example: check('iso-8859-1') -> True check('bla') -> False A: You can use the lookup() function in the codecs module. It throws an exception if a codec does not exist: import codecs def exis...
Detect whether charset exists in python
Is it possible to check in Python whether a given charset exists/is installed. For example: check('iso-8859-1') -> True check('bla') -> False
[ "You can use the lookup() function in the codecs module. It throws an exception if a codec does not exist:\nimport codecs\ndef exists_encoding(enc):\n try:\n codecs.lookup(enc)\n except LookupError:\n return False\n return True\nexists_encoding('latin1')\n\n" ]
[ 4 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0000630938_character_encoding_python.txt
Q: figure out whether python module is installed or in develop mode programmatically I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed. This can be done by poor hacks, like checking whether installati...
figure out whether python module is installed or in develop mode programmatically
I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed. This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me...
[ "Isn't it easier, and cleaner, to just set an environment variable on your development machine, and test for os.environ['development_mode'] (or a setting of your choice)?\n", "Indeed, pkg_resources will do that:\ndist = pkg_resources.get_distribution('your-app')\nif dist.precedence == pkg_resources.DEVELOP_DIST:\...
[ 5, 4, 0 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0000631996_packaging_python.txt
Q: base64 png in python on Windows How do you encode a png image into base64 using python on Windows? iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?...
base64 png in python on Windows
How do you encode a png image into base64 using python on Windows? iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
[ "Open the file in binary mode:\nopen(\"icon.png\", \"rb\")\n\nI'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that Windows is interpreting as the end of the file (for legacy reasons) when it is opened in text mode. The other issue is that opening a ...
[ 26, 9 ]
[]
[]
[ "base64", "python", "windows" ]
stackoverflow_0000631884_base64_python_windows.txt
Q: Nested loop syntax in python server pages I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy. My question is why do I only get output fo...
Nested loop syntax in python server pages
I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy. My question is why do I only get output for the last match in my data set? I figure it ha...
[ "<%\nfor match in matches:\n #begin\n%><tr>\n<%\nfor i in range(1, len(match.groups())+1):\n #begin\n%>\n <td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= match.group(i) %></td>\n<%\n #end\n# end\n%>\n\nYeah, you haven't got a nested loop there. Instead you've got a lo...
[ 1, 0 ]
[]
[]
[ "python", "python_server_pages" ]
stackoverflow_0000632624_python_python_server_pages.txt
Q: What is the best method to read a double from a Binary file created in C? A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using struct.unpack('d',f.read(8)) EDIT: I used the following in C to write a random double number r = drand48(); fwrite((void*)&r, sizeof...
What is the best method to read a double from a Binary file created in C?
A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using struct.unpack('d',f.read(8)) EDIT: I used the following in C to write a random double number r = drand48(); fwrite((void*)&r, sizeof(double), 1, data); The Errors are now fixed but I cannot read the first value...
[ "I think you are actually reading the number correctly, but are getting confused by the display. When I read the number from your provided file, I get \"3.907985046680551e-14\" - this is almost but not quite zero (0.000000000000039 in expanded form). I suspect your C code is just printing it with less precision t...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "double", "python" ]
stackoverflow_0000631607_c_double_python.txt
Q: Python, Evaluate a Variable value as a Variable I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python? def punctuated_object_list(objects, field): field_list = [f.eval(field) for f ...
Python, Evaluate a Variable value as a Variable
I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python? def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) > 0: if le...
[ "getattr(f, field), if I understand you correctly (that is, if you might have field = \"foo\", and want f.foo). If not, you might want to clarify. Python has an eval(), and I don't know what other languages' eval() you want the equivalent of.\n", "getattr( object, 'field' ) #note that field is a string\n\nf = 'fi...
[ 13, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000632856_python.txt
Q: Automatically fetching latest version of a file on import I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: Have a module (mod1.py) in the site-packages directory that copies a different module from some other location into the site-packages directory, and then impo...
Automatically fetching latest version of a file on import
I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: Have a module (mod1.py) in the site-packages directory that copies a different module from some other location into the site-packages directory, and then imports * from that module. import shutil from distutils.sysconf...
[ "Do you really want to do this? This means you could very easily roll code to a production app simply by committing to source control. I would consider this a nasty side-effect for someone who isn't aware of your setup.\nThat being said this seems like a pretty good solution - you may want to add some exception-h...
[ 2, 1, 0 ]
[]
[]
[ "python", "version_control", "visual_sourcesafe" ]
stackoverflow_0000632171_python_version_control_visual_sourcesafe.txt
Q: why am i getting errors while installing pysqlite2.5.3 Am trying build pysqlite 2.5.3 package on SLSE 9, and am getting all sorts of compilation errors i.e. ... src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27].constant_value') src/m...
why am i getting errors while installing pysqlite2.5.3
Am trying build pysqlite 2.5.3 package on SLSE 9, and am getting all sorts of compilation errors i.e. ... src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27].constant_value') src/module.c:290: error: initializer element is not constant src/...
[ "Do you have the sqlite development headers installed?\n\nerror: SQLITE_DETACH' undeclared here \n\nLooks like you need sqlite3-dev (or whatever your distro named it, perhaps sqlite3-devel?)\nEdit:\nAfter a good natured soul cleaned up your error trace a bit more, I'm quite sure you are missing the sqlite3 developm...
[ 4 ]
[]
[]
[ "linux", "python", "sqlite" ]
stackoverflow_0000633601_linux_python_sqlite.txt
Q: How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2...
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04?
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this. Thanks D...
[ "With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:\nFirst, install 2.6rc2. You can download the source from the Python website. Standard ./configure && make && sudo make install installation style.\nNext, remove the /usr/bin/python symlink. Do ...
[ 14, 6, 1, 1 ]
[]
[]
[ "installation", "linux", "python", "ubuntu" ]
stackoverflow_0000142764_installation_linux_python_ubuntu.txt
Q: What is the feasibility of porting a legacy C program to Python? I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange. Now this C program has been legacy and I want to convert it to Python - do you think Python ...
What is the feasibility of porting a legacy C program to Python?
I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange. Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?
[ "Yes, I do think that Python would be a good replacement. I understand that the Twisted Python framework is quite popular.\n", "I'd say that if:\n\nYour C code contains no platform specific requirements\nYou are sure speed is not going to be an issue going from C to python\nYou have a desire to not compile anymor...
[ 9, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000632730_c_python.txt
Q: Why do Python's frameworks return dictionaries from controllers? Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? For example: return dict(sape=4139, guido=4127, jack=4098) instead of (that's the way Rails does it) @var1 = "jello" @var2 = "hihi" Is...
Why do Python's frameworks return dictionaries from controllers?
Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? For example: return dict(sape=4139, guido=4127, jack=4098) instead of (that's the way Rails does it) @var1 = "jello" @var2 = "hihi" Is there any advantage using dictionaries over plain variables (speed-wi...
[ "The main advantage is that this is the only way in python to return a) more than a single value and b) give that value a name. Other options would be to use a class (extra code), return a tuple (no names, so you'd have to use indexes to access the values) or allow to return only a single value which would probably...
[ 5, 3 ]
[ "The nice thing is that a template engine like Jinja2 treats an object and a dict similarly, so if:\nd = {'color': 'red'}\no = Color(red)\n\nthen these all work in the template syntax:\nd.color d['color'] o.color o['color']\n\n" ]
[ -1 ]
[ "python", "ruby_on_rails", "web2py" ]
stackoverflow_0000634024_python_ruby_on_rails_web2py.txt
Q: How to debug a file upload? I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. The file upload is part of a large complicated web form that submits ...
How to debug a file upload?
I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. The file upload is part of a large complicated web form that submits the form data and PDF file though...
[ "A tool like WireShark will give you a more complete trace at a much lower-level than the firefox plugins.\nOften this can be something as simple as not setting the content-type correctly, or failing to include content-length.\n", "You might be better off instrumenting the server to see why this is failing, rathe...
[ 1, 0, 0 ]
[]
[]
[ "post", "python", "upload", "urllib2" ]
stackoverflow_0000632577_post_python_upload_urllib2.txt
Q: Django: Calling custom Model method from Form clean method. "Unbound Method"? I'm having a problem while trying to call a custom Model method from my Form clean method. Here is [part of] my model: http://dpaste.com/hold/12695/ Here is my Form: http://dpaste.com/hold/12699/ I'm specifically having a problem with li...
Django: Calling custom Model method from Form clean method. "Unbound Method"?
I'm having a problem while trying to call a custom Model method from my Form clean method. Here is [part of] my model: http://dpaste.com/hold/12695/ Here is my Form: http://dpaste.com/hold/12699/ I'm specifically having a problem with line 11 in my Form: nzb_data = File.get_nzb_data(nzb_absolute) This raises the follow...
[ "You can't call \nnzb_data = File.get_nzb_data(nzb_absolute)\n\nbecause your using the class, not an object.\nYou have two choices.\n\nMake get_nzb_data a @classmethod. See http://docs.python.org/library/functions.html#classmethod\nCreate an instance of File and use that. temp_f= File(...). Then temp_f.get_dnb_d...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000634857_django_python.txt
Q: Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac I've looked for other questions, but could not find any... I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using htt...
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
I've looked for other questions, but could not find any... I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using http://localhost/ I come from a PHP background and always used MAMP before. But I want...
[ "Why not try the official installation instructions? Really all you need to do is install Django. You can use its built-in server (http://localhost:8000 by default) for testing:\n./manage.py runserver\n\n", "Your Mac should come pre-installed with Python 2.4 (or later) which is fine for Django 1.0.2.\n", "10.5 ...
[ 6, 1, 0, 0, 0 ]
[ "Okay. I'd just install MySQL from their site and stick with what's already on my Mac as of 10.5, then install Django and the Python MySQL driver. But since you like MAMP, install MAMP or XAMPP and read something like this which summarized says:\nMac OS X 10.5 comes with \"Python 2.5.1, thus you won’t have to insta...
[ -1 ]
[ "django", "macos", "osx_leopard", "php", "python" ]
stackoverflow_0000632046_django_macos_osx_leopard_php_python.txt
Q: Visual Studio 2005 Build of Python with Debug .lib I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr). Any hin...
Visual Studio 2005 Build of Python with Debug .lib
I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr). Any hints where I can find those builds ? Regards, Paul
[ "I would recommend that you download the Python source (tgz and tar.bz2 zipped versions available) and compile it yourself. It comes with a VS2005 solution so it isn't difficult. I had to do this for a SWIG project I was working on.\n", "If you have trouble finding the debug builds, you can try and build your o...
[ 1, 0, 0 ]
[]
[]
[ "python", "visual_studio_2005" ]
stackoverflow_0000635200_python_visual_studio_2005.txt
Q: Django: Open uploaded file while still in memory; In the Form Clean method? I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the ...
Django: Open uploaded file while still in memory; In the Form Clean method?
I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the destination directory. For example the following code doesn't work because the fi...
[ "I'm assuming that you've bound your form to the files using:\nmy_form = MyFormClass(request.POST, request.FILES)\n\nIf you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary:\nif my_form.is_valid():\n data = request.FILES['myfile'].read()\n\nThe req...
[ 30 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000635524_django_python.txt
Q: How do you deploy your WSGI application? (and why it is the best way) I am deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be wo...
How do you deploy your WSGI application? (and why it is the best way)
I am deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as...
[ "As always: It depends ;-)\nWhen I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in...
[ 26, 13, 13, 6, 4, 4, 3, 1, 1 ]
[]
[]
[ "deployment", "python", "wsgi" ]
stackoverflow_0000574068_deployment_python_wsgi.txt
Q: tell whether a character is a combining diacritic mark if you're looping though the chars a unicode string in python (2.x), say: ak.sɛp.tɑ̃ How can you tell whether the current char is a combining diacritic mark? For instance, the last char in the above string is actually a combining mark: ak.sɛp.tɑ̃ --> ̃ A: ...
tell whether a character is a combining diacritic mark
if you're looping though the chars a unicode string in python (2.x), say: ak.sɛp.tɑ̃ How can you tell whether the current char is a combining diacritic mark? For instance, the last char in the above string is actually a combining mark: ak.sɛp.tɑ̃ --> ̃
[ "Use the unicodedata module:\nimport unicodedata\nif unicodedata.combining(u'a'):\n print \"is combining character\"\nelse:\n print \"is not combining\"\n\nthese posts are also relevant\nHow do I reverse Unicode decomposition using Python?\nWhat is the best way to remove accents in a Python unicode string?\n"...
[ 9 ]
[]
[]
[ "diacritics", "python", "unicode" ]
stackoverflow_0000635643_diacritics_python_unicode.txt