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: Python - efficient method to remove all non-letters and replace them with underscores def format_title(title): ''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip())) Anything faster? A: The faster way to do it is to use str.translate() This is ~50 times faster than your way # You ...
Python - efficient method to remove all non-letters and replace them with underscores
def format_title(title): ''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip())) Anything faster?
[ "The faster way to do it is to use str.translate()\nThis is ~50 times faster than your way\n# You only need to do this once\n>>> title_trans=''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256))\n\n>>> \"abcde1234!@%^\".translate(title_trans)\n'abcde________'\n\n# Using map+lambda\n$ ...
[ 20, 17, 2, 1, 0 ]
[]
[]
[ "performance", "python", "string" ]
stackoverflow_0002171095_performance_python_string.txt
Q: Can Large Python Scripts Drain DiskSpace? UPDATE: Interestingly, after almost 15min, I seem to have AUTOMATICALLY restored about 500MB. Hows this happening? I'm on Mac OSX 10.5.6(Leopard). I wrote a python script for a Project-Euler problem. My script had a loop which iterated for an enormous count like 6008514751...
Can Large Python Scripts Drain DiskSpace?
UPDATE: Interestingly, after almost 15min, I seem to have AUTOMATICALLY restored about 500MB. Hows this happening? I'm on Mac OSX 10.5.6(Leopard). I wrote a python script for a Project-Euler problem. My script had a loop which iterated for an enormous count like 600851475143. Used Vi and Python on Mac's Terminal. I did...
[ "The only way your script can fill up your disk is if it creates large/many temporary files and doesn't clean up. Just running a Python program cannot itself fill up your disk.\nTo recover the disk space, you need to figure out where the space is spent and remove the temporary files. Not sure how to do that on OSX...
[ 2, 0, 0 ]
[]
[]
[ "caching", "loops", "macos", "memory", "python" ]
stackoverflow_0002171395_caching_loops_macos_memory_python.txt
Q: Redirect calls to a member of a class in python I was trying to 'extend' a closed class collections.defaultdict(lambda: 1) by addint it 2 methods, called 'vocabulary', and 'wordcount' apparently it's impossible to setattr method to builin types, nor can I inherit from defaultdic, so I decided to write a class and...
Redirect calls to a member of a class in python
I was trying to 'extend' a closed class collections.defaultdict(lambda: 1) by addint it 2 methods, called 'vocabulary', and 'wordcount' apparently it's impossible to setattr method to builin types, nor can I inherit from defaultdic, so I decided to write a class and redirect calls to it to the type I want to extend. c...
[ "Either copy from class to class, not instance to instance, or just have .__getattr__() delegate to the encapsulated object.\n", "What do you mean with \"cannot inherit from defaultdict\"? It works for me (not a very good example, but I'm not sure what you're trying to accomplish, so...):\n#!/usr/bin/env python\n...
[ 4, 1 ]
[]
[]
[ "functional_programming", "metaprogramming", "python" ]
stackoverflow_0002171396_functional_programming_metaprogramming_python.txt
Q: python-tz am I wrong or it's a bug It's a bit weird it seems that when I want to get a timezone for Europe/Paris with pytz it gets me to the PMT timezone instead of GMT+1 when it seems to work for Europe/Berlin. Not clear ? Well look at this snippet : #!/usr/bin/python import os import datetime from pytz.tzfile im...
python-tz am I wrong or it's a bug
It's a bit weird it seems that when I want to get a timezone for Europe/Paris with pytz it gets me to the PMT timezone instead of GMT+1 when it seems to work for Europe/Berlin. Not clear ? Well look at this snippet : #!/usr/bin/python import os import datetime from pytz.tzfile import build_tzinfo base='/usr/share/zone...
[ "The docs say you can't use datetime.datetime(..., tzinfo) like you're doing:\n\nUnfortunately using the tzinfo argument of the standard datetime constructors does not work with pytz for many timezones.\n\nAnd curiously, despite all signs that the Europe/Paris timezone is wrong, when you actually use with localize ...
[ 6 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0002171189_python_timezone.txt
Q: how to wait for a pause in user input in a gtk.TextBuffer? I'm trying to write a simple gui-based application in pygtk which provides 'live' previewing of text-based markup. The markup processing, however, can be quite computationally expensive and slow to run, so updating the preview on every keystroke is not re...
how to wait for a pause in user input in a gtk.TextBuffer?
I'm trying to write a simple gui-based application in pygtk which provides 'live' previewing of text-based markup. The markup processing, however, can be quite computationally expensive and slow to run, so updating the preview on every keystroke is not really viable. Instead I'd like to have the update run only when ...
[ "so I think I found a solution using glib.timeout_add() instead of threading.Timer:\nimport gtk, glib\n\nclass example:\n def __init__(self):\n window = gtk.Window()\n window.set_title(\"example\")\n window.resize(600,400)\n box = gtk.HBox(homogeneous = True, spacing = 2)\n sel...
[ 1, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002170851_gtk_pygtk_python.txt
Q: How to implement a client admin in Django? I'm building a simple app, a sort of project/tasks manager where I can have several projects and several tasks that are assigned to one project. I enabled Django admin for all this sort of tasks and it's working like a charm. Also, I have some users that have projects ass...
How to implement a client admin in Django?
I'm building a simple app, a sort of project/tasks manager where I can have several projects and several tasks that are assigned to one project. I enabled Django admin for all this sort of tasks and it's working like a charm. Also, I have some users that have projects assigned to them. So what I want now is to enable a...
[ "+1 for custom app, hacking admin can take more time than just putting together your own admin from generic views.\n", "I think that the best way to do this, either way, would be to somehow implement row-level permissions.\nAt the moment, the best solution for this is probably using the django-granular-permission...
[ 3, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002171820_django_django_admin_python.txt
Q: python how to -generate license- using time module I'm searching for a way to generate a (limited time license) .so when a user starts the program . it has to check license date first before the program runs. but the problem is : i tried a couple of solutions . one of them is python's time.ctime , (to check time a...
python how to -generate license- using time module
I'm searching for a way to generate a (limited time license) .so when a user starts the program . it has to check license date first before the program runs. but the problem is : i tried a couple of solutions . one of them is python's time.ctime , (to check time and see if it's realy during the license time) and it ret...
[ "Regardless with the question whether or not this hassle is really worth the effort, you can check access times of ubiquitous files (e.g. /etc/passwd in Linux) and compare these to the current date. If you see that the files have been accessed/modified in the future, you know that there is a problem. Again, at leas...
[ 3, 1, 0 ]
[]
[]
[ "datetime", "licensing", "python", "time" ]
stackoverflow_0002171902_datetime_licensing_python_time.txt
Q: Python regex for matching bb code I'm writing a very simple bbcode parse. If i want to replace hello i'm a [b]bold[/b] text, i have success with replacing this regex r'\[b\](.*)\[\/b\]' with this <strong>\g<1></strong> to get hello, i'm a <strong>bold</strong> text. If I have two or more tags of the same type, it...
Python regex for matching bb code
I'm writing a very simple bbcode parse. If i want to replace hello i'm a [b]bold[/b] text, i have success with replacing this regex r'\[b\](.*)\[\/b\]' with this <strong>\g<1></strong> to get hello, i'm a <strong>bold</strong> text. If I have two or more tags of the same type, it fails. eg: i'm [b]bold[/b] and i'm [b...
[ "You shouldn't use regular expressions to parse non-regular languages (like matching tags). Look into a parser instead.\nEdit - a quick Google search takes me here.\n", "Just change your regular expression from:\nr'\\[b\\](.*)\\[\\/b\\]'\n\nto\nr'\\[b\\](.*?)\\[\\/b\\]'\n\nThe * qualifier is greedy, appending a ...
[ 7, 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002172046_python_regex.txt
Q: draw hebrew text to an image using Image module (python) I am trying to use Image module in order to make bitmaps with hebrew lettering in it. when printing from the shell (idle) I managed to print hebrew, but when trying to draw text to a bitmap it draws some ascii lettering. this is the code: import Image impo...
draw hebrew text to an image using Image module (python)
I am trying to use Image module in order to make bitmaps with hebrew lettering in it. when printing from the shell (idle) I managed to print hebrew, but when trying to draw text to a bitmap it draws some ascii lettering. this is the code: import Image import ImageDraw a = "אריאל" #or any other hebrew string im=Imag...
[ "Try a = u\"אריאל\".\nFailing that, try PyCairo. It has advanced typography handling that may work better.\n", "This site mentions that to draw Chinese text, they had to specify that the string was unicode, so you should do the same, e.g.\na = u\"אריאל\" #like this\na = unicode(\"אריאל\", \"UTF-8\") #or like this...
[ 1, 1 ]
[]
[]
[ "draw", "image", "python" ]
stackoverflow_0002171910_draw_image_python.txt
Q: problem with breadth first tree generation i have a problem with breadth first algorithm, my script generates curves in maya, position them, rotate and scale them so they give me the tree shape, i have these variables cs=current State, p=parent, nodes=non visited node List lvl=current depth maxlvl= max depth the p...
problem with breadth first tree generation
i have a problem with breadth first algorithm, my script generates curves in maya, position them, rotate and scale them so they give me the tree shape, i have these variables cs=current State, p=parent, nodes=non visited node List lvl=current depth maxlvl= max depth the problem is that i cant determine current depth, a...
[ "You need to associate the depth with each node. Either put it as a member in the node class, or have your queue entries store both depth and node like this:\nnodes.append((1, firstNode))\nwhile nodes and lvl<5:\n lvl, p = nodes.pop(0)\n\n For each child:\n #...create child\n nodes.append((lvl+1...
[ 4 ]
[]
[]
[ "breadth_first_search", "python", "tree" ]
stackoverflow_0002171733_breadth_first_search_python_tree.txt
Q: Parsing forwarded emails I'm writing some code to parse forwarded emails. What I'm not sure is if maybe there is some Python library, some RFC I could stick to or some other resource that would allow me to automate the task. To be precise, I don't know if the "layout" of forwarded emails is covered by some standa...
Parsing forwarded emails
I'm writing some code to parse forwarded emails. What I'm not sure is if maybe there is some Python library, some RFC I could stick to or some other resource that would allow me to automate the task. To be precise, I don't know if the "layout" of forwarded emails is covered by some standard or recommendation, or if it...
[ "Unlike what many other people said, there is a standard on forwarded emails, RFC 2046, \"Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types\", more than ten years old. See specially its section 5.2, \"Message Media Type\".\nThe basic idea behind RFC 2046 is to encapsulate one message into the MIME ...
[ 5, 2, 2, 1 ]
[]
[]
[ "python", "rfc" ]
stackoverflow_0002168719_python_rfc.txt
Q: How does len work? How does len work on Python? Look at this example: class INT(int): pass class STR(str): def __len__(self): return INT(42) q = STR('how').__len__() print q, type(q) q = len(STR('how')) print q, type(q) The output is: 42 <class '__main__.INT'> 42 <type 'int'> How can I handle ...
How does len work?
How does len work on Python? Look at this example: class INT(int): pass class STR(str): def __len__(self): return INT(42) q = STR('how').__len__() print q, type(q) q = len(STR('how')) print q, type(q) The output is: 42 <class '__main__.INT'> 42 <type 'int'> How can I handle it so len returns an INT...
[ "Do not do this. You need to learn when the best answer really is not to do what you are trying to do at all. This is one of those times.\n", "I don't think you can, unless you write your own len.\nThe builtin len always return an int.\n", "You won't be able to. At least if you want it to work with the rest of ...
[ 4, 3, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002171960_python.txt
Q: Best python UI package for simple graph simulations (TSP simulation, etc...) I've never done any UI programming in python before. What is the best (read most intuitive, easy to use, functional) UI package for python for doing simulations? I'll be doing a simulation of TSP right now. So I'll have a graph (nodes...
Best python UI package for simple graph simulations (TSP simulation, etc...)
I've never done any UI programming in python before. What is the best (read most intuitive, easy to use, functional) UI package for python for doing simulations? I'll be doing a simulation of TSP right now. So I'll have a graph (nodes and edges) where the edges are rapidly changing, along with some selection boxes ...
[ "I am not sure what you mean by \"simulations\" since the type of UI you want to do depends on what you simulate. But if you want to visualize graphs, networkx is pretty cool.\n", "Such a simulation could be easily coded using:\n\nnetworkx - for the graph data structures and algorithms\nmatplotlib - which is used...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0002172302_python_user_interface.txt
Q: Why I can't extend bool in Python? >>> class BOOL(bool): ... print "why?" ... why? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type I thought Python trusted the programmer. A: Guido's ta...
Why I can't extend bool in Python?
>>> class BOOL(bool): ... print "why?" ... why? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type I thought Python trusted the programmer.
[ "Guido's take on it:\n\nI thought about this last\n night, and realized that you shouldn't\n be allowed to subclass bool at all! A\n subclass would only be useful when it\n has instances, but the mere existance\n of an instance of a subclass of bool\n would break the invariant that True\n and False are the ...
[ 58, 12, 12, 9, 3 ]
[]
[]
[ "boolean", "python", "restriction" ]
stackoverflow_0002172189_boolean_python_restriction.txt
Q: Where is gsl_cdf_beta_Pinv() in PyGSL? I'm trying to use the distribution functions in a Python program (the random functions I've got figured out; I'm looking specifically for gsl_cdf_beta_Pinv()) and I can't find it. Can someone tell me how I can use these or a fast alternative in a program? Thanks, Mark Ch. A...
Where is gsl_cdf_beta_Pinv() in PyGSL?
I'm trying to use the distribution functions in a Python program (the random functions I've got figured out; I'm looking specifically for gsl_cdf_beta_Pinv()) and I can't find it. Can someone tell me how I can use these or a fast alternative in a program? Thanks, Mark Ch.
[ "It's defined in this Cython source file (for module probability_distribution) as being mediated by the method cum_distribution_function_inv of an instance of class RealDistribution when its self.distribution_type==beta. So you should import the module, instantiate the class, and then call the method -- e.g.\nfrom...
[ 1 ]
[]
[]
[ "gsl", "pygsl", "python" ]
stackoverflow_0002172128_gsl_pygsl_python.txt
Q: How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two? Suppose I have the following tables: Articles with fields article_id, title Tags with fields tag_id, name ArticleTags with fields article_id, tag_id And I wish to find all articles that have a given tag. How do I create t...
How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two?
Suppose I have the following tables: Articles with fields article_id, title Tags with fields tag_id, name ArticleTags with fields article_id, tag_id And I wish to find all articles that have a given tag. How do I create this complicated join in SQLAlchemy? In SQL it would look like: SELECT a.article_id, a.title FROM ...
[ "Assuming that you set the ForeignKey constraints correctly and created mappers:\nq = Session.query(Articles).filter(Articles.article_id == ArticleTags.article_id).\\\n filter(ArticleTags.tag_id == Tags.tag_id).\\\n filter(Tags.name == 'tag_name')\n\nIf you have setup a Many-to-Many relation it's even more si...
[ 9 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002173031_python_sql_sqlalchemy.txt
Q: Is there any way to create a class property in Python? The following doesn't work for some reason: >>> class foo(object): ... @property ... @classmethod ... def bar(cls): ... return "asdf" ... >>> foo.bar <property object at 0x1da8d0> >>> foo.bar + '\n' Traceback (most recent call last): ...
Is there any way to create a class property in Python?
The following doesn't work for some reason: >>> class foo(object): ... @property ... @classmethod ... def bar(cls): ... return "asdf" ... >>> foo.bar <property object at 0x1da8d0> >>> foo.bar + '\n' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported ...
[ "If you want the descriptor property to trigger when you get an attribute from object X, then you must put the descriptor in type(X). So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no \"trickery\" involved, it's just a matter of completely general rules.\nAlt...
[ 6 ]
[]
[]
[ "class", "class_method", "properties", "python" ]
stackoverflow_0002173206_class_class_method_properties_python.txt
Q: two conflicting meanings of builtins in python 3 (python 3.1, python 3k, python3000) I just posted below query to comp.lang.python, but i feel this kind of question has some kind of right-of-way here on Stack Overflow, too, so be it repeated. the essence: why does ‘builtins’ have two distinct interpretations in Py...
two conflicting meanings of builtins in python 3 (python 3.1, python 3k, python3000)
I just posted below query to comp.lang.python, but i feel this kind of question has some kind of right-of-way here on Stack Overflow, too, so be it repeated. the essence: why does ‘builtins’ have two distinct interpretations in Python 3? I would be very gladly accept any commentaries about what this sentence, gleaned f...
[ "getattr(__builtins__, '__dict__', __builtins__) should give you the dict that you want to update to \"export names to the global namespace\", whether __builtins__ is a dict (then it doesn't have a __dict__ attribute so getattr returns the third argument, which is the dict __builtins__ itself) or a module (then it ...
[ 1 ]
[]
[]
[ "built_in", "python", "python_3.x" ]
stackoverflow_0002173425_built_in_python_python_3.x.txt
Q: Returning binomal as a tuple I want to save the results of my function binomal_aux to a tuple but I don't have an idea how to, here is my code I have right now. def binomal (n): i=0 for i in range(n): binomal_aux(n,i) #want this to be in a tuple so, binomal (2) = (1,2,1) return def binomal...
Returning binomal as a tuple
I want to save the results of my function binomal_aux to a tuple but I don't have an idea how to, here is my code I have right now. def binomal (n): i=0 for i in range(n): binomal_aux(n,i) #want this to be in a tuple so, binomal (2) = (1,2,1) return def binomal_aux (n,k): if (k==0): ...
[ "In your binomal function, just make the tuple you want to return.\ndef binomal(n):\n return tuple(binomal_aux(n, i) for i in range(n+1))\n\nNote also that the correct spelling is binomial.\n", "def binomal (n): \n return tuple(binomal_aux(n,i) for i in range(n+1))\n\n", "Alternate way:\ndef binomal(n): ...
[ 2, 0, 0 ]
[]
[]
[ "python", "recursion", "tuples" ]
stackoverflow_0002173451_python_recursion_tuples.txt
Q: In PyQt, how can signals and slots be used to connect a dropdownlist to a function? In PyQt, there's a concept of signals and slots to connect objects to one another's functions, but I can't seem to find them referenced to functions not associated with other objects. For example, I want a dropdown list to have al...
In PyQt, how can signals and slots be used to connect a dropdownlist to a function?
In PyQt, there's a concept of signals and slots to connect objects to one another's functions, but I can't seem to find them referenced to functions not associated with other objects. For example, I want a dropdown list to have algorithm A or algorithm B run. How does PyQt accomplish this functionality?
[ "Do you want the effect of changing the drop down list to call a function?\nConnect the dropdown list's appropriate signal to your function.\nFor example with the QComboBox currentIndexChanged() signal. Connect that to a \"wrapper\" function that decides (based on the index) which function to call.\nEdit: The wrapp...
[ 3 ]
[]
[]
[ "pyqt", "python", "user_interface" ]
stackoverflow_0002173449_pyqt_python_user_interface.txt
Q: Why is this genexp performing worse than a list comprehension? I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list. While doing this, I was surprised by the results of comparing a list comprehension ...
Why is this genexp performing worse than a list comprehension?
I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list. While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression: python -m timeit -s "L = xra...
[ "When essentially unlimited memory is available (which will invariably be the case in tiny benchmarks, although often not in real-world problems!-), lists will tend to outperform generators because they can get allocated just once, in one \"big bunch\" (no memory fragmentation, etc), while generators require (inter...
[ 15, 3 ]
[]
[]
[ "generator_expression", "list_comprehension", "python" ]
stackoverflow_0002173845_generator_expression_list_comprehension_python.txt
Q: How to create folders using file names and then move files into folders? I have hundreds of text files in a folder named using this kind of naming convention: Bandname1 - song1.txt Bandname1 - song2.txt Bandname2 - song1.txt Bandname2 - song2.txt Bandname2 - song3.txt Bandname3 - song1.txt ..etc. I would like to ...
How to create folders using file names and then move files into folders?
I have hundreds of text files in a folder named using this kind of naming convention: Bandname1 - song1.txt Bandname1 - song2.txt Bandname2 - song1.txt Bandname2 - song2.txt Bandname2 - song3.txt Bandname3 - song1.txt ..etc. I would like to create folders for different bands and move according text files into these fo...
[ "It's not necessary to use trim or xargs:\nfor f in *.txt; do\n band=${f% - *}\n mkdir -p \"$band\"\n mv \"$f\" \"$band\"\ndone\n\n", "with Perl\nuse File::Copy move;\nwhile (my $file= <*.txt> ){\n my ($band,$others) = split /\\s+-\\s+/ ,$file ;\n mkdir $band;\n move($file, $band);\n}\n\n", "Y...
[ 4, 2, 1, 1, 0, 0 ]
[ "ls |perl -lne'$f=$_; s/(.+?) - [^-]*\\.txt/$1/; mkdir unless -d; rename $f, \"$_/$f\"'\n\n" ]
[ -1 ]
[ "bash", "batch_file", "perl", "python", "unix" ]
stackoverflow_0002172420_bash_batch_file_perl_python_unix.txt
Q: How do you get a responsive GUI if your codebehind is running an infinte loop? PyQT If you have a function consistently running an infinite loop in the background, how will your GUI ever be responsive? It is waiting for the loop to finish and this renders the interface useless. How is this solved in PyQT? A: U...
How do you get a responsive GUI if your codebehind is running an infinte loop? PyQT
If you have a function consistently running an infinite loop in the background, how will your GUI ever be responsive? It is waiting for the loop to finish and this renders the interface useless. How is this solved in PyQT?
[ "Use threads.\nIn Qt, they use something called Signals and Slots. I haven't used Qt since college, but there are plenty of good resources here:\nPyQt Wiki: Threading,_Signals_and_Slots\nSee also this related SO post: Threading in a PyQt application: Use Qt threads or Python threads? or\nPython - PyQt app in sepera...
[ 4, 0 ]
[]
[]
[ "multithreading", "pyqt", "python", "user_interface" ]
stackoverflow_0002174039_multithreading_pyqt_python_user_interface.txt
Q: Can't get wx.BufferedDC to draw anything I've got a problem with DCs. I'm trying to make an application that will draw many lines on the screens and needs to update really fast, and since I don't want flickering, I decided to give buffered dcs a shot. But when I run this code, it doesn't draw anything. What am I d...
Can't get wx.BufferedDC to draw anything
I've got a problem with DCs. I'm trying to make an application that will draw many lines on the screens and needs to update really fast, and since I don't want flickering, I decided to give buffered dcs a shot. But when I run this code, it doesn't draw anything. What am I doing wrong? import wx class MainFrame(wx.Fram...
[ "I've used AutoBufferedPaintDC, but I've found doing my own double-buffering with a MemoryDC to be more flexible. Here's a template for you.\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n super(Frame, self).__init__(None, -1, 'CursorTracker')\n self.mdc = None # memory dc to draw off...
[ 3, 1 ]
[]
[]
[ "python", "wxwidgets" ]
stackoverflow_0002173821_python_wxwidgets.txt
Q: recursive nested expression in Python I am using Python 2.6.4. I have a series of select statements in a text file and I need to extract the field names from each select query. This would be easy if some of the fields didn't use nested functions like to_char() etc. Given select statement fields that could have s...
recursive nested expression in Python
I am using Python 2.6.4. I have a series of select statements in a text file and I need to extract the field names from each select query. This would be easy if some of the fields didn't use nested functions like to_char() etc. Given select statement fields that could have several nested parenthese like "ltrim(rtrim(...
[ "Regular expressions are not suitable for parsing \"nested\" structures. Try, instead, a full-fledged parsing kit such as pyparsing -- examples of using pyparsing specifically to parse SQL can be found here and here, for example (you'll no doubt need to take the examples just as a starting point, and write some pa...
[ 11, 2, 2, 1, 1, 0 ]
[]
[]
[ "expression", "nested", "python", "regex" ]
stackoverflow_0002174015_expression_nested_python_regex.txt
Q: In the Python Google App Engine, how to mock or subclass the File class so that software written to access files does not throw an exception? I would like to run some code on the Python version of Google App Engine that uses the built in File type. I’m looking for the easiest way to stop GAE from throwing errors d...
In the Python Google App Engine, how to mock or subclass the File class so that software written to access files does not throw an exception?
I would like to run some code on the Python version of Google App Engine that uses the built in File type. I’m looking for the easiest way to stop GAE from throwing errors due to illegal access. Has anyone already sub-classed or mocked File to read and write to memory rather than to the disk? I don’t need persistence, ...
[ "import __builtin__\nimport StringIO\n\nclass File(StringIO.StringIO):\n def __init__(self, *a, **k): pass\n\n__builtin__.file = __builtin__.open = File\n\nYou'll surely want finer-grained simulation, but this works as a very rough first cut.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002174596_google_app_engine_python.txt
Q: pinax ImportError cannot import name UserOpenidAssociation I have these errors: ImportError at / cannot import name UserOpenidAssociation. I could not make any sense out of the traceback: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.1.1 Python Version: 2.6.1 Installed Applications: ...
pinax ImportError cannot import name UserOpenidAssociation
I have these errors: ImportError at / cannot import name UserOpenidAssociation. I could not make any sense out of the traceback: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.1.1 Python Version: 2.6.1 Installed Applications: ['inventory.inlanddbase'] Installed Middleware: ('django.middlew...
[ "sudo pip install django_openid\n" ]
[ 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002173829_django_pinax_python.txt
Q: Migrating from Javadoc to Python Documentation So I've gotten somewhat used to Javadoc style documentation. Looking through various examples of Python code, I'm finding that, at first blush, the documentation seems to be missing a lot of information. The good: vary rarely do you see self-evident bits of documentat...
Migrating from Javadoc to Python Documentation
So I've gotten somewhat used to Javadoc style documentation. Looking through various examples of Python code, I'm finding that, at first blush, the documentation seems to be missing a lot of information. The good: vary rarely do you see self-evident bits of documentation. Docstrings are usually a paragraph or less of E...
[ "The reStructuredText format was designed in response to the need for Python documentation that could be embedded in docstrings, so the best thing is to learn reST and format your docstrings with that format. You might find, as I did, that you then go on to format just about any documentation in reST, but that's a ...
[ 9 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002175040_python_python_sphinx.txt
Q: How would I discover the memory used by an application through a python script? Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer i...
How would I discover the memory used by an application through a python script?
Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it. It seems reasonable to assume that there's a way to query the os (windows 7) API f...
[ "this answer has some code (for windows and unix):\nTotal memory used by Python process?\non win, you are checking Win32_PerfRawData_PerfProc_Process and on linux it's /proc/pid/status (or ps)\n", "Remember that Squish allows remote testing of the application. A system parameter queried via Python directly will o...
[ 2, 0 ]
[ "In command line: tasklist /FO LIST and parse the results?\nSorry, I don't know a Pythonic way. =P\n" ]
[ -1 ]
[ "memory_management", "python", "squish", "windows_7" ]
stackoverflow_0002084063_memory_management_python_squish_windows_7.txt
Q: mercurial - I want to add some custom code to be run after commit where could I place code to be run after every commit I make with mercurial? Specifically, I would like to maintain a file called latest inside the .hg folder in the root of my project - that file will hold the revision number and hash code for the ...
mercurial - I want to add some custom code to be run after commit
where could I place code to be run after every commit I make with mercurial? Specifically, I would like to maintain a file called latest inside the .hg folder in the root of my project - that file will hold the revision number and hash code for the most recent commit. On that same topic, how can I get those in python? ...
[ "http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html\nspecifically you seem to want the commit hook which there is a tutorial for\nof course it sounds like what you really want is hg tip\n" ]
[ 5 ]
[]
[]
[ "automation", "customization", "mercurial", "python" ]
stackoverflow_0002175788_automation_customization_mercurial_python.txt
Q: Why do we need tuples in Python (or any immutable data type)? I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples. Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be ...
Why do we need tuples in Python (or any immutable data type)?
I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples. Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first p...
[ "\nimmutable objects can allow substantial optimization; this is presumably why strings are also immutable in Java, developed quite separately but about the same time as Python, and just about everything is immutable in truly-functional languages.\nin Python in particular, only immutables can be hashable (and, ther...
[ 131, 42, 25, 15, 9, 8, 6, 1, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002174124_python_tuples.txt
Q: Implementing chat system with in Web browser We want to have web based application to track the issues, knowledge management and chat system. Once the user logged in, user can chat with the service engineers. We will be using Ajax for Chat within the browser. But the server-side we are not sure how to implement ch...
Implementing chat system with in Web browser
We want to have web based application to track the issues, knowledge management and chat system. Once the user logged in, user can chat with the service engineers. We will be using Ajax for Chat within the browser. But the server-side we are not sure how to implement chat? The chat history must be saved for lateral vie...
[ "Oh. If I have to implement something like this, I would take a XMPP (Jabber) server. Why to reinvent?\nThere are two servers that are pretty stable and feature rich: ejabberd (implemented in Erlang) and OpenFire (implemented in Java). Personally I prefer OpenFire since it easier to configure and Java developers ar...
[ 4, 2, 1 ]
[]
[]
[ ".net", "php", "python", "ruby_on_rails" ]
stackoverflow_0002175513_.net_php_python_ruby_on_rails.txt
Q: Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other) Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: pickle/cpickle json jsonpickle xml database...
Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other)
Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: pickle/cpickle json jsonpickle xml database (like SQLite) Pickle is the easiest and fastest technique, but my understanding is that there is no guarantee th...
[ "You have a misconception about pickles: they are guaranteed to work across Python versions. You simply have to choose a protocol version that is supported by all the Python versions you care about.\nThe technique you left out is marshal, which is not guaranteed to work across Python versions (and btw, is how .pyc...
[ 15, 4, 2, 2 ]
[]
[]
[ "json", "pickle", "python", "sqlite" ]
stackoverflow_0002003693_json_pickle_python_sqlite.txt
Q: How to create "virtual root" with Python's ElementTree? I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES...
How to create "virtual root" with Python's ElementTree?
I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc. How do I do that? Thanks
[ "I don't know if there's a better way but I've seen this done:\nCreate the base document as a string:\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html></html>\n\nThen parse that string to start your new document.\n", "I have had ...
[ 7, 1 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0001070772_elementtree_python.txt
Q: Signal handling in Python In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below: def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR...
Signal handling in Python
In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below: def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') return signal.signal(...
[ "Mixing signals and threads is always a little precarious. What you describe should not happen, however. Python only handles signals in the main thread. If the OS delivered the signal to another thread, that thread may be briefly interrupted (when it's performing, say, a systemcall) but it won't execute the signal ...
[ 2, 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "signals" ]
stackoverflow_0002163194_multithreading_python_signals.txt
Q: How do I convert a string to a buffer in Python 3.1? I am attempting to pipe something to a subprocess using the following line: p.communicate("insert into egg values ('egg');"); TypeError: must be bytes or buffer, not str How can I convert the string to a buffer? A: The correct answer is: p.communicate(b"inse...
How do I convert a string to a buffer in Python 3.1?
I am attempting to pipe something to a subprocess using the following line: p.communicate("insert into egg values ('egg');"); TypeError: must be bytes or buffer, not str How can I convert the string to a buffer?
[ "The correct answer is:\np.communicate(b\"insert into egg values ('egg');\");\n\nNote the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:\nvalue = open('thefile', 'rt').read()\np.communicate(value);\n\nThe change that to:\nvalue = op...
[ 12, 7 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002176511_python_python_3.x.txt
Q: Individually labeled bars for bar graphs in matplotlib / Python I am trying to create bar graphs of letter frequency in Python. I thought the best way to accomplish this would be matplotlib, but I have been unable to decipher the documentation. Is it possible to label the bars of a matplotlib.pyplot.hist plot with...
Individually labeled bars for bar graphs in matplotlib / Python
I am trying to create bar graphs of letter frequency in Python. I thought the best way to accomplish this would be matplotlib, but I have been unable to decipher the documentation. Is it possible to label the bars of a matplotlib.pyplot.hist plot with one letter per bar, instead of a numerical axis? I think it must be,...
[ "Sure is! You just need to reset the tick labels.\nEDIT with answer and picture (can be done similarly with hist):\nx = scipy.arange(4)\ny = scipy.array([4,7,6,5])\nf = pylab.figure()\nax = f.add_axes([0.1, 0.1, 0.8, 0.8])\nax.bar(x, y, align='center')\nax.set_xticks(x)\nax.set_xticklabels(['Aye', 'Bee', 'Cee', 'De...
[ 34 ]
[]
[]
[ "histogram", "label", "matplotlib", "plot", "python" ]
stackoverflow_0002177504_histogram_label_matplotlib_plot_python.txt
Q: Python: How do I disallow imports of a class from a module? I tried: __all__ = ['SpamPublicClass'] But, of course that's just for: from spammodule import * Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write: from spammodule import Simila...
Python: How do I disallow imports of a class from a module?
I tried: __all__ = ['SpamPublicClass'] But, of course that's just for: from spammodule import * Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write: from spammodule import SimilarSpamClass and it'll cause debugging mayhem.
[ "The convention is to use a _ as a prefix:\nclass PublicClass(object):\n pass\n\nclass _PrivateClass(object):\n pass\n\nThe following:\nfrom module import *\n\nWill not import the _PrivateClass.\nBut this will not prevent them from importing it. They could still import it explicitly.\nfrom module import _Pri...
[ 20, 7, 5 ]
[]
[]
[ "import", "python", "python_import", "python_module" ]
stackoverflow_0002177817_import_python_python_import_python_module.txt
Q: Inserting multiple types into an SQLite database with Python I'm trying to create an SQLite 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand al...
Inserting multiple types into an SQLite database with Python
I'm trying to create an SQLite 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand all the differences. My problem is the INSERT statement. DAS = 12345...
[ "The type real(4) does not mean an array/list/tuple of 4 reals; the 4 alters the 'real' type. However, SQLite mostly ignores column types due to its manifest typing, but they can still affect column affinity.\nYou have a few options, such as storing the text representation (from repr) or using four columns, one fo...
[ 1, 0, 0 ]
[]
[]
[ "insert", "python", "sqlite" ]
stackoverflow_0001963790_insert_python_sqlite.txt
Q: Trying to understand Django's sorl-thumbnail I have been playing around with sorl-thumbnail for Django. And trying to understand how it works better. I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put sorl.thumbnail in the INSTALLED APPS in my settings.py, put ...
Trying to understand Django's sorl-thumbnail
I have been playing around with sorl-thumbnail for Django. And trying to understand how it works better. I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put sorl.thumbnail in the INSTALLED APPS in my settings.py, put from sorl.thumbnail.fields import ImageWithThumbna...
[ "I'm one of the sorl-thumbnail developers.\nFirstly, you don't need to {% load thumbnail %} unless you're just using the thumbnail tag rather than a thumbnail field.\nCurrently, a thumbnail is only ever created the first time it is used - even if you use the field [I'll get around to changing that one day if no-one...
[ 2, 0 ]
[]
[]
[ "django", "image_processing", "python" ]
stackoverflow_0001171680_django_image_processing_python.txt
Q: How can I step into pdb to diagnose this error on a production server? ProgrammingError(1110, "Column 'about' specified twice" ProgrammingError(1110, "Column 'about' specified twice" /usr/local/lib/python2.5/site-packages/MySQLdb/connections.py errorclass <class '_mysql_exceptions.ProgrammingError'> errorv...
How can I step into pdb to diagnose this error on a production server? ProgrammingError(1110, "Column 'about' specified twice"
ProgrammingError(1110, "Column 'about' specified twice" /usr/local/lib/python2.5/site-packages/MySQLdb/connections.py errorclass <class '_mysql_exceptions.ProgrammingError'> errorvalue ProgrammingError(1110, "Column 'about' specified twice") This error seems to be happening here in django_authopenid/view...
[ "If you're asking how to break into pdb, add this line in your code where you want to drop into the debugger:\nimport pdb; pdb.set_trace() \n\nIf you need to know how to have a stdout on your production server, I don't know that.\n" ]
[ 0 ]
[]
[]
[ "django", "pdb", "python" ]
stackoverflow_0002177929_django_pdb_python.txt
Q: Opening POSTed file with PIL Image Using WSGI, webob and PIL, I'm trying to use Image.open() on a file directly from the request. However, Image.open() always throws the exception "cannot identify image file". The image is the only field, no other POST or GET variables are used. The file is coming from a standa...
Opening POSTed file with PIL Image
Using WSGI, webob and PIL, I'm trying to use Image.open() on a file directly from the request. However, Image.open() always throws the exception "cannot identify image file". The image is the only field, no other POST or GET variables are used. The file is coming from a standard HTML upload form with enctype="multip...
[ "I'm not famaliar with webob, but my guess is that body_file contains the contents of the entire post and not just your image. The docs seem to confirm this.\nWhat's in req.POST['nameOfFileControl']? Does that have a file handle? That is going to be the file handle that Image.open needs.\n" ]
[ 4 ]
[]
[]
[ "mod_wsgi", "python", "webob" ]
stackoverflow_0002174938_mod_wsgi_python_webob.txt
Q: In python, sorting on date field, field may sometimes be null I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following: results = so...
In python, sorting on date field, field may sometimes be null
I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following: results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=Tr...
[ "Using a key= function is definitely right, you just have to decide how you want to treat the None values -- pick a datetime value that you want to treat as the equivalent of None for sorting purposes. E.g.:\nimport datetime\nmindate = datetime.date(datetime.MINYEAR, 1, 1)\n\ndef getaccountingdate(x):\n return x[...
[ 30, 12 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002178931_python_sorting.txt
Q: unpredicted output binary search tree in python class Node(): def __init__(self,data, left=None, right=None): self.data = data self.left = left self.right = right class BSTree(): def __init__(self): self.root = None def add(self,data): if self.root is None:...
unpredicted output binary search tree in python
class Node(): def __init__(self,data, left=None, right=None): self.data = data self.left = left self.right = right class BSTree(): def __init__(self): self.root = None def add(self,data): if self.root is None: self.root = Node(data) self....
[ " def __add(self,node,data): \n if node is None: \n return Node(data) \n else: \n if data < node.data: \n node.left = self.__add(node.left,data) \n elif data > node.data: \n node.right = self.__add(node.right,data) \n\nThis function is inc...
[ 3, 0 ]
[]
[]
[ "binary_tree", "python" ]
stackoverflow_0002174679_binary_tree_python.txt
Q: Problem installing MySQLdb on windows - Can't find python I'm trying to install the module mySQLdb on a windows vista 64 (amd) machine. I've installed python on a different folder other than suggested by Python installer. When I try to install the .exe mySQLdb installer, it can't find python 2.5 and it halts the i...
Problem installing MySQLdb on windows - Can't find python
I'm trying to install the module mySQLdb on a windows vista 64 (amd) machine. I've installed python on a different folder other than suggested by Python installer. When I try to install the .exe mySQLdb installer, it can't find python 2.5 and it halts the installation. Is there anyway to supply the installer with the c...
[ "did you use an egg?\nif so, python might not be able to find it.\nimport os,sys\nos.environ['PYTHON_EGG_CACHE'] = 'C:/temp'\nsys.path.append('C:/path/to/MySQLdb.egg')\n" ]
[ 0 ]
[]
[]
[ "mysql", "python", "windows_installer" ]
stackoverflow_0001980454_mysql_python_windows_installer.txt
Q: python chaining Updated Let's say I have: dic={"z":"zv", "a":"av"} ## why doesn't the following return a sorted list of keys? keys=dic.keys().sort() I know I could do the following and have the proper result: dic={"z":"zv", "a":"av"} keys=dic.keys() skeys=keys.sort() ### skeys will be None Why doesn't the first...
python chaining
Updated Let's say I have: dic={"z":"zv", "a":"av"} ## why doesn't the following return a sorted list of keys? keys=dic.keys().sort() I know I could do the following and have the proper result: dic={"z":"zv", "a":"av"} keys=dic.keys() skeys=keys.sort() ### skeys will be None Why doesn't the first example work?
[ ".sort doesn't return the list. You could do:\nkeys = sorted(dic.keys())\n\n", "sort() modifies the contents of the existing list. it doesn't return a list. See the manual.\n" ]
[ 16, 13 ]
[]
[]
[ "python" ]
stackoverflow_0002179241_python.txt
Q: Using python properties in django models? My problem relates to this question: Default ordering for m2m items by intermediate model field in Django class Group(models.Model): name = models.CharField(max_length=128) _members = models.ManyToManyField(Person, through='Membership') @property def members(se...
Using python properties in django models?
My problem relates to this question: Default ordering for m2m items by intermediate model field in Django class Group(models.Model): name = models.CharField(max_length=128) _members = models.ManyToManyField(Person, through='Membership') @property def members(self): return self._members.order_by('memb...
[ "If it's a one-off, you can exclude the _members field when you create the modelform:\nclass GroupForm(ModelForm):\n class Meta:\n model=Group\n exclude = {'_members',}\n\nIf you do this a lot, you might consider creating a subclass of ModelForm and override the init method to automatically exclude...
[ 0 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0002178688_django_models_python.txt
Q: Dynamically import a callable given the full module path? >>> import_path('os.path.join') <function join at 0x22d4050> What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package. A: This seems to be what you want: def import_p...
Dynamically import a callable given the full module path?
>>> import_path('os.path.join') <function join at 0x22d4050> What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package.
[ "This seems to be what you want:\ndef import_path(name):\n modname, _, attr = name.rpartition('.')\n if not modname:\n # name was just a single module name\n return __import__(attr)\n m = __import__(modname, fromlist=[attr])\n return getattr(m, attr)\n\nTo make it work with Python 2.5 and ...
[ 4, 0, 0 ]
[]
[]
[ "import", "introspection", "module", "python" ]
stackoverflow_0002179251_import_introspection_module_python.txt
Q: Enable Unicode "globally" in Python Is it possible to avoid having to put this in every page? # -*- coding: utf-8 -*- I'd really like Python to default to this. A: In Python 3, the default encoding is UTF-8, so you won't need to set it explicitly anymore. There isn't a way to 'globally' set the default source ...
Enable Unicode "globally" in Python
Is it possible to avoid having to put this in every page? # -*- coding: utf-8 -*- I'd really like Python to default to this.
[ "In Python 3, the default encoding is UTF-8, so you won't need to set it explicitly anymore. There isn't a way to 'globally' set the default source encoding, though, and history has shown that such global options are generally a bad idea. (For instance, the -U and -Q options to Python, and sys.setdefaultencoding() ...
[ 9, 1 ]
[ "It's a very bad idea for Python 2 because you will be expecting behavior which is only preset on your dev machine. Which means that when your library goes out to someone else, or to a host server, or elsewhere, any use of it will flood the logs with UnicodeDecodeErrors.\n" ]
[ -1 ]
[ "python", "unicode" ]
stackoverflow_0002179253_python_unicode.txt
Q: Am I passing the string correctly to the python library? I'm using a python library called Guess Language: http://pypi.python.org/pypi/guess-language/0.1 "justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japanese. Does anyone know wh...
Am I passing the string correctly to the python library?
I'm using a python library called Guess Language: http://pypi.python.org/pypi/guess-language/0.1 "justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japanese. Does anyone know why? Am I not encoding correctly? §ç©ºéå ¶ä»æ¡å°±æ²æéç¨®å¾ ...
[ "Looking at the main page, it says \"\"\"Detects over 60 languages; Greek (el), Korean (ko), Japanese (ja), Chinese (zh) and all the languages listed in the trigrams directory. \"\"\"\nIt doesn't use trigrams for those 4 languages; it relies on what script blocks are present in the input text. Looking at the source...
[ 7, 0 ]
[ "Google says your example is in chinese. They have a (much more advanced) webservice to translate text and guess the language.\nThey have an API and code examples for Python.\n" ]
[ -1 ]
[ "encoding", "nlp", "python", "unicode" ]
stackoverflow_0002164899_encoding_nlp_python_unicode.txt
Q: Python: penalty for sleeping threads this question relates to performance penalities that may or may not arise from having a large number of sleeping python threads on a webserver. Background: I am implementing an online shop using django/satchmo. A requirement is for delayed payment. The customer can reserve a pr...
Python: penalty for sleeping threads
this question relates to performance penalities that may or may not arise from having a large number of sleeping python threads on a webserver. Background: I am implementing an online shop using django/satchmo. A requirement is for delayed payment. The customer can reserve a product and allow a third party to pay for i...
[ "I see no reason why this shouldn't work. The underlying code for Timer (in threading.py) simply uses time.sleep. Once it's been waiting for awhile, it basically runs a loop with time.sleep(0.05) This should result in CPU usage of basically 0%, even with hundreds of threads. Here's a simple example, where I noticed...
[ 7, 4, 3 ]
[]
[]
[ "multithreading", "performance", "python" ]
stackoverflow_0002178563_multithreading_performance_python.txt
Q: How is the __format__ method supposed to be used for int? I saw there was a __format__ method but help(int.__format__) doesn't provide any help. I also know you're not suppose to call a __method__ directly. When is this method called? Which is its argument? A: It's used for Py3k's new string formatting scheme. Y...
How is the __format__ method supposed to be used for int?
I saw there was a __format__ method but help(int.__format__) doesn't provide any help. I also know you're not suppose to call a __method__ directly. When is this method called? Which is its argument?
[ "It's used for Py3k's new string formatting scheme.\nYou can find more info here:\nhttp://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting\nYou are right that it isn't called directly. It's called by str.format or the new format builtin.\n", "It's used when you pass an integer to the format()...
[ 6, 4 ]
[]
[]
[ "int", "python" ]
stackoverflow_0002179926_int_python.txt
Q: SQLAlchemy sqlalchemy.sql.expression.select vs. sqlalchemy.sql.expression.Select So I'm brand new to SQLAlchemy, and I'm trying to use the SQL Expression API to create a SELECT statement that specifies the exact columns to return. I found both a class and a function defined in the sqlalchmey.sql.expressions module...
SQLAlchemy sqlalchemy.sql.expression.select vs. sqlalchemy.sql.expression.Select
So I'm brand new to SQLAlchemy, and I'm trying to use the SQL Expression API to create a SELECT statement that specifies the exact columns to return. I found both a class and a function defined in the sqlalchmey.sql.expressions module and I'm not too sure which to use... Why do they have both a class and a function? Wh...
[ "Use the source.\nHere's the implementation of the select function, from the source code:\ndef select(columns=None, whereclause=None, from_obj=[], **kwargs):\n \"\"\"Returns a ``SELECT`` clause element.\n (... long docstring ...)\n \"\"\"\n return Select(columns, whereclause=whereclause, from_obj=from_o...
[ 3, 2, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002159874_python_sql_sqlalchemy.txt
Q: JPype - Issue importing & calling methods! Here I'm attaching my code below from jpype import * from javax.swing import JFrame classpath = "-Djava.class.path=praat.jar" startJVM(getDefaultJVMPath(),"-ea",classpath) frame = javax.swing.JFrame("Hello JPype") label = javax.swing.JLabel("Hello JPype!", JLabel.CENT...
JPype - Issue importing & calling methods!
Here I'm attaching my code below from jpype import * from javax.swing import JFrame classpath = "-Djava.class.path=praat.jar" startJVM(getDefaultJVMPath(),"-ea",classpath) frame = javax.swing.JFrame("Hello JPype") label = javax.swing.JLabel("Hello JPype!", JLabel.CENTER) frame.add(label) frame.setDefaultCloseOperat...
[ "Add the Java runtime library (rt.jar) to the classpath and try again. The error indicates, that JFrame can't be found but it is inside rt.jar.\n", "If you import JFrame into the local namespace, use it without the full namespace:\nframe = JFrame(\"Hello Jython\")\n\nSame with JLabel, but remember to import it fi...
[ 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002178532_java_python.txt
Q: Python: Why can't I iterate over a list? Is my exception class borked? I've already looked at this question: Python iterators – how to dynamically assign self.next within a new style class? but this doesn't help me because I want to iterate of an attribute of the error which is a list (ie, already iterable) withou...
Python: Why can't I iterate over a list? Is my exception class borked?
I've already looked at this question: Python iterators – how to dynamically assign self.next within a new style class? but this doesn't help me because I want to iterate of an attribute of the error which is a list (ie, already iterable) without having to use the attribute explicitly. I'm looking to do this: class SCE(...
[ "The __iter__ method should return an iterator object, but you are returning a list object. Use\ndef __iter__(self):\n return iter(self._values)\n\ninstead to fix this. From the documentation for object.__iter__ (my highlighting):\n\nThis method is called when an iterator is required for a container. This method...
[ 32, 8, 1 ]
[]
[]
[ "exception", "exception_handling", "iterator", "python" ]
stackoverflow_0002180578_exception_exception_handling_iterator_python.txt
Q: Python Dynamic module loading based on input I wrote a program that takes in a partial rss feed and outputs a full one, but it is one a case by case basis. The recipe for one site is not the same as the recipe for the other. So what I do is look at the domain basename(for instance nyt or wsj) and choose a module...
Python Dynamic module loading based on input
I wrote a program that takes in a partial rss feed and outputs a full one, but it is one a case by case basis. The recipe for one site is not the same as the recipe for the other. So what I do is look at the domain basename(for instance nyt or wsj) and choose a module based on that. Though I need to load each and ev...
[ "It sounds like you're looking for the __import__ function. This function does the same thing as the import statement, but allows you to pass a name to import that might only be known at runtime.\nSo you might do:\nparsemodule = __import__(feed)\nparsemodule.parser(posixpath.basename(url), urldir, rss_file_path, ur...
[ 3, 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0002180539_python_web_scraping.txt
Q: pygtk: find out focused element i'm creating a dialog that finds out what is focused element. that's what i wrote: import gtk import gobject class FocusedElementPath(gtk.Dialog): def __init__(self, parent, title=None): gtk.Dialog.__init__(self, title or 'Show path', parent) self.catch_withi...
pygtk: find out focused element
i'm creating a dialog that finds out what is focused element. that's what i wrote: import gtk import gobject class FocusedElementPath(gtk.Dialog): def __init__(self, parent, title=None): gtk.Dialog.__init__(self, title or 'Show path', parent) self.catch_within = parent self.catch_f...
[ "gtk.Window.get_focus (also available in gtk.Dialog) will return the currently focused child.\nAnyway I don't quite understand what you want to achieve here...\n" ]
[ 1 ]
[]
[]
[ "dialog", "focus", "gtk", "pygtk", "python" ]
stackoverflow_0002180614_dialog_focus_gtk_pygtk_python.txt
Q: Is it OK to raise a built-in exception, but with a different message, in Python? Is it OK to raise a built-in exception with a custom text? or to raise a built-in warning also with custom text? The documentation reads: exception ValueError: Raised when a built-in operation or function receives an argument (…) I...
Is it OK to raise a built-in exception, but with a different message, in Python?
Is it OK to raise a built-in exception with a custom text? or to raise a built-in warning also with custom text? The documentation reads: exception ValueError: Raised when a built-in operation or function receives an argument (…) Is it implied that only built-in operations should raise a ValueError exception? In pra...
[ "There's nothing operationally wrong with doing something like:\nraise ValueError(\"invalid input encoding\")\n\nIn fact, I do that quite often when I'm writing the first pass of some code. The main problem with doing it that way is that clients of your code have a hard time being precise in their exception handlin...
[ 29, 3, 3 ]
[]
[]
[ "built_in", "exception", "python", "raise" ]
stackoverflow_0002180577_built_in_exception_python_raise.txt
Q: How do I use this Python package? (guess_language) I am trying to use this package: http://pypi.python.org/pypi/guess-language/0.1 I've read the documentation/wiki, but can't find the solution. Basically, this package allows you to pass in a string, and it will return a "language". I'm able to make it print out "e...
How do I use this Python package? (guess_language)
I am trying to use this package: http://pypi.python.org/pypi/guess-language/0.1 I've read the documentation/wiki, but can't find the solution. Basically, this package allows you to pass in a string, and it will return a "language". I'm able to make it print out "en". htmlSource = download('http://feeds.feedburner.com/n...
[ "By modifying the source code of the module, from the sounds of this quote (taken from the answer you linked to):\n\nUpdate after some experimentation, including inserting a print statement to show what script blocks were detected with what percentages\n\n(Emphasis added by me.)\n" ]
[ 1 ]
[]
[]
[ "package", "python", "wiki" ]
stackoverflow_0002180864_package_python_wiki.txt
Q: Why do I get the u"xyz" format when I print a list of unicode strings in Python? Please observe the following behavior: a = u"foo" b = u"b\xe1r" # \xe1 is an 'a' with an accent s = [a, b] print a, b print s for x in s: print x, The result is: foo bár [u'foo', u'b\xe1r'] foo bár When I just print the two value...
Why do I get the u"xyz" format when I print a list of unicode strings in Python?
Please observe the following behavior: a = u"foo" b = u"b\xe1r" # \xe1 is an 'a' with an accent s = [a, b] print a, b print s for x in s: print x, The result is: foo bár [u'foo', u'b\xe1r'] foo bár When I just print the two values sitting in variables a and b, I get what I expect; when I put the string values in a...
[ "When you print a list, you get the repr() of each element, lists aren't really meant to be printed, so python tries to print something representative of it's structure.\nIf you want to format it in any particular way, either be explicit about how you want it formatted, or override it's __repr__ method.\n", "Obje...
[ 7, 1, 0 ]
[]
[]
[ "list", "python", "unicode" ]
stackoverflow_0002180929_list_python_unicode.txt
Q: Django generic views with multiple parameters Is it possible to use a generic view with additional parameters in the URL mapping - i.e. I got the following model: class Route(models.Model): area = models.ForeignKey(Area) slug = models.SlugField(null=True,blank=True) @models.permalink def get_absol...
Django generic views with multiple parameters
Is it possible to use a generic view with additional parameters in the URL mapping - i.e. I got the following model: class Route(models.Model): area = models.ForeignKey(Area) slug = models.SlugField(null=True,blank=True) @models.permalink def get_absolute_url(self): return ('route_details', (),...
[ "Sure, something like this:\nurl(r'^(?P<area>[-\\w]+)/(?P<slug>[-\\w]+)/$',\n 'django.views.generic.list_detail.object_detail',\n {'queryset': Route.objects.all()}\n name='route_details')\n\nShould just work.\nBe sure to either set template_object_name to \"route\" or use \"object\" in template.\n" ]
[ 0 ]
[]
[]
[ "django", "django_generic_views", "python" ]
stackoverflow_0002181002_django_django_generic_views_python.txt
Q: How to access url hash/fragment from a Django Request object As in the title: How can I access the URL hash/fragment (the part following the hash #, or 'pound symbol' in US English) from a Django view and so, I suppose, from a Django Request object? I've not found enough information on the documentation here avail...
How to access url hash/fragment from a Django Request object
As in the title: How can I access the URL hash/fragment (the part following the hash #, or 'pound symbol' in US English) from a Django view and so, I suppose, from a Django Request object? I've not found enough information on the documentation here available: http://docs.djangoproject.com/en/dev/ref/request-response/ P...
[ "This is not sent to the server, by definition. From URI References: Fragment Identifiers on URIs :\n\n\"The HTTP engine cannot make any assumptions about it. The server is not even given it.\"\n\n" ]
[ 42 ]
[]
[]
[ "django", "django_urls", "fragment_identifier", "hash", "python" ]
stackoverflow_0002181186_django_django_urls_fragment_identifier_hash_python.txt
Q: Deleting attributes when deleting instance class A: def __get(self): return self._x def __set(self, y): self._x = y def __delete_x(self): print('DELETING') del self._x x = property(__get,__set,__delete_x) b = A() # Here, when b is deleted, i'd like b.x to be deleted, i.e __delete_x() # call...
Deleting attributes when deleting instance
class A: def __get(self): return self._x def __set(self, y): self._x = y def __delete_x(self): print('DELETING') del self._x x = property(__get,__set,__delete_x) b = A() # Here, when b is deleted, i'd like b.x to be deleted, i.e __delete_x() # called (and for immediate consequence, "DELETING" pr...
[ "The semantics of the del statement don't really lend themselves to what you want here. del b simple removes the reference to the A object you just instantiated from the local scope frame / dictionary; this does not directly cause any operation to be performed on the object itself. If that was the last reference to...
[ 2, 1, 0 ]
[]
[]
[ "attributes", "class", "del", "instance", "python" ]
stackoverflow_0002181016_attributes_class_del_instance_python.txt
Q: HTML parser for GAE Generally I use lxml for my HTML parsing needs, but that isn't available on Google App Engine. The obvious alternative is BeautifulSoup, but I find it chokes too easily on malformed HTML. Currently I am testing libxml2dom and have been getting better results. Which pure Python HTML parser have...
HTML parser for GAE
Generally I use lxml for my HTML parsing needs, but that isn't available on Google App Engine. The obvious alternative is BeautifulSoup, but I find it chokes too easily on malformed HTML. Currently I am testing libxml2dom and have been getting better results. Which pure Python HTML parser have you found performs best?...
[ "From the BeautifulSoup documentation:\n\nVersion 3.1.0 of Beautiful Soup does significantly worse on real-world HTML than version 3.0.8 does\n\nSo, it might help you to use this earlier version. That is precisely what the author himself recommends.\n\nYou can pretend that Beautiful Soup version 3.1.0 was never rel...
[ 5, 5 ]
[]
[]
[ "google_app_engine", "html_parsing", "lxml", "python" ]
stackoverflow_0002161560_google_app_engine_html_parsing_lxml_python.txt
Q: How do I use a Python regex to match the function syntax of MATLAB? I am trying to find all the inputs/outputs of all MATLAB functions in our internal library. I am new (first time) to regex and have been trying to use the multiline mode in Python's re library. The MATLAB function syntax looks like: function outpu...
How do I use a Python regex to match the function syntax of MATLAB?
I am trying to find all the inputs/outputs of all MATLAB functions in our internal library. I am new (first time) to regex and have been trying to use the multiline mode in Python's re library. The MATLAB function syntax looks like: function output = func_name(input) where the signature can span multiple lines. I star...
[ "The peculiar (internal) error you're getting should come if you pass re.T instead of re.M as the second argument to re.compile (re.template -- a currently undocumented entry -- is the one intended to use it, and, in brief, template REs don't support repetition or backtracking). Can you print re.M to show what's i...
[ 5, 2, 0 ]
[]
[]
[ "matlab", "python", "regex" ]
stackoverflow_0002180784_matlab_python_regex.txt
Q: Sorting and grouping objects by Date with the Django ORM I have an Article model which has a date field. I want to query against all Article objects, and have a datatype returned with each distinct year, and then each distinct month within that. for instance archives = { 2009: {12, [, , ...], 11: [...]}, 20...
Sorting and grouping objects by Date with the Django ORM
I have an Article model which has a date field. I want to query against all Article objects, and have a datatype returned with each distinct year, and then each distinct month within that. for instance archives = { 2009: {12, [, , ...], 11: [...]}, 2008: {12, [...], 11: [...]}, } is this possible?
[ "This sort of question seems to come up fairly often. The easiest solution is to loop through the data and group the objects by year and month. You can do this by hand in the view or using regroup in your template. It really depends on what you want to do with the data. \nIf grouping Archives by year and month ...
[ 4, 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0002180847_django_django_orm_python.txt
Q: Using the Image.point() method in PIL to manipulate pixel data I am using the Python Imaging Library to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element list of RGB tuples: >>> len(colors) 256 >>> colors[0] (255, 237, 237) >>> colo...
Using the Image.point() method in PIL to manipulate pixel data
I am using the Python Imaging Library to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element list of RGB tuples: >>> len(colors) 256 >>> colors[0] (255, 237, 237) >>> colors[127] (50, 196, 33) >>> My first version used the getpixel() and...
[ "\nIs Image.point() the right tool for\n this job?\n\nYes indeed, Image.point() is perfect for this job\n\nWhat format/structure does\n Image.point() expect the table?\n\nYou should flatten the list so instead of [(12, 140, 10), (10, 100, 200), ...] use:\n[12, 140, 10, 10, 100, 200, ...]\n\nHere is a quick exampl...
[ 17, 3 ]
[]
[]
[ "image", "image_manipulation", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002181292_image_image_manipulation_image_processing_python_python_imaging_library.txt
Q: Multiprocessing and niceness value Does anyone know of an easy way to set the niceness value of a Process or Pool when it is created in multiprocessing? A: os.nice(increment) Add increment to the process’s “niceness”. Return the new niceness. Availability: Unix. From http://docs.python.org/library/os.html#os.ni...
Multiprocessing and niceness value
Does anyone know of an easy way to set the niceness value of a Process or Pool when it is created in multiprocessing?
[ "os.nice(increment)\nAdd increment to the process’s “niceness”. Return the new niceness. Availability: Unix.\n\nFrom http://docs.python.org/library/os.html#os.nice.\nIs there a reason you can't call this in the child process?\n", "Try importing the ctypes module and looking for pthread_schedparam() or SetThreadPr...
[ 14, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002181209_multiprocessing_python.txt
Q: Python method to boost function I have a method exported to Python using boost python that takes a boost::function as an argument. From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error Boost.Python.Argum...
Python method to boost function
I have a method exported to Python using boost python that takes a boost::function as an argument. From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error Boost.Python.ArgumentError: Python argument types in ...
[ "Got an answer on the python mailing list, and after a bit of reworking and more research I got exactly what I wanted :)\nI did see that post before mithrandi but I did not like the idea of having to declare the functions like that. With some fancy wrappers and a bit of python magic this can work and look good at ...
[ 12 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0002179345_boost_boost_python_c++_python.txt
Q: Scraping html with Python or One of the arguments I make to my (Microbiology and Genetics) students is that "data" is/are messy, and Python can help with that (of course other languages can too). So here is a practical kind of web-based data-gathering exercise. I notice that there a few people who answer Python-r...
Scraping html with Python or
One of the arguments I make to my (Microbiology and Genetics) students is that "data" is/are messy, and Python can help with that (of course other languages can too). So here is a practical kind of web-based data-gathering exercise. I notice that there a few people who answer Python-related questions among the users w...
[ "There's a perfectly usable monthly \"data dump\" of Stack Overflow under Creative Commons license, see for example here (just the first one \"under my thumb\" of the many links about this -- at least one per month). For such analysis as my average weekly rep relative to some other poster's, such monthly dollops o...
[ 3 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0002181708_python_screen_scraping.txt
Q: How do you make QT threads in python for pyqt? I see discussion about qt threads vs python threads but how do you create and call qt threads in python? how do you give it access to your functions in another thread? Thanks! A: There's a good, fully worked-out example here.
How do you make QT threads in python for pyqt?
I see discussion about qt threads vs python threads but how do you create and call qt threads in python? how do you give it access to your functions in another thread? Thanks!
[ "There's a good, fully worked-out example here.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "pyqt", "python" ]
stackoverflow_0002181724_multithreading_pyqt_python.txt
Q: Parsing Python Response using httplib After connecting to a socket and capturing the response using .read() how do I parse the input stream and read lines? I see the data is returned without any CRLF <html><head><title>Apache Tomcat/6.0.16 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;co...
Parsing Python Response using httplib
After connecting to a socket and capturing the response using .read() how do I parse the input stream and read lines? I see the data is returned without any CRLF <html><head><title>Apache Tomcat/6.0.16 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-siz...
[ "You have to parse the HTML. Python has several ways of parsing HTML - one of them the built-in HTMLParser module. Another, and probably better way, is the 3rd party BeautifulSoup module.\nMany other issues dealing with HTML processing are explained in this nice article. You can also read the relevant chapter of th...
[ 3, 0 ]
[]
[]
[ "httplib", "python", "urllib" ]
stackoverflow_0002181817_httplib_python_urllib.txt
Q: Python Iteration Problem! I have this code here, it is supposed to remove the common letters from both the lists n1 and n2. But when i run this code it only runs once as in it removes only 'a' from both n1 and n2 and doesnt remove 'k'. Just to clarify this code should always work on only 2 words. name1 = "abdjek" ...
Python Iteration Problem!
I have this code here, it is supposed to remove the common letters from both the lists n1 and n2. But when i run this code it only runs once as in it removes only 'a' from both n1 and n2 and doesnt remove 'k'. Just to clarify this code should always work on only 2 words. name1 = "abdjek" name2 = "doarhsnk" n1l = list(...
[ "I suggest a much simpler approach:\ndef removecommon(name1, name2):\n common = set(name1).intersection(name2)\n res1 = ''.join(n for n in name1 if n not in common)\n res2 = ''.join(n for n in name2 if n not in common)\n return res1, res2\n\nn1, n2 = removecommon('naveen', 'darshana')\nprint n1, n2\n\nemits vee...
[ 5, 2, 0, 0, 0, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002173238_iteration_python.txt
Q: what is 'comments' mean in this code {% load comments %} where defined 'comments' ,a viewer? or a template?? thanks A: It is a template tag library. For example: {% load cache %} loads the caching tags. Custom tags can be defined and placed within your project structure as defined here. A: It's a template ...
what is 'comments' mean in this code
{% load comments %} where defined 'comments' ,a viewer? or a template?? thanks
[ "It is a template tag library. For example:\n{% load cache %}\n\nloads the caching tags.\nCustom tags can be defined and placed within your project structure as defined here.\n", "It's a template tag that loads a specific set of other template tags (comments application specific tags in this case) making them av...
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002181460_django_python.txt
Q: QT4, GTK+, wxWidgets or IronPython for a native Windows app using Python I need to build a native windows app using Python (and py2exe, I guess). Feature requirements are: Taskbar icon Alert notifications (next to Taskbar Icon) Chromeless window (ideally a pretty, rounded, coloured one). Webkit to render some of ...
QT4, GTK+, wxWidgets or IronPython for a native Windows app using Python
I need to build a native windows app using Python (and py2exe, I guess). Feature requirements are: Taskbar icon Alert notifications (next to Taskbar Icon) Chromeless window (ideally a pretty, rounded, coloured one). Webkit to render some of the Chromeless window So far I've identified the following possible toolkits:...
[ "Qt has a clean and consistent API, complete widgets set, excellent documentation and tools and Webkit integration is built in.\nIn my opinion none of the other libraries you cite offer all of these, so my advice would be to use PyQt4 if you can live with its licensing scheme.\n", "I've been using wxPython for so...
[ 4, 1 ]
[]
[]
[ "ironpython", "pygtk", "pyqt4", "python", "wxwidgets" ]
stackoverflow_0002181948_ironpython_pygtk_pyqt4_python_wxwidgets.txt
Q: Determining the frequency of Twitter tweets on a certain topic Is there a way for me to determine the total number of Twitter messages on a given trend topic (e.g. frequency of Twitter messages with subject matter on Haiti/#Haiti) at a given instance in time using the Twitter API? I'm writing a script in Python th...
Determining the frequency of Twitter tweets on a certain topic
Is there a way for me to determine the total number of Twitter messages on a given trend topic (e.g. frequency of Twitter messages with subject matter on Haiti/#Haiti) at a given instance in time using the Twitter API? I'm writing a script in Python that will monitor Twitter traffic over a long spell of time and I was ...
[ "Yes. Use the Twitter Streaming API to get a representative sample.\n", "You might take a look at this site (see below) Drew has several sources of information and was to look at the data. \nNetwork of People who Twitter about R \nhttp://www.drewconway.com/zia/?p=1471\n" ]
[ 1, 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0002181230_python_twitter.txt
Q: python sqlite check points? I working with python sqlite3 , I found we have commit and rollback option. Does sqlite3 allows something like check point ? For example: Initial state is empty. ... insert something ... commit .... ..... insert something commit. update something Found some problem.Now I want to roll...
python sqlite check points?
I working with python sqlite3 , I found we have commit and rollback option. Does sqlite3 allows something like check point ? For example: Initial state is empty. ... insert something ... commit .... ..... insert something commit. update something Found some problem.Now I want to roll back to initial state. Something...
[ "No, I don't know of any SQL database engine supporting \"multiple undo\" -- if one exists at all, Sqlite is definitely not it! For nested transactions (a less general concept), consider (per Sqlite's docs!) the SAVEPOINT feature -- it may be sufficient to do most of what you require.\n" ]
[ 2 ]
[]
[]
[ "python", "rollback", "sqlite" ]
stackoverflow_0002182062_python_rollback_sqlite.txt
Q: Django templates condition check All, Can t we do the following in templates {% if subject.id == selected_id %} and also cannot we assign variable like {{selected="selected"}} Thank........ A: This comparison will work in Django 1.2. For 1.1 you have to use ifequal: {% ifequal subject.id selected_id %} For var...
Django templates condition check
All, Can t we do the following in templates {% if subject.id == selected_id %} and also cannot we assign variable like {{selected="selected"}} Thank........
[ "This comparison will work in Django 1.2. For 1.1 you have to use ifequal:\n{% ifequal subject.id selected_id %}\n\nFor variable assignment you can use with.\n{% with selected as 'selected' %}\n\n{% endwith %}\n\nDon't hesitate to read the documentation, it doesn't hurt.\n", "Not as shown. Use the ifequal and wi...
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002182512_django_python.txt
Q: python style question around reading small files What is the most pythonic way to read in a named file, strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines? Assume it all fits easily in memory. Note: it's not tough to do this -- what I'm asking ...
python style question around reading small files
What is the most pythonic way to read in a named file, strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines? Assume it all fits easily in memory. Note: it's not tough to do this -- what I'm asking is for the most pythonic way. I've been writing a lot...
[ "Generators are perfect for tasks like this. They are readable, maintain perfect separation of concerns, and efficient in memory-use and time.\ndef RemoveComments(lines):\n for line in lines:\n if not line.strip().startswith('#'):\n yield line\n\ndef RemoveBlankLines(lines):\n for line in li...
[ 5, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "coding_style", "idioms", "python" ]
stackoverflow_0002182082_coding_style_idioms_python.txt
Q: Python: How do I access an decorated class's instance from inside a class decorator? Here's an example of what I mean: class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method's parent class's instance? # In the below example, I wo...
Python: How do I access an decorated class's instance from inside a class decorator?
Here's an example of what I mean: class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method's parent class's instance? # In the below example, I would want to access from here: myinstance def wrapper(*args, **kwargs): ...
[ "class MyDecorator(object):\n def __call__(self, func):\n def wrapper(that, *args, **kwargs):\n ## you can access the \"self\" of func here through the \"that\" parameter\n ## and hence do whatever you want \n return func(that, *args, **kwargs)\n return wrapper\n\n", "Plea...
[ 8, 2, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002181275_decorator_python.txt
Q: python sqlite 3 : roll back to save point fails def rollback_savepoint(self): try: self.db.execute("rollback to savepoint pt;") except: print "roll back to save point failed" else: print "Roll back to save point. Done" In above code snippet , It says "roll back to save point fa...
python sqlite 3 : roll back to save point fails
def rollback_savepoint(self): try: self.db.execute("rollback to savepoint pt;") except: print "roll back to save point failed" else: print "Roll back to save point. Done" In above code snippet , It says "roll back to save point failed". What went wrong? EDIT: I changed the code as s...
[ "Don't ever catch exceptions you aren't handling. Let it raise, so you can have useful error messages and tracebacks.\nExample:\n>>> c.execute('rollback to savepoint pt;')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nsqlite3.OperationalError: no such savepoint: pt\n\nFrom the traceb...
[ 4 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002182591_python_sqlite.txt
Q: Django template-printing variables All, In Template condition check,whats wrong with the following code, selected_id and selected_sub are equal to 5 but still ifequal loop is not working.. <tr><td><p>Subjects:</td> <td> <select id="subjects" name="subjects" multiple="multiple"> {% for subject in subjects %} <optio...
Django template-printing variables
All, In Template condition check,whats wrong with the following code, selected_id and selected_sub are equal to 5 but still ifequal loop is not working.. <tr><td><p>Subjects:</td> <td> <select id="subjects" name="subjects" multiple="multiple"> {% for subject in subjects %} <option value="{{subject.id}}" {% for selected...
[ "Ok, sorry. What is the output you get?\nselected should have the value 'selected=\"selected\"'.\nChange to {% with selected as 'selected=\"selected\"' %} and try again.\n", "If, as you say, selected_id and selected_sub are equal to 5 then\nfor selected_id in selected_sub\n\nwill not work, since 5 is not iterable...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002182977_django_python.txt
Q: How can I pack several decorators into one? I have several decorators on each function, is there a way to pack them in to one instead? @fun1 @fun2 @fun3 def do_stuf(): pass change to: @all_funs #runs fun1 fun2 and fun3, how should all_funs look like? def do_stuf(): pass A: A decorator is in principl...
How can I pack several decorators into one?
I have several decorators on each function, is there a way to pack them in to one instead? @fun1 @fun2 @fun3 def do_stuf(): pass change to: @all_funs #runs fun1 fun2 and fun3, how should all_funs look like? def do_stuf(): pass
[ "A decorator is in principle only syntactic sugar for this:\ndef do_stuf():\n pass\n\ndo_stuf = fun1(do_stuf)\n\nSo in your all_fun, all you should need to do is to wrap the function in the same kind of chain of decorators:\ndef all_funs(funky):\n return fun1(fun2(fun3(fun4(funky)))\n\nThings get a little bit...
[ 10, 7, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002182858_decorator_python.txt
Q: importing a module in nested packages This is a python newbie question: I have the following directory structure: test -- test_file.py a -- b -- module.py where test, a and b are folders. Both test and a are on the same level. module.py has a class called shape, and I want to instantiate an instance of ...
importing a module in nested packages
This is a python newbie question: I have the following directory structure: test -- test_file.py a -- b -- module.py where test, a and b are folders. Both test and a are on the same level. module.py has a class called shape, and I want to instantiate an instance of it in test_file.py. How can I do so? I have...
[ "What you want is a relative import like:\nfrom ..a.b import module\nThe problem with this is that it doesn't work if you are calling test_file.py as your main module. As stated here:\n\nNote that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main mod...
[ 34, 21, 14 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0002183205_import_package_python.txt
Q: python regular expression to validate types of strings I want to do the following with python: Validate if a UTF8 string is an integer. Validate if a UTF8 string is a float. Validate if a UTF8 string is of length(1-255). Validate if a UTF8 string is a valid date. I'm totally new to python and I believe this shou...
python regular expression to validate types of strings
I want to do the following with python: Validate if a UTF8 string is an integer. Validate if a UTF8 string is a float. Validate if a UTF8 string is of length(1-255). Validate if a UTF8 string is a valid date. I'm totally new to python and I believe this should be done with regular expression, except maybe for the las...
[ "Regex is not a good solution here.\n\nValidate if a UTF8 string is an integer:\ntry:\n int(val)\n is_int = True\nexcept ValueError:\n is_int = False\n\nValidate if a UTF8 string is a float: same as above, but with float().\nValidate if a UTF8 string is of length(1-255):\nis_of_appropriate_length = 1 <= len(val)...
[ 6, 2, 1 ]
[]
[]
[ "python", "regex", "validation" ]
stackoverflow_0002183786_python_regex_validation.txt
Q: Basic google app engine (python) templating issue after going through some basic tutorials on the app engine and the webapp framework, I'm attempting to display documents that are related to a project construct I've created (e.g {% ifequal project.key doc.parentproject %} ) I have created several documents that do...
Basic google app engine (python) templating issue
after going through some basic tutorials on the app engine and the webapp framework, I'm attempting to display documents that are related to a project construct I've created (e.g {% ifequal project.key doc.parentproject %} ) I have created several documents that do indeed have a doc.parentproject identical to keys from...
[ "Without seeing the controller code that provides the values to this template, it is difficult to really diagnose the problem that you are having, but I would guess that the docs variable isn't getting the list of doc entities that it clearly expects.\nFrom a good design standpoint, I would suggest giving the Proj...
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002179481_django_google_app_engine_python.txt
Q: Populate ChoiceField from database I'd like to have several fields in my form being rendered as ChoiceFields which get their content from the database. I was thinking something like: class SeriesForm(ModelForm): series = forms.ChoiceField(choices=Series.objects.all()) class Meta: model = Series exclud...
Populate ChoiceField from database
I'd like to have several fields in my form being rendered as ChoiceFields which get their content from the database. I was thinking something like: class SeriesForm(ModelForm): series = forms.ChoiceField(choices=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) But the fi...
[ "Use a ModelChoiceField instead.\n" ]
[ 6 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002184108_django_django_forms_python.txt
Q: Telnet automation / scripting I have already checked this question but could not find what I'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server. Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and pre...
Telnet automation / scripting
I have already checked this question but could not find what I'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server. Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then r...
[ "There's a python library for telnet connections that reads and writes from/to a telnet connection.\nCheck the link. It has some basic examples of what you are looking for.\nHere's an example from the link:\nimport getpass\nimport sys\nimport telnetlib\n\nHOST = \"localhost\"\nuser = raw_input(\"Enter your remote a...
[ 21, 3, 1 ]
[]
[]
[ "automation", "python", "scripting", "telnet", "windows" ]
stackoverflow_0001491494_automation_python_scripting_telnet_windows.txt
Q: Finding the length of a cubic B-spline Using scipy's interpolate.splprep function get a parametric spline on parameter u, but the domain of u is not the line integral of the spline, it is a piecewise linear connection of the input coordinates. I've tried integrate.splint, but that just gives the individual integr...
Finding the length of a cubic B-spline
Using scipy's interpolate.splprep function get a parametric spline on parameter u, but the domain of u is not the line integral of the spline, it is a piecewise linear connection of the input coordinates. I've tried integrate.splint, but that just gives the individual integrals over u. Obviously, I can numerically in...
[ "Because both x & y are cubic parametric functions, there isn't a closed solution in terms of simple functions. Numerical integration is the way to go. Either integrating the arc length expression or simply adding line segment lengths - depends on the accuracy you are after and how much effort you want to exert.\nA...
[ 6, 4 ]
[]
[]
[ "interpolation", "python", "scipy" ]
stackoverflow_0002181349_interpolation_python_scipy.txt
Q: Python Leave Loop Early How do I leave a loop early in python? for a in b: if criteria in list1: print "oh no" #Force loop i.e. force next iteration without going on someList.append(a) Also, in java you can break out of a loop, is there an equivalent in Python? A: continue and break is w...
Python Leave Loop Early
How do I leave a loop early in python? for a in b: if criteria in list1: print "oh no" #Force loop i.e. force next iteration without going on someList.append(a) Also, in java you can break out of a loop, is there an equivalent in Python?
[ "continue and break is what you want. Python works identically to Java/C++ in this regard.\n", "Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like:\nsomelist = [a for a in b if not a.criteria in otherlist]\n\nIf you want to leave a...
[ 57, 24, 5, 2 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0002184287_loops_python.txt
Q: PyQt post installation question I successfully installed PyQt in both mac and PC. To do so I had to install mingw (on PC), Xcode (on MAC) and Qt4.6 library. Now that I have PyQt working perfectly, I would like to uninstall mingw, Xcode and Qt Library from both mac and PC. I know I can remove Xcode and mingw, but ...
PyQt post installation question
I successfully installed PyQt in both mac and PC. To do so I had to install mingw (on PC), Xcode (on MAC) and Qt4.6 library. Now that I have PyQt working perfectly, I would like to uninstall mingw, Xcode and Qt Library from both mac and PC. I know I can remove Xcode and mingw, but what care should I take before removi...
[ "You can remove the demos and examples directories inside your qt installation directory... they take up over 1GB of space and are not required. I would leave the rest there, unless you are really worried about space.\nIf you do try to clean up the QT installation directory, start by renaming larger files/directori...
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002106178_pyqt4_python.txt
Q: Making Python Interactive Mode of Emacs Highlight and Indent I am using Emacs 23 with python-mode 5.1.0 to edit my python programs. Sometimes when writing a program I want to run a small throwaway python script and so I run the interactive move (C-c !). This is fine, but it neither indents nor highlights the code,...
Making Python Interactive Mode of Emacs Highlight and Indent
I am using Emacs 23 with python-mode 5.1.0 to edit my python programs. Sometimes when writing a program I want to run a small throwaway python script and so I run the interactive move (C-c !). This is fine, but it neither indents nor highlights the code, and if I try running python mode while in it, it no longer evalua...
[ "Adding these to my .emacs seems to have done it.\nThe bit where it checks the buffer name in the advice would probably be better as a test on a buffer-local variable set by set-pycomint-keywords, but you get the idea.\n(defun set-pycomint-keywords ()\n (setq font-lock-keywords python-font-lock-keywords))\n\n...
[ 3 ]
[ "I don't have time to try it now, but i found you can replace python shell when you press C-c\nwith this that should be more powerful:\nhttp://ipython.scipy.org/moin/\nWhen i'll have time I'll give it a try\n" ]
[ -1 ]
[ "emacs", "python" ]
stackoverflow_0002063343_emacs_python.txt
Q: EventHandler, event, delegate based programming in Python any example would appreciate? Basically I'm a C# developer, I know the way C# does, EventHandler, delegate, even... but whats the best way to implement it on Python. A: I think you should be able to use a function: def do_work_and_notify(on_done): // ...
EventHandler, event, delegate based programming in Python any example would appreciate?
Basically I'm a C# developer, I know the way C# does, EventHandler, delegate, even... but whats the best way to implement it on Python.
[ "I think you should be able to use a function:\ndef do_work_and_notify(on_done):\n // do work\n on_done()\n\ndef send_email_on_completion():\n email_send('joe@example.com', 'you are done')\n\ndo_work_and_notify(send_email_on_completion)\n\nFunctions (and even methods) in python are first-class objects that...
[ 21, 2 ]
[]
[]
[ "delegates", "event_handling", "events", "function_pointers", "python" ]
stackoverflow_0002184263_delegates_event_handling_events_function_pointers_python.txt
Q: Python thinks a 3000-line text file is one line long? I have a very long text file that I'm trying to process using Python. However, the following code: for line in open('textbase.txt', 'r'): print 'hello world' produces only the following output: hello world It's as though Python thinks the file is only one...
Python thinks a 3000-line text file is one line long?
I have a very long text file that I'm trying to process using Python. However, the following code: for line in open('textbase.txt', 'r'): print 'hello world' produces only the following output: hello world It's as though Python thinks the file is only one line long, though it is many thousands of lines long, when...
[ "According to the documentation for open(), you should add a U to the mode:\nopen('textbase.txt', 'Ur')\n\nThis enables \"universal newlines\", which normalizes them to \\n in the strings it gives you.\nHowever, the correct thing to do is to decode the UTF-16BE into Unicode objects first, before translating the new...
[ 25, 6, 1 ]
[ "open() returns a file object. You need to use:\nfor line in open('textbase.txt', 'r').readlines():\n print line\n\n" ]
[ -1 ]
[ "character_encoding", "newline", "python", "text" ]
stackoverflow_0002184543_character_encoding_newline_python_text.txt
Q: Python database access using single file/already build file I have to save some data into MySQL from Python. I have tried MySQLdb, but it needs to be built. Build fails on my Mac; moreover, I need to have one file to copy to server. I don't have access to install anything. Can you recommend me any solution, please...
Python database access using single file/already build file
I have to save some data into MySQL from Python. I have tried MySQLdb, but it needs to be built. Build fails on my Mac; moreover, I need to have one file to copy to server. I don't have access to install anything. Can you recommend me any solution, please! Even where I can find MySQLdb build for specific platforms. Tha...
[ "MySQL has a command line interface (similar to psql from Postgres or sqlite3 from the database of the same name). I would be surprised if this wasn't installed on the same server already.\nYou could then generate input for that utility using Python and call it with subprocess. Depending on the data, this can be ...
[ 2, 1 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0002184156_database_mysql_python.txt
Q: Setting the RGB levels of pixels (Python, Jython) For each pixel in pic: r= random() if r < 0.25: set the red level to randrange(0,256), set the green level to randrange(0,256) set the blue level to randrange(0,256) The rest of the unseen code is correct, I just can't figure ...
Setting the RGB levels of pixels (Python, Jython)
For each pixel in pic: r= random() if r < 0.25: set the red level to randrange(0,256), set the green level to randrange(0,256) set the blue level to randrange(0,256) The rest of the unseen code is correct, I just can't figure out how to phrase this function well enough for it to w...
[ "I don't know anything about the rest of your code, but it would be something like this:\nimport random\n\nfor pixel in pic.get_pixels(): # Replace with appropiate way of getting the pixels\n if random.random() < 0.25:\n pixel.red = random.randint(256)\n pixel.green = random.randint(256)\n p...
[ 1, 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0002158228_jython_python.txt
Q: How to pass data to another function from a class (in HTMLParser)? I'm beginning to learn python. My python version is 3.1 I've never learnt OOP before, so I'm confused by the HTMLParser. from html.parser import HTMLParser class parser(HTMLParser): def handle_data(self, data): print(data) p = parser...
How to pass data to another function from a class (in HTMLParser)?
I'm beginning to learn python. My python version is 3.1 I've never learnt OOP before, so I'm confused by the HTMLParser. from html.parser import HTMLParser class parser(HTMLParser): def handle_data(self, data): print(data) p = parser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.fee...
[ "I did not look into the HTMLParser module itself, but I can see that feed inherently calls handle_data, which in your derived class does a print. @ron's answer suggests passing the data directly to your function, which is totally OK. However, since you are new to OOP, maybe take a look at this code.\nThis is Pyt...
[ 6, 2 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0002185020_class_function_python.txt
Q: Python / Regex: exclude everything except one thing Suppose I have these strings: a = "hello" b = "-hello" c = "-" d = "hell-o" e = " - " How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise? Let's say we put these strings into a l...
Python / Regex: exclude everything except one thing
Suppose I have these strings: a = "hello" b = "-hello" c = "-" d = "hell-o" e = " - " How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise? Let's say we put these strings into a list, looped through and all I wanted to extract was C. Ho...
[ "If you want to match only variable c:\nif '-' == something:\n print 'hurray!'\n\nTo answer the updates: yes, that would be too messy. You don't need regex there. Simple string methods are faster:\n>>> lst =[\"hello\", \"-hello\", \"-\", \"hell-o\",\" - \"]\n>>> for i, item in enumerate(lst):\n if item == '...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002185229_python_regex.txt
Q: How do I detect a lost client connection in a server that inherits from pb.Root? For example, I have a client that connects to the server with the following: class MyClientFactory(pb.PBClientFactory, ReconnectingClientFactory): def __init__(self): pb.PBClientFactory.__init__(self) self.ipaddres...
How do I detect a lost client connection in a server that inherits from pb.Root?
For example, I have a client that connects to the server with the following: class MyClientFactory(pb.PBClientFactory, ReconnectingClientFactory): def __init__(self): pb.PBClientFactory.__init__(self) self.ipaddress = None def clientConnectionMade(self, broker): log.msg('Started to conn...
[ "You can register a callback to be invoked when the connection is lost. There are two APIs for this, one is Broker.notifyOnDisconnect, the other is RemoteReference.notifyOnDisconnect. They do the same thing, but one or the other might be more convenient to access depending on the details of your application.\nI'm...
[ 4 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002184682_python_twisted.txt
Q: How to get the most represented object from an array I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple] What is the most efficient way to get the most represented object from this array? In this case it would be...
How to get the most represented object from an array
I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple] What is the most efficient way to get the most represented object from this array? In this case it would be "apple" but how would you go out and calculate that in an...
[ "Don't reinvent the wheel. In Python 2.7+ you can use the Counter class:\nimport collections\nfruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']\nc=collections.Counter(fruit)\nprint(c.most_common(1))\n# [('apple', 4)]\n\nIf you are using an older version of Python, then you can downl...
[ 8, 5, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "arrays", "list", "performance", "python" ]
stackoverflow_0002184336_algorithm_arrays_list_performance_python.txt