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: How can I design a dict like sqlite class in python which can using different field as "key"? I have a such a data structure, "ID NAME BIRTH AGE SEX" ================================= 1 Joe 01011980 30 M 2 Rose 12111986 24 F 3 Tom 31121965 35 M 4 Joe 15091990 20 M ...
How can I design a dict like sqlite class in python which can using different field as "key"?
I have a such a data structure, "ID NAME BIRTH AGE SEX" ================================= 1 Joe 01011980 30 M 2 Rose 12111986 24 F 3 Tom 31121965 35 M 4 Joe 15091990 20 M I want to use python + sqlite to store and query data in a easy way. I am in trying to design a d...
[ "sqlite is a SQL database and works by far best when used as such (wrapped in SQLAlchemy or whatever if you really insist;-).\nSyntax such as d[key=\"NAME\", 'Joe'] is simply illegal Python, no matter how much wrapping and huffing and puffing you may do. A simple class wrapper around the DB connection is easy, but...
[ 3 ]
[]
[]
[ "dictionary", "key", "python", "sqlite" ]
stackoverflow_0003464787_dictionary_key_python_sqlite.txt
Q: question about python names using a default parameter value I was reading this today: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values and I can't seem to understand what's happening under the hood. def bad_append(new_item, a_list=[]): a_list.append(new_item) r...
question about python names using a default parameter value
I was reading this today: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values and I can't seem to understand what's happening under the hood. def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list The problem here is that the default value of a_...
[ "\nwhen is the function definition stage?\n\nLook at \"Function definitions\" in the Python reference:\n\nDefault parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used f...
[ 3 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0003465017_python_variables.txt
Q: ISDN dial up connection with python I have a requirement to create a Python application that accepts dial up connections over ISDN from client software and relays messages from this connection to a website application running on a LAMP webserver. Do we have some modules or support for this kind of implementation i...
ISDN dial up connection with python
I have a requirement to create a Python application that accepts dial up connections over ISDN from client software and relays messages from this connection to a website application running on a LAMP webserver. Do we have some modules or support for this kind of implementation in python? Please suggest. Thanks in advan...
[ "You should have system hardware and software that handles establishing ISDN links, that's not something you should be trying to reimplement yourself.\nYou need to consult the documentation for that hardware and software, and the documentation for the client software, to determine how that connection can be made av...
[ 1 ]
[]
[]
[ "dial_up", "isdn", "python" ]
stackoverflow_0003464996_dial_up_isdn_python.txt
Q: Getting HTTP GET variables using Tipfy I'm currently playing around with tipfy on Google's Appengine and just recently ran into a problem: I can't for the life of me find any documentation on how to use GET variables in my application, I've tried sifting through both tipfy and Werkzeug's documentations with no suc...
Getting HTTP GET variables using Tipfy
I'm currently playing around with tipfy on Google's Appengine and just recently ran into a problem: I can't for the life of me find any documentation on how to use GET variables in my application, I've tried sifting through both tipfy and Werkzeug's documentations with no success. I know that I can use request.form.get...
[ "request.args.get('variable') should work for what I think you mean by \"GET data\".\n", "Source: http://www.tipfy.org/wiki/guide/request/\nThe Request object contains all the information transmitted by the client of the application. You will retrieve from it GET and POST values, uploaded files, cookies and heade...
[ 3, 2, 0 ]
[]
[]
[ "google_app_engine", "mod_wsgi", "python", "tipfy", "werkzeug" ]
stackoverflow_0002569895_google_app_engine_mod_wsgi_python_tipfy_werkzeug.txt
Q: simplest way to return a new list by remove index/value from another list? (order required) All, o1 = ["a","b","c","d","e","f","g","h"] index = [3,4] value = ["c","d"] [x for x in o1 if x not in value] [x for x in o1 if x not in [o1[y] for y in index]] any simpler solution for above lc? Thanks A: (x for x in...
simplest way to return a new list by remove index/value from another list? (order required)
All, o1 = ["a","b","c","d","e","f","g","h"] index = [3,4] value = ["c","d"] [x for x in o1 if x not in value] [x for x in o1 if x not in [o1[y] for y in index]] any simpler solution for above lc? Thanks
[ "(x for x in o1 if x not in value)\n(x for i, x in enumerate( o1 ) if i not in index )\n\nNote that using generator expressions will save you a pass through the list, and using sets instead of lists for index and value will be more efficient.\n" ]
[ 2 ]
[]
[]
[ "indexing", "list", "python" ]
stackoverflow_0003465417_indexing_list_python.txt
Q: How to efficiently merge multiple list of different length into a tree dictonary in python given [ ('object-top-1','object-lvl1-1','object-lvl2-1'), ('object-top-2','object-lvl1-1','object-lvl2-2','object-lvl3-1') ('object-top-1','object-lvl1-1','object-lvl2-3'), ('object-top-2','object-lvl1-2','object-lv...
How to efficiently merge multiple list of different length into a tree dictonary in python
given [ ('object-top-1','object-lvl1-1','object-lvl2-1'), ('object-top-2','object-lvl1-1','object-lvl2-2','object-lvl3-1') ('object-top-1','object-lvl1-1','object-lvl2-3'), ('object-top-2','object-lvl1-2','object-lvl2-4','object-lvl3-2','object-lvl4-1'), ] and so on .. where all the tuples are of arbitrary le...
[ "def treeify(seq):\n ret = {}\n for path in seq:\n cur = ret\n for node in path:\n cur = cur.setdefault(node, {})\n return ret\n\nExample:\n>>> pprint.pprint(treeify(L))\n{'object-top-1': {'object-lvl1-1': {'object-lvl2-1': {}, 'object-lvl2-3': {}}},\n 'object-top-2': {'object-lvl1...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003464975_python.txt
Q: How to iterate a dict of dynamic "depths" in python? I have a dict data structure with various "depths". By "depths" I mean for example: When depth is 1, dict will be like: {'str_key1':int_value1, 'str_key2:int_value2} When depth is 2, dict will be like: {'str_key1': {'str_key1_1':int_value1_1, 'str_k...
How to iterate a dict of dynamic "depths" in python?
I have a dict data structure with various "depths". By "depths" I mean for example: When depth is 1, dict will be like: {'str_key1':int_value1, 'str_key2:int_value2} When depth is 2, dict will be like: {'str_key1': {'str_key1_1':int_value1_1, 'str_key1_2':int_value1_2}, 'str_key2': {'str_key2_1':int_v...
[ "I'm not sure why everybody's thinking in terms of recursion (or recursion elimination) -- I'd just do depth steps, each of which rebuilds a list by expanding it one further level down.\nE.g.:\ndef itr(depth, d):\n cp = [([], d)]\n for _ in range(depth):\n cp = [(lk+[k], v) for lk, d in cp for k, v in d.items(...
[ 5, 3, 2, 2, 1 ]
[]
[]
[ "algorithm", "dictionary", "iteration", "python" ]
stackoverflow_0003464490_algorithm_dictionary_iteration_python.txt
Q: Python urllib2 URLError HTTP status code. I want to grab the HTTP status code once it raises a URLError exception: I tried this but didn't help: except URLError, e: logger.warning( 'It seems like the server is down. Code:' + str(e.code) ) A: You shouldn't check for a status code after catching URLError, sin...
Python urllib2 URLError HTTP status code.
I want to grab the HTTP status code once it raises a URLError exception: I tried this but didn't help: except URLError, e: logger.warning( 'It seems like the server is down. Code:' + str(e.code) )
[ "You shouldn't check for a status code after catching URLError, since that exception can be raised in situations where there's no HTTP status code available, for example when you're getting connection refused errors.\nUse HTTPError to check for HTTP specific errors, and then use URLError to check for other problems...
[ 65, 2 ]
[]
[]
[ "exception", "python", "urllib2" ]
stackoverflow_0003465704_exception_python_urllib2.txt
Q: Testing Python console programs with Unicode strings in NetBeans 6.9 I try to run the following simple code in NetBeans 6.9 s = u"\u00B0 Celsius" print u"{0}".format(s) But I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 0: ordinal not in range(128) A: Net...
Testing Python console programs with Unicode strings in NetBeans 6.9
I try to run the following simple code in NetBeans 6.9 s = u"\u00B0 Celsius" print u"{0}".format(s) But I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 0: ordinal not in range(128)
[ "NetBeans's console apparently isn't properly set up to handle printing non-ASCII unicode strings.\nIn general, you should avoid printing unicode strings without explicitly encoding them (e.g. u_str.encode(some_codec) first.\nIn your specific case, you can probably just get away with:\nprint u'{0}'.format(s).encode...
[ 4, 0 ]
[]
[]
[ "netbeans", "python", "unicode" ]
stackoverflow_0003465944_netbeans_python_unicode.txt
Q: Using recursion in Python class methods NB Noob alert ... ! I am trying to use recursion in a Python class method, but with limited results. I'm trying to build a car class, with very basic attributes: id, position in a one lane road (represented by an integer), and velocity. One of the functions I have is used t...
Using recursion in Python class methods
NB Noob alert ... ! I am trying to use recursion in a Python class method, but with limited results. I'm trying to build a car class, with very basic attributes: id, position in a one lane road (represented by an integer), and velocity. One of the functions I have is used to return which car id is in front on this one...
[ "What you're calling a class method is actually an instance method. Class methods operate on the class, and instance methods operate on the instance. Here, we're dealing with Car instances, not the Car class itself.\nclass Car(object):\n def __init__(self, position, id, velocity):\n self.position = positi...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003466143_python.txt
Q: Spawning more than one thread in Python causes RuntimeError I'm trying to add multithreading to a Python app, and thus started with some toy examples : import threading def myfunc(arg1, arg2): print 'In thread' print 'args are', arg1, arg2 thread = threading.Thread(target=myfunc, args=('asdf', 'jkle'))...
Spawning more than one thread in Python causes RuntimeError
I'm trying to add multithreading to a Python app, and thus started with some toy examples : import threading def myfunc(arg1, arg2): print 'In thread' print 'args are', arg1, arg2 thread = threading.Thread(target=myfunc, args=('asdf', 'jkle')) thread.start() thread.join() This works beautifully, but as so...
[ "thread2 = threading.Thread(target=myfunc, args=('1234', '3763763é'))\n\nAre you declaring the file as UTF-8?-----------------------------------------------------^\n", "Can you post the exact error you get?\nRuns fine for me (after replacing the é character with an e):\nIn thread\nargs areIn thread\nasdfargs are ...
[ 1, 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "runtime_error" ]
stackoverflow_0001595772_multithreading_python_runtime_error.txt
Q: What's the best layout for a python command line application? What is the right way (or I'll settle for a good way) to lay out a command line python application of moderate complexity? I've created a python project skeleton using paster, which gave me a few files to start with: myproj/__init__.py MyProj.egg-info/...
What's the best layout for a python command line application?
What is the right way (or I'll settle for a good way) to lay out a command line python application of moderate complexity? I've created a python project skeleton using paster, which gave me a few files to start with: myproj/__init__.py MyProj.egg-info/ dependency_links.txt entry_points.txt PKG-INFO SOURCES.txt to...
[ "You don't need to create all that, the .egg-info directory is generated by setuptools. You mention the command line, so I assumed you have a 'top level' script somewhere, let's say myproj-bin. Then this would work:\n./setup.py\n./myproj\n./myproj/__init__.py\n./scripts\n./scripts/myproj-bin\n\nAnd then put somet...
[ 7 ]
[]
[]
[ "distribute", "packaging", "python", "setuptools" ]
stackoverflow_0003465045_distribute_packaging_python_setuptools.txt
Q: Django templates and variable attributes I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] The Django template is: <table> <tr align="center"> <th>...
Django templates and variable attributes
I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] The Django template is: <table> <tr align="center"> <th>user</th> {% for item in result.items %} ...
[ "I found a \"nicer\"/\"better\" solution for getting variables inside\nIts not the nicest way, but it works.\nYou install a custom filter into django which gets the key of your dict as a parameter\nTo make it work in google app-engine you need to add a file to your main directory,\nI called mine django_hack.py whic...
[ 33, 10, 9, 4, 3, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000035948_django_google_app_engine_python.txt
Q: Django CMS 2.1.0 App Extension NoReverseMatch TemplateSyntaxError I'm writing a custom app for Django CMS, but get the following error when trying to view a published entry in the admin: TemplateSyntaxError at /admin/cmsplugin_publisher/entry/ Caught NoReverseMatch while rendering: Reverse for 'cmsplugin_publishe...
Django CMS 2.1.0 App Extension NoReverseMatch TemplateSyntaxError
I'm writing a custom app for Django CMS, but get the following error when trying to view a published entry in the admin: TemplateSyntaxError at /admin/cmsplugin_publisher/entry/ Caught NoReverseMatch while rendering: Reverse for 'cmsplugin_publisher_entry_detail' with arguments '()' and keyword arguments '{'slug': u't...
[ "Looks like it's a bug in the URLconf parser in Django-CMS 2.1.0beta3, which is fixed in dev. The bug only occurs when including other URLconfs from within an app.\n", "UPDATE: \nOK, I think your error originates from get_absolute_url:\n@models.permalink\ndef get_absolute_url(self):\n return ('cmsplugin_publi...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0003430383_django_django_cms_python.txt
Q: Copying a file with access locks, forcefully with python I'm trying to copy an excel sheet with python, but I keep getting "access denied" error message. The file is closed and is not shared. It has macros though. Is their anyway I can copy the file forcefully with python? thanks. A: If you do not have sufficien...
Copying a file with access locks, forcefully with python
I'm trying to copy an excel sheet with python, but I keep getting "access denied" error message. The file is closed and is not shared. It has macros though. Is their anyway I can copy the file forcefully with python? thanks.
[ "If you do not have sufficient file permissions you will not be able to access the file. In that case you will have to execute your Python program as an user with sufficient permissions.\nIf on the other hand the file is locked using other means specific to Excel then I am not sure what exactly is the solution. You...
[ 0 ]
[]
[]
[ "excel_2003", "python" ]
stackoverflow_0003465231_excel_2003_python.txt
Q: b = a vs b = a[:] in strings|lists in Lists - I can always check that b=a points to same object and c=a[:] creates another copy. >>> a = [1,2,3,4,5] >>> b = a >>> c = a[:] >>> a[0] = 10 >>> b [10, 2, 3, 4, 5] >>> c [1, 2, 3, 4, 5] In Strings - I cannot make a change to the original immutable string. How do I co...
b = a vs b = a[:] in strings|lists
in Lists - I can always check that b=a points to same object and c=a[:] creates another copy. >>> a = [1,2,3,4,5] >>> b = a >>> c = a[:] >>> a[0] = 10 >>> b [10, 2, 3, 4, 5] >>> c [1, 2, 3, 4, 5] In Strings - I cannot make a change to the original immutable string. How do I confirm myself that b=a makes b point to s...
[ "you can use the is operator.\na = 'aaaaa'\nb = 'bbbbb'\n\nprint a is b\na = b\nprint a is b\n\nc = a[:]\nprint c is a\n\nThis works because a is b if and only if id(a) == id(b). In CPython at least, id(foo) is just the memory address at which foo is stored. Hence if foo is bar, then foo and bar are literally the s...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003465897_python.txt
Q: How to depends of a system command with python/distutils? I'm looking for the most elegant way to notify users of my library that they need a specific unix command to ensure that it will works... When is the bet time for my lib to raise an error: Installation ? When my app call the command ? At the import of my l...
How to depends of a system command with python/distutils?
I'm looking for the most elegant way to notify users of my library that they need a specific unix command to ensure that it will works... When is the bet time for my lib to raise an error: Installation ? When my app call the command ? At the import of my lib ? both? And also how should you detect that the command is ...
[ "IMO, the best way is to check at install if the user has this specific *nix command.\nIf you're using distutils to distribute your package, in order to install it you have to do:\n\npython setup.py build\n python setup.py install \n\nor simply\n\npython setup.py install (in that case python setup.py build is impl...
[ 5, 4 ]
[]
[]
[ "command", "distutils", "packaging", "python" ]
stackoverflow_0003465295_command_distutils_packaging_python.txt
Q: Python module to convert from document to html Is there any python package which converts the uploaded Ms Word document to html content.As in my application am uploading a document and i want to convert it into html any suggestion o nthis will help Thanks A: You could call unoconv from within Python.
Python module to convert from document to html
Is there any python package which converts the uploaded Ms Word document to html content.As in my application am uploading a document and i want to convert it into html any suggestion o nthis will help Thanks
[ "You could call unoconv from within Python.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003467636_python.txt
Q: Get_by_key_name doesn't work with unicode key names of several characters I'm using unicode strings for non latin characters as key names for my models. I can create objects without problems, and the appengine admin shows key name correctly (I'm using chinese characters, and the right characters) However, MyModel....
Get_by_key_name doesn't work with unicode key names of several characters
I'm using unicode strings for non latin characters as key names for my models. I can create objects without problems, and the appengine admin shows key name correctly (I'm using chinese characters, and the right characters) However, MyModel.get_by_key_name() returns None if the key_name is made of several characters. F...
[ "Actually, I made some stupid encoding error when testing yesterday, which made me think the error came from the function.\nThe problem doesnt come from the keys. It is just an error in my algorithm that won't check for keys of 2 characters if there is no object which the 1st character as keyname.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003451983_google_app_engine_python.txt
Q: How can Python lists within objects be freed? I have a Python class containing a list, to which I append() values. If I delete an object of this class then create a second object later on in the same script, the second object's list is the same as the first's was at the time of deletion. For example: class myObj: ...
How can Python lists within objects be freed?
I have a Python class containing a list, to which I append() values. If I delete an object of this class then create a second object later on in the same script, the second object's list is the same as the first's was at the time of deletion. For example: class myObj: a = [] b = False o = myObj() o.a.append("I...
[ "When you create a variable inside a class declaration, it's a class attribute, not an instance attribute. To create instance attributes you have to do self.a inside a method, e.g. __init__.\nChange it to:\nclass myObj:\n def __init__(self):\n self.a = []\n self.b = False\n\n" ]
[ 9 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003467704_list_python.txt
Q: Python SOAP to MS WebService(SharePoint)(GetListItems) I am attempting to pull list Items from a sharepoint server(via python/suds) and am having some difficulty with making queries to GetListItems. If i provide no other parameters to GetListItems other than the list Name, it will return all the items in the defa...
Python SOAP to MS WebService(SharePoint)(GetListItems)
I am attempting to pull list Items from a sharepoint server(via python/suds) and am having some difficulty with making queries to GetListItems. If i provide no other parameters to GetListItems other than the list Name, it will return all the items in the default view for that List. I want to query a specific set of i...
[ "I figured this one out. The problem was the CAML query. \n1. You need to wrap the CAML 'Query' in a 'query' element.\n2. You need to set the proper 'Value Type' Element and attributes.\nSee me other posting titled 'Sharepoint Filter for List Items(GetListItems)' for more info and code.\nThanks!\nNick\n" ]
[ 2 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0003443578_python_soap.txt
Q: Document Similarity: Comparing two documents efficiently I have a loop that calculates the similarity between two documents. It collects all the tokens in a document and their scores, and places them in dictionary. It then compares the dictionaries This is what I have so far, it works, but is super slow: # Doc A ...
Document Similarity: Comparing two documents efficiently
I have a loop that calculates the similarity between two documents. It collects all the tokens in a document and their scores, and places them in dictionary. It then compares the dictionaries This is what I have so far, it works, but is super slow: # Doc A cursor1.execute("SELECT token, tfidf_norm FROM index WHERE doc...
[ "A Python point: adict.has_key(k) is obsolete in Python 2.X and vanished in Python 3.X. k in adict as an expression has been available since Python 2.2; use it instead. It will be faster (no method call).\nAn any-language practical point: iterate over the shorter dictionary.\nCombined result:\nif len(doca_dic) < le...
[ 2, 1, 0 ]
[]
[]
[ "mysql", "performance", "python" ]
stackoverflow_0002437978_mysql_performance_python.txt
Q: How to keep text inside a circle using Cairo? I a drawing a graph using Cairo (pycairo specifically) and I need to know how can I draw text inside a circle without overlapping it, by keeping it inside the bounds of the circle. I have this simple code snippet that draws a letter "a" inside the circle: ''' Created o...
How to keep text inside a circle using Cairo?
I a drawing a graph using Cairo (pycairo specifically) and I need to know how can I draw text inside a circle without overlapping it, by keeping it inside the bounds of the circle. I have this simple code snippet that draws a letter "a" inside the circle: ''' Created on May 8, 2010 @author: mrios ''' import cairo, mat...
[ "I had a similar issue, where I need to adjust the size of the font to keep the name of my object within the boundaries of rectangles, not circles. I used a while loop, and kept checking the text extent size of the string, decreasing the font size until it fit.\nHere what I did: (this is using C++ under Kylix, a D...
[ 3, 3 ]
[]
[]
[ "cairo", "graphics", "pycairo", "python" ]
stackoverflow_0002793093_cairo_graphics_pycairo_python.txt
Q: Trying to come up with a recursive function to expand a tree in Python I have table that looks like this: id | parentid | name --------------------- 1 | 0 | parent1 --------------------- 2 | 0 | parent2 --------------------- 3 | 1 | child1 --------------------- 4 | 3 | subchild...
Trying to come up with a recursive function to expand a tree in Python
I have table that looks like this: id | parentid | name --------------------- 1 | 0 | parent1 --------------------- 2 | 0 | parent2 --------------------- 3 | 1 | child1 --------------------- 4 | 3 | subchild1 I'm now trying to come up with an efficient way to take that database dat...
[ "If I understand correctly, the item for which their parent id is 0 are the root one or the first level ?\nIf so, your method should look like:\ndef expand(tree, id):\n expanded_tree = {}\n\n parents = [i for i in tree if i.parentid == id]\n\n for parent in parents:\n expanded_tree[parent.name] = ex...
[ 2, 1 ]
[]
[]
[ "python", "recursion", "tree" ]
stackoverflow_0003467723_python_recursion_tree.txt
Q: Python HTTPS client with basic authentication via proxy From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows. I have been playing around with urllib2, howeve...
Python HTTPS client with basic authentication via proxy
From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows. I have been playing around with urllib2, however did not succeed so far. I have a solution running, calling ...
[ "Try this (notice that you'll have to fill in the realm of your server also):\nimport urllib2\nauthinfo = urllib2.HTTPBasicAuthHandler()\nauthinfo.add_password(realm='Fill In Realm Here',\n uri='https://fqdn.to.site/content',\n user='username',\n passwd...
[ 3, 3, 0 ]
[]
[]
[ "basic_authentication", "https", "proxy", "python" ]
stackoverflow_0001453264_basic_authentication_https_proxy_python.txt
Q: Python doesn't have opcode cacher? I'm currently using PHP. I plan to start using Django for some of my next project. But I don't have any experience with Python. After some searching, I still can't find a Python opcode cacher. (There are lots of opcode cacher for PHP: APC, eAccelerator, Xcache, ...) A: It's aut...
Python doesn't have opcode cacher?
I'm currently using PHP. I plan to start using Django for some of my next project. But I don't have any experience with Python. After some searching, I still can't find a Python opcode cacher. (There are lots of opcode cacher for PHP: APC, eAccelerator, Xcache, ...)
[ "It's automatic in Python -- a compiled .pyc file will appear magically.\n", "Python doesn't need one the same way PHP needs it. Python doesn't throw the bytecode away after execution, it keeps it around (as .pyc files).\n", "It's built in: http://pyfaq.infogami.com/how-do-i-create-a-pyc-file\nPython can compil...
[ 9, 2, 1 ]
[]
[]
[ "opcode", "opcode_cache", "python" ]
stackoverflow_0003468243_opcode_opcode_cache_python.txt
Q: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work? What happens internally when I press Enter? My motivation for asking, besides plain curiosity, is to figure out what happens when you from sympy import * and enter an expression. How does i...
How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?
What happens internally when I press Enter? My motivation for asking, besides plain curiosity, is to figure out what happens when you from sympy import * and enter an expression. How does it go from Enter to calling __sympifyit_wrapper(a,b) in sympy.core.decorators? (That's the first place winpdb took me when I tried...
[ "All right after playing around with it some more I think I've got it.. when I first asked the question I didn't know about operator overloading.\nSo, what's going on in this python session?\n>>> from sympy import *\n>>> x = Symbol(x)\n>>> x + x\n2*x\n\nIt turns out there's nothing special about how the interpreter...
[ 12, 6, 5, 1 ]
[]
[]
[ "eval", "interactive", "python", "scripting", "sympy" ]
stackoverflow_0003191749_eval_interactive_python_scripting_sympy.txt
Q: Caching options in Python or speeding up urlopen Hey all, I have a site that looks up info for the end user, is written in Python, and requires several urlopen commands. As a result it takes a bit for a page to load. I was wondering if there was a way to make it faster? Is there an easy Python way to cache or a wa...
Caching options in Python or speeding up urlopen
Hey all, I have a site that looks up info for the end user, is written in Python, and requires several urlopen commands. As a result it takes a bit for a page to load. I was wondering if there was a way to make it faster? Is there an easy Python way to cache or a way to make the urlopen scripts fun last? The urlopens ...
[ "httplib2 understands http request caching, abstracts urllib/urllib2's messiness somewhat and has other goodies, like gzip support.\nhttp://code.google.com/p/httplib2/\nBut besides using that to get the data, if the dataset is not very big, I would also implement some kind of function caching / memoizing. \nExample...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "caching", "python", "sql", "urlopen" ]
stackoverflow_0003468248_caching_python_sql_urlopen.txt
Q: Overwrite method add for ManyToMany related fields Where should I overwrite method add() for ManyToMany related fields. Seems like it is not manager 'objects' of my model. Because when we are adding new relation for ManyToMany fields we are not writing Model.objects.add(). So what I need it overwrite method add()...
Overwrite method add for ManyToMany related fields
Where should I overwrite method add() for ManyToMany related fields. Seems like it is not manager 'objects' of my model. Because when we are adding new relation for ManyToMany fields we are not writing Model.objects.add(). So what I need it overwrite method add() of instance. How can I do it? Edit: So i know that ther...
[ "http://docs.djangoproject.com/en/1.2/topics/db/managers/#custom-managers\nYou can create any number of managers for a Model.\nYou can subclass a ManyRelatedManager and assign it to the Model.\nThis example may be what you're looking for\n# Then hook it into the Book model explicitly.\nclass Book(models.Model):\n ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003463372_django_python.txt
Q: How can I create python strings with placeholders with arbitrary number of elements I can do string="%s"*3 print string %(var1,var2,var3) but I can't get the vars into another variable so that I can create a list of vars on the fly with app logic. for example if condition: add a new %s to string variable va...
How can I create python strings with placeholders with arbitrary number of elements
I can do string="%s"*3 print string %(var1,var2,var3) but I can't get the vars into another variable so that I can create a list of vars on the fly with app logic. for example if condition: add a new %s to string variable vars.append(newvar) else: remove one %s from string vars.pop() print string with place...
[ "How about this?\nprint (\"%s\" * len(vars)) % tuple(vars)\n\nReally though, that's a rather silly way to do things. If you just want to squish all the variables together in one big string, this is likely a better idea:\nprint ''.join(str(x) for x in vars)\n\nThat does require at least Python 2.4 to work.\n", "u...
[ 6, 3, 1 ]
[]
[]
[ "placeholder", "python" ]
stackoverflow_0003468916_placeholder_python.txt
Q: Python: Why does subprocess() start 2 processes in Ubuntu, and 1 in OpenSUSE? I've written small gui-frontend in Python that lets users play internet radio channels. The program uses Pythons subprocess() to initizalize mplayer in order to tune into a channel, e.g.: runn = "mplayer http://77.111.88.131:8010" p = su...
Python: Why does subprocess() start 2 processes in Ubuntu, and 1 in OpenSUSE?
I've written small gui-frontend in Python that lets users play internet radio channels. The program uses Pythons subprocess() to initizalize mplayer in order to tune into a channel, e.g.: runn = "mplayer http://77.111.88.131:8010" p = subprocess.Popen(runn, shell=True) pid = int(p.pid) wait = os.waitpid(p.pid, 1) Then ...
[ "Try this:\np = subprocess.Popen(runn.split(), shell=False)\n\nMy guess as to what's going on is this...\nWhen you say shell=True subprocess actually starts this command sh -c \"your string\". The sh command then interprets your string and runs the command as if you'd typed that in at the shell prompt (more or les...
[ 7, 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003468922_python_subprocess.txt
Q: Regular expression: if, else if, else I am trying to parse FSM statements of the Gezel language (http://rijndael.ece.vt.edu/gezel2/) using Python and regular expressions regex_cond = re.compile(r'.+((else\tif|else|if)).+') line2 = '@s0 else if (insreg==1) then (initx,PING,notend) -> sinitx;' match = regex_cond.m...
Regular expression: if, else if, else
I am trying to parse FSM statements of the Gezel language (http://rijndael.ece.vt.edu/gezel2/) using Python and regular expressions regex_cond = re.compile(r'.+((else\tif|else|if)).+') line2 = '@s0 else if (insreg==1) then (initx,PING,notend) -> sinitx;' match = regex_cond.match(line2); I have problems to distinguis...
[ "a \\t matches a tab character. It doesn't look like you have a tab character between \"else\" and \"if\" in line2. You might try \\s instead, which matches any whitespace character.\n", "Don't do this; use pyparsing instead. You'll thank yourself later.\n\nThe problem is that .+ is greedy, so it's eating up the ...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003468881_python_regex.txt
Q: Python Django MySQLdb setup problem:: setup.py dosen't build due to incorrect location of mysql I'm trying to install MySQLdb for python. but when I run the setup, this is the error I get. well I know why its giving all the missing file statements, but dont know where to change the bold marked location from. Pleas...
Python Django MySQLdb setup problem:: setup.py dosen't build due to incorrect location of mysql
I'm trying to install MySQLdb for python. but when I run the setup, this is the error I get. well I know why its giving all the missing file statements, but dont know where to change the bold marked location from. Please help gaurav-toshniwals-macbook-7:MySQL-python-1.2.3c1 gauravtoshniwal$ python setup.py build runnin...
[ "This path probably comes from mysql_config utility, edit your setup_posix.py and change the variable mysql_config.path to meet your correct mysql_config utility path.\n", "The above suggestion is really helpful but it might also be worth mentioning that you must have mysql-devel installed as well for your build ...
[ 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003029942_django_mysql_python.txt
Q: Python file.read() seeing junk characters at the beginning of a file I'm trying to use Python to concatenate a few javascript files together before minifying them, basically like so: outfile = open("output.js", "w") for somefile in a_list_of_file_names: js = open(somefile) outfile.write(js.read()) js.c...
Python file.read() seeing junk characters at the beginning of a file
I'm trying to use Python to concatenate a few javascript files together before minifying them, basically like so: outfile = open("output.js", "w") for somefile in a_list_of_file_names: js = open(somefile) outfile.write(js.read()) js.close() outfile.close() The minifier complains about illegal characters an...
[ "That's a UTF-8 BOM (Byte Order Mark). You've probably edited the file with Notepad.\n", "EF BB BF is a Unicode Byte-Order Mark (BOM). Those are actually in your files. That's why Python is seeing it.\nEither ignore/discard the BOM or reencode the files to omit it.\n" ]
[ 6, 5 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003469200_file_io_python.txt
Q: Manipulating list from lxml xpath queries Today I tried lxml as I got very nasty html output from particular web service, and I didn't want to go with re module, just for change and to learn something new. And I did, browsing http://codespeak.net/lxml/ and http://stackoverflow.com in parallel I won't try to explai...
Manipulating list from lxml xpath queries
Today I tried lxml as I got very nasty html output from particular web service, and I didn't want to go with re module, just for change and to learn something new. And I did, browsing http://codespeak.net/lxml/ and http://stackoverflow.com in parallel I won't try to explain above html template, but just for overview it...
[ "How's this?\nfrom lxml import etree\ndoc = etree.HTML(open('test.data').read())\n\nfor t in doc.xpath('//table[.//div[@id=\"title\"] and .//td[@class=\"text\"]]'):\n print etree.tostring(t.xpath('.//div[@id=\"title\"]')[0])\n print etree.tostring(t.xpath('.//td[@class=\"text\"]')[0])\n print \"--\"\n\nYie...
[ 6, 0 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0003467203_lxml_python_xpath.txt
Q: I'd like some advice on packaging this as an egg and uploading it to pypi I wrote some code that I'd like to package as an egg. This is my directory structure: src/ src/tests src/tests/test.py # this has several tests for the movie name parser src/torrent src/torrent/__init__.py src/torrent/movienameparser src/to...
I'd like some advice on packaging this as an egg and uploading it to pypi
I wrote some code that I'd like to package as an egg. This is my directory structure: src/ src/tests src/tests/test.py # this has several tests for the movie name parser src/torrent src/torrent/__init__.py src/torrent/movienameparser src/torrent/movienameparser/__init__.py # this contains the code I'd like to package...
[ "I won't get into licensing discussion here, but it's typical to include LICENSE file at the root of your package source code, along with other customary things like README, etc.\nI usually organize packages the same way they will be installed on the target system. The standard package layout convention is explaine...
[ 6, 3, 0 ]
[]
[]
[ "distutils", "egg", "pypi", "python", "setuptools" ]
stackoverflow_0001301689_distutils_egg_pypi_python_setuptools.txt
Q: Ordering in Python (2.4) dictionary r_dict={'answer1': "value1",'answer11': "value11",'answer2': "value2",'answer3': "value3",'answer4': "value4",} for i in r_dict: if("answer" in i.lower()): print i Result is answer11,answer2,snswer4,answer3 I am using Python 2.4.3. I there any way...
Ordering in Python (2.4) dictionary
r_dict={'answer1': "value1",'answer11': "value11",'answer2': "value2",'answer3': "value3",'answer4': "value4",} for i in r_dict: if("answer" in i.lower()): print i Result is answer11,answer2,snswer4,answer3 I am using Python 2.4.3. I there any way to get the order in which it is populate...
[ "Dictionaries are unordered - that is, they do have some order, but it's influenced in nonobvious ways by the order of insertion and the hash of the keys. However, there is another implementation that remembers the order of insertion, collections.OrderedDict.\nEdit: For Python 2.4, there are several third party imp...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003469633_python.txt
Q: The listener does not work! Django-signals from django.db.models.signals import post_save class MyModel(models.Model): int = models.PositiveIntegerField(unique=True) def added (sender, instance, **kwargs): print 'Added' post_save.connect(added,MyModel) When I do: MyModel.objects.create(int=12345).save...
The listener does not work! Django-signals
from django.db.models.signals import post_save class MyModel(models.Model): int = models.PositiveIntegerField(unique=True) def added (sender, instance, **kwargs): print 'Added' post_save.connect(added,MyModel) When I do: MyModel.objects.create(int=12345).save() nothing happened Am i lose something? Aft...
[ "It looks like you're connecting added() to MyModel instead of BitRate, so it's not surprising that added() is not fired when a bitrate is saved...\n", "You're connecting post_save to MyModel, but you're creating and saving Bitrate. Is that a typo?\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003469696_django_python.txt
Q: Python: wx.ListCtrl -> how to make one of the items a picture that once clicked opens a file I have a wx.ListCtrl instance to which I use InsertColumn like this: Path | Size | ... | Last run For each item to be displayed I have a function that sets all the fields: setStringItem(index, 0, path) setStringItem(index...
Python: wx.ListCtrl -> how to make one of the items a picture that once clicked opens a file
I have a wx.ListCtrl instance to which I use InsertColumn like this: Path | Size | ... | Last run For each item to be displayed I have a function that sets all the fields: setStringItem(index, 0, path) setStringItem(index, 1, size) ... I want on column 6 (Last run) to do the following: 1) add a picture 2) the picture ...
[ "Take a look at Andrea's UltimateListCtrl - it's included in the latest wx, but the online docs aren't up to date.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003467869_python_wxpython.txt
Q: How can I benchmark different languages / frameworks? I'd like to compare the performance of different languages and/or different frameworks within the same language. This is aimed at server-side languages used for web development. I know an apples to apples comparison is not possible, but I'd like it to be as unb...
How can I benchmark different languages / frameworks?
I'd like to compare the performance of different languages and/or different frameworks within the same language. This is aimed at server-side languages used for web development. I know an apples to apples comparison is not possible, but I'd like it to be as unbiased as possible. Here are some ideas : Simple "Hello Wor...
[ "There's a lot of good advice (and a huge number of sample benchmarks for different languages) at http://shootout.alioth.debian.org/\nC.\n", "What I have done is to write many unit tests so you can test the layers.\nFor example, write a SOAP web service in PHP, Python and C#. \nWrite a REST web service in the sa...
[ 3, 2, 2, 0 ]
[]
[]
[ "asp.net", "benchmarking", "frameworks", "php", "python" ]
stackoverflow_0003468227_asp.net_benchmarking_frameworks_php_python.txt
Q: Is there any language which is just "perfect" for web scraping? I have used 3 languages for Web Scraping - Ruby, PHP and Python and honestly none of them seems to perfect for the task. Ruby has an excellent mechanize and XML parsing library but the spreadsheet support is very poor. PHP has excellent spreadsheet ...
Is there any language which is just "perfect" for web scraping?
I have used 3 languages for Web Scraping - Ruby, PHP and Python and honestly none of them seems to perfect for the task. Ruby has an excellent mechanize and XML parsing library but the spreadsheet support is very poor. PHP has excellent spreadsheet and HTML parsing library but it does not have an equivalent of WWW:Me...
[ "Check Python + Scrappy, it is pretty good:\nhttp://scrapy.org/\n", "Why not just use the XML Spreadsheet format? It's super simple to create, and it would probably be trivial with any type of class-based system.\nAlso, for Python have you tried BeautifulSoup for parsing? Urllib+BeautifulSoup makes a pretty power...
[ 2, 1, 1, 0 ]
[]
[]
[ "php", "python", "ruby", "web_scraping" ]
stackoverflow_0003468028_php_python_ruby_web_scraping.txt
Q: Reusing a Django RSS Feed for different Date Ranges What would be a way to have date range based rss feeds in Django. For instance if I had the following type of django rss feed model. from django.contrib.syndication.feeds import Feed from myapp.models import * class PopularFeed(Feed): title = '%s : Latest SO...
Reusing a Django RSS Feed for different Date Ranges
What would be a way to have date range based rss feeds in Django. For instance if I had the following type of django rss feed model. from django.contrib.syndication.feeds import Feed from myapp.models import * class PopularFeed(Feed): title = '%s : Latest SOLs' % settings.SITE_NAME link = '/' description =...
[ "You need to define a class for each feed you want. For example for Last Month feed:\nclass LastMonthFeed(Feed):\n\n def items(self):\n ts = datetime.datetime.now() - datetime.timedelta(days=30)\n return sol.object.filter(date__gte=ts).order_by('-date')\n\nThen add these feeds to your urls.py as sh...
[ 1 ]
[]
[]
[ "django", "django_rss", "feed", "python" ]
stackoverflow_0003469631_django_django_rss_feed_python.txt
Q: Send mail with python using bcc I'm working with django, i need send a mail to many emails, i want to do this with a high level library like python-mailer, but i need use bcc field, any suggestions? A: You should look at the EmailMessage class inside of django, supports the bcc. Complete docs availble here: h...
Send mail with python using bcc
I'm working with django, i need send a mail to many emails, i want to do this with a high level library like python-mailer, but i need use bcc field, any suggestions?
[ "You should look at the EmailMessage class inside of django, supports the bcc.\nComplete docs availble here:\n http://docs.djangoproject.com/en/dev/topics/email/#the-emailmessage-class\nQuick overview:\nThe EmailMessage class is initialized with the following parameters (in the given order, if positional argument...
[ 4 ]
[]
[]
[ "bcc", "django", "email", "python" ]
stackoverflow_0003470172_bcc_django_email_python.txt
Q: What does logging.basicConfig do? I have seen this in a lot of python code what does this do? What is it useful for? logging.basicConfig(level=loglevel, format=myname) A: Please read the documentation - it explains your question in detail: http://docs.python.org/library/logging.html#logging.basicConfig "baseConf...
What does logging.basicConfig do?
I have seen this in a lot of python code what does this do? What is it useful for? logging.basicConfig(level=loglevel, format=myname)
[ "Please read the documentation - it explains your question in detail:\nhttp://docs.python.org/library/logging.html#logging.basicConfig \"baseConfig\"\n" ]
[ 4 ]
[]
[]
[ "logging", "python", "scripting" ]
stackoverflow_0003470262_logging_python_scripting.txt
Q: virtualenv, sys.path and site-packages i am setting up a virtualenv for django deployment. i want an isolated env without access to the global site-packages. i used the option --no-site-packages, then installed a local pip instance for that env. after using pip and a requirements.txt file i noticed that most pac...
virtualenv, sys.path and site-packages
i am setting up a virtualenv for django deployment. i want an isolated env without access to the global site-packages. i used the option --no-site-packages, then installed a local pip instance for that env. after using pip and a requirements.txt file i noticed that most packages were installed in a "build" folder tha...
[ "it seems that the pip process quit prematurely due to a package in requirements that could not be found. this left things in limbo, stuck in the temp-like \"build\" folder before having a chance to complete the process which gets them into the proper \"site-packages\" location.\n" ]
[ 1 ]
[]
[]
[ "django", "pip", "python", "virtualenv" ]
stackoverflow_0003469551_django_pip_python_virtualenv.txt
Q: Understanding Python daemon threads I've obviously misunderstood something fundamental about a Python Thread object's daemon attribute. Consider the following: daemonic.py import sys, threading, time class TestThread(threading.Thread): def __init__(self, daemon): threading.Thread.__init__(self) ...
Understanding Python daemon threads
I've obviously misunderstood something fundamental about a Python Thread object's daemon attribute. Consider the following: daemonic.py import sys, threading, time class TestThread(threading.Thread): def __init__(self, daemon): threading.Thread.__init__(self) self.daemon = daemon def run(self...
[ "Your understanding about what daemon threads should do is correct. \nAs to why this isn't happening, I am guessing you are using an older version of Python. The Python 2.5.4 docs include a setDaemon(daemonic) function, as well as isDaemon() to check if a thread is a daemon thread. The 2.6 docs replace these wit...
[ 13, 6 ]
[]
[]
[ "python" ]
stackoverflow_0003470235_python.txt
Q: How to link one table to itself? I'm trying to link one table to itself. I have media groups which can contain more media group. I created a relation many to many: media_group_groups = Table( "media_group_groups", metadata, Column("groupA_id", Integer, ForeignKey("media_groups.i...
How to link one table to itself?
I'm trying to link one table to itself. I have media groups which can contain more media group. I created a relation many to many: media_group_groups = Table( "media_group_groups", metadata, Column("groupA_id", Integer, ForeignKey("media_groups.id")), Column("groupB_id", ...
[ "SQLAlchemy can't figure out which columns in your link table to join on. Try this for the relationship:\nmediaGroup = relationship(\"MediaGroup\",\n secondary=media_group_groups,\n order_by=\"MediaGroup.title\",\n backref=backref('media_groups', \n secondary=\"media_med...
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003470208_python_sqlalchemy.txt
Q: Build SQL queries in Python Are there any python packages that help generating SQL queries from variables and classes? For example, instead of writing create query manually, the developer will create a create table (as an object maybe), with desired columns in a list for instance. Then the object will return a str...
Build SQL queries in Python
Are there any python packages that help generating SQL queries from variables and classes? For example, instead of writing create query manually, the developer will create a create table (as an object maybe), with desired columns in a list for instance. Then the object will return a string that will be used as a query....
[ "Probably the best Object-Relational mapper package for Python today is the popular SqlAlchemy.\n", "The standard python MySQLdb package will do the right things about quoting variables if it's given a chance. If you're worried about SQL injection attacks.\nc.executemany(\n \"\"\"INSERT INTO breakfast (name...
[ 2, 1 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003469990_python_sql.txt
Q: In Django, how to limit entries from each user to a specific number N (N > 1)? I have a Django web application that's similar to the typical Q&A system. A user asks a question. other users submit answers to that question: Each user is allowed to submit up to N answers to each question, where N > 1 (so, say each ...
In Django, how to limit entries from each user to a specific number N (N > 1)?
I have a Django web application that's similar to the typical Q&A system. A user asks a question. other users submit answers to that question: Each user is allowed to submit up to N answers to each question, where N > 1 (so, say each user can submit no more than 3 answers to each question) A user can edit his existin...
[ "I'd add the following method to your Question model:\nclass Question(models.Model):\n\n def can_answer(self, user):\n return Answer.filter(question=self, user=user).count() < 3\n\nYou can use this method to decide if a user can add answers to the question.\n", "This is a business rule that you will hav...
[ 2, 2 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0003470120_database_django_python.txt
Q: Anyone else having trouble keeping ghettoq running inthe background with django-celery? nohup python manage.py celeryd -f queue.log 2>queue.err 1>queue.out & Handles one request fine, then the client app posting the next job to the queues fails with this traceback. tasks.spawn_job.delay(details) File "/relea...
Anyone else having trouble keeping ghettoq running inthe background with django-celery?
nohup python manage.py celeryd -f queue.log 2>queue.err 1>queue.out & Handles one request fine, then the client app posting the next job to the queues fails with this traceback. tasks.spawn_job.delay(details) File "/releases/env/lib/python2.6/site-packages/celery/task/base.py", line 321, in delay return self.a...
[ "Switching to RabbitMQ is probably a good idea. But note that this is a bug fixed in the master\n branch of ghettoq.\n" ]
[ 0 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0003465568_celery_django_python.txt
Q: Java or any other language: Which method/class invoked mine? I would like to write a code internal to my method that print which method/class has invoked it. (My assumption is that I can't change anything but my method..) How about other programming languages? EDIT: Thanks guys, how about JavaScript? python? C++?...
Java or any other language: Which method/class invoked mine?
I would like to write a code internal to my method that print which method/class has invoked it. (My assumption is that I can't change anything but my method..) How about other programming languages? EDIT: Thanks guys, how about JavaScript? python? C++?
[ "This is specific to Java.\nYou can use Thread.currentThread().getStackTrace(). This will return an array of StackTraceElements.\nThe 2nd element in the array will be the calling method.\nExample:\npublic void methodThatPrintsCaller() {\n StackTraceElement elem = Thread.currentThread.getStackTrace()[2];\n Sy...
[ 20, 4, 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "classloader", "java", "javascript", "programming_languages", "python" ]
stackoverflow_0003468101_classloader_java_javascript_programming_languages_python.txt
Q: django, show fields on admin site that are not in model Building a Django app. Class Company(models.Model): trucks = models.IntegerField() multiplier = models.IntegerField() #capacity = models.IntegerField() The 'capacity' field is actually the sum of (trucks * multiplier). So I don't need a database ...
django, show fields on admin site that are not in model
Building a Django app. Class Company(models.Model): trucks = models.IntegerField() multiplier = models.IntegerField() #capacity = models.IntegerField() The 'capacity' field is actually the sum of (trucks * multiplier). So I don't need a database field for it since I can calculate it. However, my admin use...
[ "define a method on company that returns the product of trucks and multiplier\ndef capacity(self):\n return self.trucks * self.multiplier\n\nand in the admin model set\nlist_display = ('trucks', 'multiplier', 'capacity')\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003471035_django_django_admin_python.txt
Q: Invalid syntax error in simple Python-3 program from TurtleWorld import * import math bob = Turtle() print(bob) draw_circle(turtle, r): d = r*2 c = d*math.pi degrees = 360/25 length = c // 25 for i in range(25): fd(turtle, length) rt(turtle, degrees) draw_circle(bob, 25) wai...
Invalid syntax error in simple Python-3 program
from TurtleWorld import * import math bob = Turtle() print(bob) draw_circle(turtle, r): d = r*2 c = d*math.pi degrees = 360/25 length = c // 25 for i in range(25): fd(turtle, length) rt(turtle, degrees) draw_circle(bob, 25) wait_for_user() The problem in on line 7: draw_circle...
[ "in python, we define functions using the def keyword.. like\ndef draw_circle(turtle, r):\n # ...\n\n", "You need to write:\ndef draw_circle(turtle, r):\n\nto define a function.\n", "http://docs.python.org/release/3.0.1/tutorial/controlflow.html#defining-functions\nYour missing the def part?\n", "I thought...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "python_3.x", "syntax", "syntax_error" ]
stackoverflow_0003471165_python_python_3.x_syntax_syntax_error.txt
Q: Python inline of XML or ASCII string/template? I am generating complex XML files through Python scripts that require a bunch of conditional statements (example http://repository.azgs.az.gov/uri_gin/azgs/dlio/536/iso19139.xml). I am working with multiple XML or ASCII metadata standards that often have poor schema o...
Python inline of XML or ASCII string/template?
I am generating complex XML files through Python scripts that require a bunch of conditional statements (example http://repository.azgs.az.gov/uri_gin/azgs/dlio/536/iso19139.xml). I am working with multiple XML or ASCII metadata standards that often have poor schema or are quite vague. In PHP, I just wrote out the XML...
[ "wgrunberg,\nI use Python's built-in string.Template class like so:\nfrom string import Template\nthe_template = Template(\"<div id='$section_id'>First name: $first</div>\")\nprint the_template.substitute(section_id=\"anID\", first=\"Sarah\")\n\nThe output of the above is:\n<div id='anID'>First name: Sarah</div>\n\...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003454437_python.txt
Q: Weird behaviour with lxml getiterator() I have the following XML document: <x> <a>Some text</c> <b>Some text 2</b> <c>Some text 3</c> </x> I want to get the text of all the tags, so I decided to use getiterator(). My problem is, it adds up blank lines for a reason I can't understand. Consider this: >>> for ...
Weird behaviour with lxml getiterator()
I have the following XML document: <x> <a>Some text</c> <b>Some text 2</b> <c>Some text 3</c> </x> I want to get the text of all the tags, so I decided to use getiterator(). My problem is, it adds up blank lines for a reason I can't understand. Consider this: >>> for text in document_root.getiterator(): ... ...
[ "By default lxml.etree will regard empty text between tags as the textual content for that tag and in your case the whitespace being displayed comes from <x>. If you want a parser that ignores the whitespace you'll want to do something like:\nfrom lxml import etree\n\nparser = etree.XMLParser(remove_blank_text=True...
[ 2, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003470929_lxml_python.txt
Q: Python Class in module not loading in one computer, but the other So I have two files: File 1 has this method in it: import MyGlobals global old_function def init(): import ModuleB global old_function MyGlobals.SomeNumber = 0 old_function = ModuleB.someClass.function ModuleB.someClass.function ...
Python Class in module not loading in one computer, but the other
So I have two files: File 1 has this method in it: import MyGlobals global old_function def init(): import ModuleB global old_function MyGlobals.SomeNumber = 0 old_function = ModuleB.someClass.function ModuleB.someClass.function = someNewFunction File 2 has a class "someClass" and a class "someOthe...
[ "Well, it's fairly clear that you are using different versions of ModuleB. I would hazard a guess that even though you are running the code from a thumb drive, you have put ModuleB.py somewhere else in your PYTHONPATH and it is running that version on your computer, but not on your friend's. This is easy to check:\...
[ 2 ]
[]
[]
[ "module", "python", "python_module" ]
stackoverflow_0003471416_module_python_python_module.txt
Q: Sorting a python array opt=[] opt=["opt3","opt2","opt7","opt6","opt1"] for i in range(len(opt)): print opt[i] Output for the above is opt3,opt2,opt7,opt6,opt1 How to sort the above array in ascending order.. A: Use .sort() if you want to sort the original list. (opt.sort()) Use sorted() if you want a sor...
Sorting a python array
opt=[] opt=["opt3","opt2","opt7","opt6","opt1"] for i in range(len(opt)): print opt[i] Output for the above is opt3,opt2,opt7,opt6,opt1 How to sort the above array in ascending order..
[ "Use .sort() if you want to sort the original list. (opt.sort())\nUse sorted() if you want a sorted copy of it.\n", "print sorted(opt)\n", "Depends on whether or not you want a natural sort (which I think you do) or not.\nIf you use sorted() or .sort() you'll get:\n>>> opt = [\"opt3\", \"opt2\", \"opt7\", \"opt...
[ 8, 2, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003470436_python_sorting.txt
Q: memory size of Python data structure How do I find out the memory size of a Python data structure? I'm looking for something like: sizeof({1:'hello', 2:'world'}) It is great if it counts every thing recursively. But even a basic non-recursive result helps. Basically I want to get a sense of various implementation...
memory size of Python data structure
How do I find out the memory size of a Python data structure? I'm looking for something like: sizeof({1:'hello', 2:'world'}) It is great if it counts every thing recursively. But even a basic non-recursive result helps. Basically I want to get a sense of various implementation options like tuple v.s. list v.s. class i...
[ "Have a look at the sys.getsizeof function. According to the documentation, it returns the size of an object in bytes, as given by the object's __sizeof__ method.\nAs Daniel pointed out in a comment, it's not recursive; it only counts bytes occupied by the object itself, not other objects it refers to. This recipe ...
[ 26 ]
[]
[]
[ "data_structures", "memory", "memory_management", "python" ]
stackoverflow_0003471559_data_structures_memory_memory_management_python.txt
Q: Python project deployment design Here is the situation: the company that I'm working in right now gave me the freedom to work with either java or python to develop my applications. The company has mainly experience in java. I have decided to go with python, so they where very happy to ask me to give maintenance to...
Python project deployment design
Here is the situation: the company that I'm working in right now gave me the freedom to work with either java or python to develop my applications. The company has mainly experience in java. I have decided to go with python, so they where very happy to ask me to give maintenance to all the python projects/scripts relat...
[ "A package is a way of creating a module hierarchy: if you make a file called __init__.py in a directory, Python will treat that directory as a package and allow you to import its contents using dotted imports:\nspam \\\n __init__.py\n ham.py\n eggs.py\n\nimport spam.ham\n\nThe modules inside a pa...
[ 2, 2 ]
[]
[]
[ "project_layout", "python" ]
stackoverflow_0003471413_project_layout_python.txt
Q: Auto Increment While Building list in Python Here is what I have so far. Is there anyway, I can auto increment the list while it is being built? So instead of having all ones, I'd have 1,2,3,4.... possible = [] possible = [1] * 100 print possible Thanks, Noah A: possible = range(1, 101) Note that the end ...
Auto Increment While Building list in Python
Here is what I have so far. Is there anyway, I can auto increment the list while it is being built? So instead of having all ones, I'd have 1,2,3,4.... possible = [] possible = [1] * 100 print possible Thanks, Noah
[ "possible = range(1, 101)\n\nNote that the end point (101 in this case) is not part of the resulting list.\n", "Something like this?\nstart=1\ncount= 100\npossible = [num for num in range(start,start+count)]\nprint possible\n\n" ]
[ 13, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003471151_list_python.txt
Q: Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference? I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the...
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds a...
[ "It seems that Python 2.7 has introduced a total_seconds() method, which is what you were looking for, I believe!\n", "You can compute the difference in seconds.\ntotal_seconds = delta.days * 86400 + delta.seconds\n\nNo, you're no \"missing something\". It doesn't provide deltas in seconds. \n", "\nIt would b...
[ 21, 15, 5, 5 ]
[]
[]
[ "datetime", "python", "timedelta" ]
stackoverflow_0000500168_datetime_python_timedelta.txt
Q: how to get a descendant from parent entity I can't seem to find a quick answer on how to get Datastore descendants given a reference to the parent entity. Here's a quick example: # a person who has pets john=Person(**kwargs) # pets fluffy=Pet(parent=john, ...) rover=Pet(parent=john, ...) # lengthy details about...
how to get a descendant from parent entity
I can't seem to find a quick answer on how to get Datastore descendants given a reference to the parent entity. Here's a quick example: # a person who has pets john=Person(**kwargs) # pets fluffy=Pet(parent=john, ...) rover=Pet(parent=john, ...) # lengthy details about john that are accessed infrequently facts=Detai...
[ "You want to use an ancestor filter:\nkid_keys = db.Query(keys_only=True).ancestor(john).fetch(1000)\n\nAnd you can get just facts by specifying the type of facts:\nfacts_key = db.Query(Details, keys_only=True).ancestor(john).get()\n\nUsing get() instead of fetch() assumes that john will have only one Details child...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003471054_google_app_engine_python.txt
Q: Be my human compiler: What is wrong with this Python 2.5 code? My framework is raising a syntax error when I try to execute this code: from django.template import Template, TemplateSyntaxError try: Template(value) except TemplateSyntaxError as error: raise forms.ValidationError(error) ...
Be my human compiler: What is wrong with this Python 2.5 code?
My framework is raising a syntax error when I try to execute this code: from django.template import Template, TemplateSyntaxError try: Template(value) except TemplateSyntaxError as error: raise forms.ValidationError(error) return value And here's the error: from template_field impor...
[ "The alternate syntax except SomeException as err is new in 2.6. You should use except SomeException, err in 2.5.\n", "You can't have an empty try block like that in Python. If you just want to do nothing in the block (for prototyping code, say), use the pass keyword:\nfrom django.template import Template, Templa...
[ 17, 6, 4, 3, 1 ]
[]
[]
[ "django", "python", "syntax" ]
stackoverflow_0003471295_django_python_syntax.txt
Q: How to pass object_id to generic view object_detail in Django I'm using django.views.generic.list_detail.object_detail. According to the documentation the view takes the variable object_id. To do this I added the following to my urlconf: (r'^(?P<object_id>\d+)$', list_detail.object_detail, article_info), The abov...
How to pass object_id to generic view object_detail in Django
I'm using django.views.generic.list_detail.object_detail. According to the documentation the view takes the variable object_id. To do this I added the following to my urlconf: (r'^(?P<object_id>\d+)$', list_detail.object_detail, article_info), The above line is in a separate urlconf that is included in the main urlcon...
[ "I'll tackle your second question first. The ? character in this context is used to denote a named group in the regular expression. This is a custom extension to regular expressions provided by Python. (See the howto for examples)\nTo pass an object_id append it to the URL (in your case). Like this: ../foo/app/3 wh...
[ 3, 2, 1 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0003467121_django_django_urls_python_regex.txt
Q: Python lazy dictionary evaluation Python evangelists will say the reason Python doesn't have a switch statement is because it has dictionaries. So... how can I use a dictionary to solve this problem here? The problem is that all values are being evaluated some and raising exceptions depending on the input. This i...
Python lazy dictionary evaluation
Python evangelists will say the reason Python doesn't have a switch statement is because it has dictionaries. So... how can I use a dictionary to solve this problem here? The problem is that all values are being evaluated some and raising exceptions depending on the input. This is just a dumb example of a class that s...
[ "Yes, define small lambdas for these different options:\n def __mul__(self, other): \n scalar_times_scalar = lambda x,y: x*y\n scalar_times_seq = lambda x,y: [x*y_i for y_i in y]\n seq_times_scalar = lambda x,y: scalar_times_seq(y,x)\n seq_times_seq = lambda x,y: [x_i*y_i ...
[ 4, 1, 1 ]
[]
[]
[ "dictionary", "lazy_evaluation", "python", "switch_statement" ]
stackoverflow_0003471024_dictionary_lazy_evaluation_python_switch_statement.txt
Q: Create x lists in python dynamically (First, I chose to do this in Python because I never programmed in it and it would be good practice.) Someone asked me to implement a little "combination" program that basically outputs all possible combinations of a set of group of numbers. Example, if you have: (1,2,3) as th...
Create x lists in python dynamically
(First, I chose to do this in Python because I never programmed in it and it would be good practice.) Someone asked me to implement a little "combination" program that basically outputs all possible combinations of a set of group of numbers. Example, if you have: (1,2,3) as the first set, (4,5,6) as the second, and ...
[ "Ls = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nimport collections\nimport itertools\n\ndef products_by_even_count(seq):\n ret = collections.defaultdict(set)\n for p in itertools.product(*seq):\n n_even = sum(1 for n in p if n % 2 == 0)\n ret[n_even].add(p)\n return ret\n\nimport pprint\n# Calling d...
[ 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003472048_list_python.txt
Q: Number Guesser: Please Review and Make it More Pythonic I'm working on learning python, here is a simple program, I wrote: def guesser(var, num1,possible): if var == 'n': cutoff = len(possible)/2 possible = possible[0:cutoff] cutoff = possible[len(possible)/2] #print possible ...
Number Guesser: Please Review and Make it More Pythonic
I'm working on learning python, here is a simple program, I wrote: def guesser(var, num1,possible): if var == 'n': cutoff = len(possible)/2 possible = possible[0:cutoff] cutoff = possible[len(possible)/2] #print possible if (len(possible) == 1): print "Your Numb...
[ "Normally I would try to help with your code, but you have made it so way much too complicated that I think it would be easier for you to look at some code.\ndef guesser( bounds ):\n a, b = bounds\n mid = ( a + b ) // 2\n\n if a == b: return a\n\n if input( \"over {0}? \".format( mid ) ) == \"y\":\n ...
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003472124_python.txt
Q: What are the differences between the two Python 2.7 Mac OS X disk image installers? Python 2.7 has two different disk image installers for Mac OS X. My questions are: What are the differences between the two Python 2.7 disk image installers? Python 2.7 32-bit Mac OS X Installer Disk Image for Mac OS X 10.3 throu...
What are the differences between the two Python 2.7 Mac OS X disk image installers?
Python 2.7 has two different disk image installers for Mac OS X. My questions are: What are the differences between the two Python 2.7 disk image installers? Python 2.7 32-bit Mac OS X Installer Disk Image for Mac OS X 10.3 through 10.6 Python 2.7 PPC/i386/x86-64 Mac OS X Installer Disk Image for Mac OS X 10.5 or la...
[ "As others have pointed out, the second (64-bit) installer variant is new on python.org starting with 2.7 and future releases of 2.7 and 3.2 will have both 32-bit-only and a 32-/64-bit variants. The newer variant is an attempt to add out-of-the-box support from python.org for Intel 64-bit (x86_64) processes which ...
[ 3, 0, 0, 0 ]
[]
[]
[ "diskimage", "installation", "python" ]
stackoverflow_0003472349_diskimage_installation_python.txt
Q: How to get stdout into a string (Python) I need to capture the stdout of a process I execute via subprocess into a string to then put it inside a TextCtrl of a wx application I'm creating. How do I do that? EDIT: I'd also like to know how to determine when a process terminates A: From the subprocess documentatio...
How to get stdout into a string (Python)
I need to capture the stdout of a process I execute via subprocess into a string to then put it inside a TextCtrl of a wx application I'm creating. How do I do that? EDIT: I'd also like to know how to determine when a process terminates
[ "From the subprocess documentation:\nfrom subprocess import *\noutput = Popen([\"mycmd\", \"myarg\"], stdout=PIPE).communicate()[0]\n\n", "Take a look at the subprocess module.\nhttp://docs.python.org/library/subprocess.html\nIt allows you to do a lot of the same input and output redirection that you can do in th...
[ 10, 2 ]
[]
[]
[ "python", "stdout" ]
stackoverflow_0003472760_python_stdout.txt
Q: python generate SQL statement keywords by given lists I have below variables try to make an auto generating SQL statement in python _SQL_fields = ("ID", "NAME", "BIRTH", "SEX", "AGE") _add_SQL_desc_type = ("PRIMARY KEY AUTOINCREASEMENT",) _SQL_type = ("INT",'TEXT') _Value = ...
python generate SQL statement keywords by given lists
I have below variables try to make an auto generating SQL statement in python _SQL_fields = ("ID", "NAME", "BIRTH", "SEX", "AGE") _add_SQL_desc_type = ("PRIMARY KEY AUTOINCREASEMENT",) _SQL_type = ("INT",'TEXT') _Value = (1,'TOM',19700101,'M',40) bop = ["AND"] * (len(_SQL_fields...
[ "To obtain\n'(ID PRIMARY KEY AUTOINCREASEMENT INT, NAME TEXT, BIRTH, SEX, AGE)'\n\nyou can use izip_longest from itertools module in python.\nThen, to remove exception_fields in the obtain list, you can use set or list comprehension. \nl1 = [1, 2, 3, 4]\nl2 = [2, 3]\nl3 = list(set(l1) - set(l2))\nprint l3\n--> [1, ...
[ 0 ]
[]
[]
[ "keyword", "list", "python", "sql" ]
stackoverflow_0003466617_keyword_list_python_sql.txt
Q: PyAMF / Django - Flex class mapping errors I'm using PyAmf to communicate with a Flex app. But I keep getting errors. My model: from django.contrib.auth.models import User class Talent(User): street = models.CharField(max_length=100) street_nr = models.CharField(max_length=100) postal_code = models.Po...
PyAMF / Django - Flex class mapping errors
I'm using PyAmf to communicate with a Flex app. But I keep getting errors. My model: from django.contrib.auth.models import User class Talent(User): street = models.CharField(max_length=100) street_nr = models.CharField(max_length=100) postal_code = models.PositiveIntegerField() city = models.CharField...
[ "This is done using the IExternalizable interface.\n\nPyAMF Docs\nAdobe Docs\n\nIt lets you explicitly write and read objects. If this is similar to Java implicit serialization, it's not going to let you limit what is sent by default. I was unable to find any examples of this with PyAMF.\nBest post on Serialization...
[ 3, 1 ]
[]
[]
[ "apache_flex", "django", "pyamf", "python" ]
stackoverflow_0000856846_apache_flex_django_pyamf_python.txt
Q: Popen gives "File not found" Error (windows/python) I'm trying to run console commands via subprocess.Popen, and whenever I run it I get the windows "File not found" error, even when running the echo command. I am also using Popen inside a thread made with the thread module. Is that the problem? A: Instead ofD:\...
Popen gives "File not found" Error (windows/python)
I'm trying to run console commands via subprocess.Popen, and whenever I run it I get the windows "File not found" error, even when running the echo command. I am also using Popen inside a thread made with the thread module. Is that the problem?
[ "Instead ofD:\\Program Files\\Steam\\steamapps\\terabytest\\sourcesdk\\bin\\orangebox\\bin\\vbsp.exe, useD:/Program Files/Steam/steamapps/terabytest/sourcesdk/bin/orangebox/bin/vbsp.exe\nThis eliminates any complications with backslashes inside quotes.\n", "echo is not an executable, it's an internal command insi...
[ 4, 3 ]
[]
[]
[ "popen", "python", "windows" ]
stackoverflow_0003472862_popen_python_windows.txt
Q: Resuable model members in django I have a django model like this: class Something(models.Model): title = models.CharField(max_length=200, default=u'') text = models.CharField(max_length=250, default=u'', blank=True) photo = models.ImageField(upload_to=u'something') def photo_thumb(self): ...
Resuable model members in django
I have a django model like this: class Something(models.Model): title = models.CharField(max_length=200, default=u'') text = models.CharField(max_length=250, default=u'', blank=True) photo = models.ImageField(upload_to=u'something') def photo_thumb(self): if self.photo: return u...
[ "I agree with @Gintautas. The general rule of thumb is to create an abstract model class if you need to reuse model fields and meta options; use a simple class if you only need to reuse other properties and methods.\nIn your case I'd go with the abstract class (because of the photo model field):\nclass PhotoModels(...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "django_models", "dry", "inheritance", "python" ]
stackoverflow_0003472811_django_django_models_dry_inheritance_python.txt
Q: How can I display native accents to languages in console in windows? print "Español\nPortuguês\nItaliano".encode('utf-8') Errors: Traceback (most recent call last): File "", line 1, in print "Español\nPortuguês\nItaliano".encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in po...
How can I display native accents to languages in console in windows?
print "Español\nPortuguês\nItaliano".encode('utf-8') Errors: Traceback (most recent call last): File "", line 1, in print "Español\nPortuguês\nItaliano".encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 4: ordinal not in range(128) I'm trying to make a multilingual con...
[ "Short answer:\n# -*- coding: utf-8 -*-\nprint u\"Español\\nPortuguês\\nItaliano\".encode('utf-8')\n\nThe first line tells Python that your file is encoded in UTF-8 (your editor must use the same settings) and this line should always be on the beginning of your file.\nAnother thing is that Python 2 knows two differ...
[ 3, 2, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003473166_python_unicode.txt
Q: Python - Sum of numbers I am trying to sum all the numbers up to a range, with all the numbers up to the same range. I am using python: limit = 10 sums = [] for x in range(1,limit+1): for y in range(1,limit+1): sums.append(x+y) This works just fine, however, because of the nested loops, if the limit i...
Python - Sum of numbers
I am trying to sum all the numbers up to a range, with all the numbers up to the same range. I am using python: limit = 10 sums = [] for x in range(1,limit+1): for y in range(1,limit+1): sums.append(x+y) This works just fine, however, because of the nested loops, if the limit is too big it will take a lot ...
[ "[x + y for x in xrange(limit + 1) for y in xrange(x + 1)]\n\nThis still performs just as many calculations but will do it about twice as fast as a for loop.\nfrom itertools import combinations\n\n(a + b for a, b in combinations(xrange(n + 1, 2)))\n\nThis avoids a lot of duplicate sums. I don't know if you want to ...
[ 2, 1, 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0003473413_for_loop_loops_python.txt
Q: Python design question (Can/should decorators be used in this case?) I have a problem that can be simplified as follows: I have a particular set of objects that I want to modify in a particular way. So, it's possible for me to write a function that modifies a single object and then create a decorator that applies ...
Python design question (Can/should decorators be used in this case?)
I have a problem that can be simplified as follows: I have a particular set of objects that I want to modify in a particular way. So, it's possible for me to write a function that modifies a single object and then create a decorator that applies that function to all of the objects in the set. So, let's suppose I have ...
[ "Apply the decorator manually to the function once and save the result in a new name.\ndef modify_one(obj):\n ...\n\nmodify_some = modify_all(modify_one)\nmodify_some([a, b, c])\nmodify_one(d)\n\n", "Decorators are meant for when you apply a higher-order function (HOF) in the specific form\ndef f ...\n\nf = HO...
[ 2, 2, 1, 0 ]
[ "In your particular case I'd consider using argument unpacking. This can be done with only a slight modification of your existing code:\ndef broadcast(f):\n def fun(*objs):\n for o in objs:\n f(o)\n return fun\n\n@broadcast\ndef modify(obj):\n # Modify obj in some way.\n\nmodify(*all_my_o...
[ -1 ]
[ "decorator", "python" ]
stackoverflow_0003473746_decorator_python.txt
Q: Which Exception for notifying that subclass should implement a method? Suppose I want to create an abstract class in Python with some methods to be implemented by subclasses, for example: class Base(): def f(self): print "Hello." self.g() print "Bye!" class A(Base): def g(self): ...
Which Exception for notifying that subclass should implement a method?
Suppose I want to create an abstract class in Python with some methods to be implemented by subclasses, for example: class Base(): def f(self): print "Hello." self.g() print "Bye!" class A(Base): def g(self): print "I am A" class B(Base): def g(self): print "I am B...
[ "In Python 2.6 and better, you can use the abc module to make Base an \"actually\" abstract base class:\nimport abc\n\nclass Base:\n __metaclass__ = abc.ABCMeta\n @abc.abstractmethod\n def g(self):\n pass\n def f(self): # &c\n\nthis guarantees that Base cannot be instantiated -- and neither can a...
[ 15, 2, 0 ]
[]
[]
[ "abstract_base_class", "coding_style", "design_patterns", "exception", "python" ]
stackoverflow_0003473667_abstract_base_class_coding_style_design_patterns_exception_python.txt
Q: Problems with my BaseHTTPServer I am trying to create my own functions in the subclass of BaseHTTPRequestHandler as such class Weblog(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): ...
Problems with my BaseHTTPServer
I am trying to create my own functions in the subclass of BaseHTTPRequestHandler as such class Weblog(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): """Respond to a GET request.""" ...
[ "To call something in the current class, you should use self.method_name()\ndef do_GET(self):\n \"\"\"Respond to a GET request.\"\"\"\n if self.path == '/':\n self.do_index()\n elif self.path == '/timestamp':\n self.do_entry()\n elif self.path == '/post':\n self.do_post_form()\n\n" ...
[ 2 ]
[]
[]
[ "basehttpserver", "python" ]
stackoverflow_0003474045_basehttpserver_python.txt
Q: Import fails with a strange error I get: TemplateSyntaxError at /blog/post/test Caught NameError while rendering: global name 'forms' is not defined for this code: forms.py from dojango.forms import widgets from django.contrib.comments.forms import CommentForm from Website.Comments.models import PageComment ...
Import fails with a strange error
I get: TemplateSyntaxError at /blog/post/test Caught NameError while rendering: global name 'forms' is not defined for this code: forms.py from dojango.forms import widgets from django.contrib.comments.forms import CommentForm from Website.Comments.models import PageComment class PageCommentForm(CommentForm): ...
[ "put the following in __init__.py:\nimport forms\n\n", "This is a bug in dojango.\nI will report it.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python", "python_import" ]
stackoverflow_0003433066_django_python_python_import.txt
Q: In django 1.2.1 how can I get something like the old .as_sql? In past versions of django you could construct a queryset and then do .as_sql() on it to find out the final query. in Django 1.2.1 there is a function ._as_sql() which returns something similar, but not the same. In past versions: qs=Model.objects.all()...
In django 1.2.1 how can I get something like the old .as_sql?
In past versions of django you could construct a queryset and then do .as_sql() on it to find out the final query. in Django 1.2.1 there is a function ._as_sql() which returns something similar, but not the same. In past versions: qs=Model.objects.all() qs.as_sql() ====> SELECT `model_table.id`, `model_table.name`, `m...
[ "qs=Model.objects.all()\nqs.query.as_sql() \n\nShould do the job as it is shown here\nEDIT:\nI just try it and get the same error. \nqs=Model.objects.all()\nprint qs.query\n\nthis must give you what you want (:\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003474505_django_python.txt
Q: Get a count for a pattern using python In the following how to count the number of times that __TEXT__ appears in the variable sing python a="This is __TEXT__ message to test __TEXT__ message" A: a.count("__TEXT__")
Get a count for a pattern using python
In the following how to count the number of times that __TEXT__ appears in the variable sing python a="This is __TEXT__ message to test __TEXT__ message"
[ "a.count(\"__TEXT__\")\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003474690_python.txt
Q: How to parse data in a variable length delimited file? I have a text file which does not confirm to standards. So I know the (end,start) positions of each column value. Sample text file : # # # # Techy Inn Val NJ Found the position of # using this code : 1 f = open('sample.txt', 'r') 2 i = 0 3 posi...
How to parse data in a variable length delimited file?
I have a text file which does not confirm to standards. So I know the (end,start) positions of each column value. Sample text file : # # # # Techy Inn Val NJ Found the position of # using this code : 1 f = open('sample.txt', 'r') 2 i = 0 3 positions = [] 4 for line in f: 5 if line.find('#') > 0:...
[ "Here's a way to read fixed width fields using regexp\n>>> import re\n>>> s=\"Techy Inn Val NJ\"\n>>> var1,var2,var3,var4 = re.match(\"(.{5}) (.{3}) (.{3}) (.{2})\",s).groups()\n>>> var1\n'Techy'\n>>> var2\n'Inn'\n>>> var3\n'Val'\n>>> var4\n'NJ'\n>>> \n\n", "Off the top of my head:\nf = open(.......)\nheader = f....
[ 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "file", "python", "text" ]
stackoverflow_0003472884_file_python_text.txt
Q: Python: traverse tree adding html list (ul) I have this python code that will traverse a tree structure. I am trying to add ul and li tags to the function but I am not very succesful. I though I was able to keep the code clean without to many conditionals but now I ain't so sure anymore. def findNodes(nodes): ...
Python: traverse tree adding html list (ul)
I have this python code that will traverse a tree structure. I am trying to add ul and li tags to the function but I am not very succesful. I though I was able to keep the code clean without to many conditionals but now I ain't so sure anymore. def findNodes(nodes): def traverse(ns): for child in ns: ...
[ "I removed the unused level parameter. Adding in any sort of text is left as an exercise to the reader.\ndef findNodes(nodes):\n def traverse(ns):\n if not ns:\n return ''\n\n ret = ['<ul>']\n for child in ns:\n ret.extend(['<li>', traverse(child.Children), '</li>'])\n ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003474684_python.txt
Q: What is the difference between getiterator() and iter() wrt to lxml As the question says, what would be the difference between: x.getiterator() and x.iter(), where x is an ElementTree or an Element? Cause it seems to work for both, I have tried it. If I am wrong somewhere, correct me please. A: The Python docume...
What is the difference between getiterator() and iter() wrt to lxml
As the question says, what would be the difference between: x.getiterator() and x.iter(), where x is an ElementTree or an Element? Cause it seems to work for both, I have tried it. If I am wrong somewhere, correct me please.
[ "The Python documentation for ElementTree states that the getiterator() method has been deprecated starting with version 2.7 and says to use Element.iter(). The lxml API documentation states the same but also mentions that the implementation of getiterator() in lxml diverges from the original ElementTree behavior. ...
[ 8, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003077010_lxml_python.txt
Q: Reading a SOAP header to a SOAPpy response? How can I read s SOAP header from a SOAPpy response? A: You can't, without modifying SOAPy. When you call a SOAP method, SOAPy runs its own request function, which returns a valid HTTPResponse object. However, it does not retain that object; within the same method call...
Reading a SOAP header to a SOAPpy response?
How can I read s SOAP header from a SOAPpy response?
[ "You can't, without modifying SOAPy.\nWhen you call a SOAP method, SOAPy runs its own request function, which returns a valid HTTPResponse object. However, it does not retain that object; within the same method call, it parses the body, and returns the result. \nIn order to alter this behaviour, you'll want to look...
[ 0 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0003474809_python_soap_soappy.txt
Q: How do I Handle Database changes and port my data? Example, for web applications using Turbogears and SQLAlchemy. Every time I update my data model, I need to delete my database and recreate it. Is there an easy way to update the production database? Do I have to write a custom script that transfers all the produ...
How do I Handle Database changes and port my data?
Example, for web applications using Turbogears and SQLAlchemy. Every time I update my data model, I need to delete my database and recreate it. Is there an easy way to update the production database? Do I have to write a custom script that transfers all the production data into a new database model? Or is there an ea...
[ "These database changes are called schema migrations. For SQLAlchemy, sqlalchemy-migrate is the defacto standard. Other ORMs/abstraction layers have similar solutions, e.g. South for Django.\n", "You can ALTER TABLE, i think that's the easiest way.\n" ]
[ 4, 1 ]
[]
[]
[ "database", "python", "sqlalchemy", "turbogears" ]
stackoverflow_0003474754_database_python_sqlalchemy_turbogears.txt
Q: Is it possible to combine annotations with defer/only in django 1.2.1? I have two simple models: Book, and Author Each Book has one Author, linked through a foreignkey. Things work normally until I try to use defer/only on an annotation: authors=Author.objects.all().annotate(bookcount=Count('books')) that works. ...
Is it possible to combine annotations with defer/only in django 1.2.1?
I have two simple models: Book, and Author Each Book has one Author, linked through a foreignkey. Things work normally until I try to use defer/only on an annotation: authors=Author.objects.all().annotate(bookcount=Count('books')) that works. The query looks like: select table_author.name, table_author.birthday, COUN...
[ "Well, this would seem to be a bug. There's already a ticket, but it hasn't had much attention for a while. Might be worth making a post to the django-developers Google group to chivvy things along.\n" ]
[ 1 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0003474728_django_django_queryset_python.txt
Q: How to create a floor function with a "step" argument I would like to create a function floor(number, step), which acts like : floor(0, 1) = 0 floor(1, 1) = 1 floor(1, 2) = 0 floor(5, 2) = 4 floor(.8, .25) = .75 What is the better way to do something like that ? Thanks. A: You could do something like floor( val...
How to create a floor function with a "step" argument
I would like to create a function floor(number, step), which acts like : floor(0, 1) = 0 floor(1, 1) = 1 floor(1, 2) = 0 floor(5, 2) = 4 floor(.8, .25) = .75 What is the better way to do something like that ? Thanks.
[ "You could do something like floor( val / step ) * step\n", "what you want is basically the same as\nstep * (x // step)\nisn't ?\n", "Something along the lines of the code below ought to do the job.\ndef stepped_floor (n, step=1):\n return n - (n % step)\n\n" ]
[ 6, 2, 1 ]
[]
[]
[ "algorithm", "math", "python" ]
stackoverflow_0003472618_algorithm_math_python.txt
Q: Python, Threads, the GIL, and C++ Is there some way to make boost::python control the Python GIL for every interaction with python? I am writing a project with boost::python. I am trying to write a C++ wrapper for an external library, and control the C++ library with python scripts. I cannot change the external...
Python, Threads, the GIL, and C++
Is there some way to make boost::python control the Python GIL for every interaction with python? I am writing a project with boost::python. I am trying to write a C++ wrapper for an external library, and control the C++ library with python scripts. I cannot change the external library, only my wrapper program. (I a...
[ "I found a really obscure post on the mailing list that said to use \nPyEval_InitThreads();\nin BOOST_PYTHON_MODULE\nand that actually seemed to stop the crashes.\nIts still a crap shoot whether it the program reports all the messages it got or not. If i send 2000, most of the time it says it got 2000, but sometim...
[ 4, 4, 2 ]
[]
[]
[ "boost_python", "c", "c++", "multithreading", "python" ]
stackoverflow_0001934898_boost_python_c_c++_multithreading_python.txt
Q: I have trouble installing the django-socialregistration app! I'm a Django amateur, and have problems getting django-registration to work. I followed the installation instructions on their website, but for someone like me these instructions are not 100% clear as to what I should be doing. Here is what I've done: I...
I have trouble installing the django-socialregistration app!
I'm a Django amateur, and have problems getting django-registration to work. I followed the installation instructions on their website, but for someone like me these instructions are not 100% clear as to what I should be doing. Here is what I've done: I installed the oauth2 and python-openid packages using pip. I then...
[ "\nPlease add the django.core.context_processors.request context processors to your settings.\n\nHave you done that?\nYou'll need to change TEMPLATE_CONTEXT_PROCESSORS to include django.core.context_processors.request.\n", "I've found the problem. When my view renders the template, it needs to pass the RequestCon...
[ 3, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003465371_django_python.txt
Q: sqlalchemy Oracle REF CURSOR I am using sqlalchemy for connection pooling only (need to call existing procs) and want to return a REF CURSOR which is an out parameter. There seems to be no cursor in sqlalchemy to do this. Any advice greatly appreciated. A: Gut feel - you may have to dive down a lower level than ...
sqlalchemy Oracle REF CURSOR
I am using sqlalchemy for connection pooling only (need to call existing procs) and want to return a REF CURSOR which is an out parameter. There seems to be no cursor in sqlalchemy to do this. Any advice greatly appreciated.
[ "Gut feel - you may have to dive down a lower level than SQLAlchemy, perhaps to the underlying cx_oracle classes.\nFrom an answer provided by Gerhard Häring on another forum :\nimport cx_Oracle \n\ncon = cx_Oracle.connect(\"me/secret@tns\") \ncur = con.cursor() \noutcur = con.cursor() \ncur.execute(\"\"\" \nBEGIN \...
[ 0 ]
[]
[]
[ "oracle", "python", "sqlalchemy" ]
stackoverflow_0003474152_oracle_python_sqlalchemy.txt
Q: Design Golf: modeling an Address in appengine, aka an AddressProperty? Today I was refactoring some code and revisited an old friend, an Address class (see below). It occurred to me that, in our application, we don't do anything special with addresses-- no queries, only lightweight validation and frequent seriali...
Design Golf: modeling an Address in appengine, aka an AddressProperty?
Today I was refactoring some code and revisited an old friend, an Address class (see below). It occurred to me that, in our application, we don't do anything special with addresses-- no queries, only lightweight validation and frequent serialization to JSON. The only "useful" properties from the developer point-of-vi...
[ "Given that you don't need to query on addresses, and given they tend to be fairly small (as opposed to, say, a large binary blob), I would suggest going with the latter. It'll save space and time (fetching it) - the only real downside is that you have to implement the property yourself.\n", "If you wanted to be ...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003471798_google_app_engine_python.txt
Q: Static variable inheritance in Python I'm writing Python scripts for Blender for a project, but I'm pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of code I am currently working on: class panelToggle(bpy.types.Operator): active = False def inv...
Static variable inheritance in Python
I'm writing Python scripts for Blender for a project, but I'm pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of code I am currently working on: class panelToggle(bpy.types.Operator): active = False def invoke(self, context, event): self.act...
[ "use type(self) for access to class attributes\n>>> class A(object):\n var = 2\n def write(self):\n print type(self).var\n>>> class B(A):\n pass\n>>> B().write()\n2\n>>> B.var = 3\n>>> B().write()\n3\n>>> A().write()\n2\n\n", "You can access active through the class it belongs to:\nif panelToggle.active:\n #...
[ 22, 4 ]
[]
[]
[ "blender", "inheritance", "python", "static", "syntax" ]
stackoverflow_0003475488_blender_inheritance_python_static_syntax.txt
Q: how to return the element tree instance I want to generate a xml file. I have written a xml_generator method. When /xxx url hits i call this generator function. how should i return this Because returning instance of generator function creates an error. A: if you meant you're returning a function, it will be erro...
how to return the element tree instance
I want to generate a xml file. I have written a xml_generator method. When /xxx url hits i call this generator function. how should i return this Because returning instance of generator function creates an error.
[ "if you meant you're returning a function, it will be erroneous when you're actually trying to return the results of the function. I.e.: my_function instead of my_function().\n" ]
[ 3 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0003475563_elementtree_python.txt
Q: Difference between save() and put()? What is the difference between Mymodel.save() and Mymodel.put() in appengine with python? I know that save is used in django but does is work with appengine models too? A: save() is a (deprecated) alias for put(). They work exactly equivalently - in fact, they're the same fun...
Difference between save() and put()?
What is the difference between Mymodel.save() and Mymodel.put() in appengine with python? I know that save is used in django but does is work with appengine models too?
[ "save() is a (deprecated) alias for put(). They work exactly equivalently - in fact, they're the same function!\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003476152_google_app_engine_python.txt
Q: append columns of data I have tab delimited data that I am exporting a select few columns into another file. I have: a b c d 1 2 3 4 5 6 7 8 9 10 11 12 and I get: b, d b, d 2, 4 b, d 2, 4 6, 8 b, d 2, 4 6, 8 10, 12 ...... I want: b, d 2, 4 6, 8 10, 12 My code is f=open('data.txt', 'r') f1=open('newdata.txt'...
append columns of data
I have tab delimited data that I am exporting a select few columns into another file. I have: a b c d 1 2 3 4 5 6 7 8 9 10 11 12 and I get: b, d b, d 2, 4 b, d 2, 4 6, 8 b, d 2, 4 6, 8 10, 12 ...... I want: b, d 2, 4 6, 8 10, 12 My code is f=open('data.txt', 'r') f1=open('newdata.txt','w') t=[] for line in f.rea...
[ "The indentation is wrong so you are writing the entire array t on every iteration instead of only at the end. Change it to this:\nt=[]\nfor line in f.readlines():\n line = line.split('\\t')\n t.append('%s,%s\\n' % (line[0], line[3]))\nf1.writelines(t)\n\nAlternatively you could write the lines one at a time ...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003476161_python.txt
Q: How do I cache a list/dictionary in Pylons? On a website I'm making, there's a section that hits the database pretty hard. Harder than I want. The data that's being retrieved is all very static. It will rarely change. So I want to cache it. I came across http://wiki.pylonshq.com/display/pylonsdocs/Caching+in+Templ...
How do I cache a list/dictionary in Pylons?
On a website I'm making, there's a section that hits the database pretty hard. Harder than I want. The data that's being retrieved is all very static. It will rarely change. So I want to cache it. I came across http://wiki.pylonshq.com/display/pylonsdocs/Caching+in+Templates+and+Controllers and had a good read have bee...
[ "As alternative of traditional cache you can use app globals variables. Once on server startup load data to variable and then use data in you actions or direct in templates.\nhttp://pylonsbook.com/en/1.1/exploring-pylons.html#app-globals-object\nAlso you can code some action to update this global variable through t...
[ 1, 1 ]
[]
[]
[ "caching", "pylons", "python" ]
stackoverflow_0003473864_caching_pylons_python.txt
Q: Is there any way to create an app for python3 script? Py2app will create the app for python2. But for python3? Has anyone succeeded in creating an app for python3 script? Any clue would be helpful for my script in creating that. A: cx_freeze Unlike these two tools, cx_Freeze is cross platform and should work...
Is there any way to create an app for python3 script?
Py2app will create the app for python2. But for python3? Has anyone succeeded in creating an app for python3 script? Any clue would be helpful for my script in creating that.
[ "cx_freeze\n\nUnlike these two tools, cx_Freeze is\n cross platform and should work on any\n platform that Python itself works on.\n It requires Python 2.3 or higher since\n it makes use of the zip import\n facility which was introduced in that\n version.\n\n", "Py2app also create app for python3 script.\n"...
[ 1, 0, 0 ]
[]
[]
[ "macos", "python", "python_3.x" ]
stackoverflow_0003412796_macos_python_python_3.x.txt
Q: Is there a python equivalent of the prefuse visualization toolkit? The prefuse visualization toolkit is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs. A: I know this is not exactly python, but you could use pre...
Is there a python equivalent of the prefuse visualization toolkit?
The prefuse visualization toolkit is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.
[ "I know this is not exactly python, but you could use prefuse in python through jython\nSomething along the lines of:\nAdd prefuse to your path:\nexport JYTHONPATH=$JYTHONPATH:prefuse.jar\nand\n>>> import prefuse\nfrom your jython machinery\nthis guy has an example of using prefuse from jython here\n", "You might...
[ 6, 3, 2, 1, 0, 0 ]
[ "MayaVi\n" ]
[ -1 ]
[ "prefuse", "python", "visualization" ]
stackoverflow_0000591839_prefuse_python_visualization.txt
Q: Intelligent date range parsing of human input? Has anyone come across a script / cl app written in any language that handles the parsing of human-entered dates well? I'd love to be able to parse, for example: "3 to 4 weeks" "2 - 3 days" "3 weeks to 2 months" A: The Chronic gem for ruby will allow you to express...
Intelligent date range parsing of human input?
Has anyone come across a script / cl app written in any language that handles the parsing of human-entered dates well? I'd love to be able to parse, for example: "3 to 4 weeks" "2 - 3 days" "3 weeks to 2 months"
[ "The Chronic gem for ruby will allow you to express dates in a natural form.\nSome examples of supported forms (from the documentation)\n\n thursday\n november\n summer\n friday 13:00\n mon 2:35\n 4pm\n yesterday at 4:00\n last friday at 20:00\n last week tuesday\n tomorrow at 6:45pm\n afternoon yesterda...
[ 4, 0 ]
[]
[]
[ "coldfusion", "javascript", "php", "python", "ruby" ]
stackoverflow_0003473830_coldfusion_javascript_php_python_ruby.txt