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: Represent node relationship using Python NetworkX I have around 200K nodes and their relationship in a XML file as follows: node_A - node_B direct, node_A - node_G inverse, node_A - node_H direct, node_A - node_X inverse, node_A - node_Y direct I need to model the nodes and their relationship in ...
Represent node relationship using Python NetworkX
I have around 200K nodes and their relationship in a XML file as follows: node_A - node_B direct, node_A - node_G inverse, node_A - node_H direct, node_A - node_X inverse, node_A - node_Y direct I need to model the nodes and their relationship in the XML file using Python NetworkX graph data structure...
[ "You need a parser for doing this. Take a look at pyparsing. \n" ]
[ 0 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0005684678_networkx_python.txt
Q: Pure virtual function call I'm using boost.python to make python-modules written in c++. I have some base class with pure virtual functions which I have exported like this: class Base { virtual int getPosition() = 0; }; boost::python::class_<Base>("Base") .def("GetPosition", boost::python::pure_virtual(&Ba...
Pure virtual function call
I'm using boost.python to make python-modules written in c++. I have some base class with pure virtual functions which I have exported like this: class Base { virtual int getPosition() = 0; }; boost::python::class_<Base>("Base") .def("GetPosition", boost::python::pure_virtual(&Base::getPosition)); in Python I ...
[ "This error happens when a constructor or a destructor directly or indirectly calls a pure virtual member.\n(Remember that during constructor and destructor execution, the dynamic type is the constructed/destructed type and so virtual members are resolved for that type).\n", "A \"pure virtual function\" is a func...
[ 4, 1 ]
[]
[]
[ "boost_python", "c++", "pure_virtual", "python" ]
stackoverflow_0005688294_boost_python_c++_pure_virtual_python.txt
Q: Django get_absolute_url with ForeignKey parameter not working I am using the get_absolute_url method to get the url for a dynamic query, however when the link is displayed, it only shows the first parameter and not the second in the get_absolute_url method. It only does this when I use the ForeignKey of the model ...
Django get_absolute_url with ForeignKey parameter not working
I am using the get_absolute_url method to get the url for a dynamic query, however when the link is displayed, it only shows the first parameter and not the second in the get_absolute_url method. It only does this when I use the ForeignKey of the model as the first parameter. Below is the code. class Topic(models.Model...
[ "def get_absolute_url(self):\n return '/forums/%s/%s/' % (str(self.forum_id.pk), self.topic_id)\n\nedit: jerzyk comment mentions these other points:\n\nusing @permalink with get_absolute_url and reversing the url using the view and arguments so you don't have to hardcode the urls. \nusing _id instead of .pk\ndef...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005688276_django_python.txt
Q: How to convert a string properly instead of MutableString Im trying to incorporate my encryption program into a chat program. But i cant pass a MutableString with Socket. So how would I properly covert my MutableString into a proper string? import sys from UserString import MutableString def GetMode(): while Tru...
How to convert a string properly instead of MutableString
Im trying to incorporate my encryption program into a chat program. But i cant pass a MutableString with Socket. So how would I properly covert my MutableString into a proper string? import sys from UserString import MutableString def GetMode(): while True: print '\n(E)ncrypt Or (D)ecrypt?' Mode = raw_input()...
[ "First of all, as the MutableString documentation states: \n\nIt should be noted that these classes are highly inefficient compared to real string or Unicode objects; this is especially the case for MutableString.\n\nand most importantly:\n\nThe main intention of this class is to serve as an educational example for...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005688338_python.txt
Q: Python & FreeBSD: threading.currentThread().ident returns same value even in different processes As the title says, different calls to threading.currentThread().ident returns 34382823872, even in different processes. (Using Python 3.1 & FreeBSD) Is it FreeBSD's problem with python threads or not? A: Are you test...
Python & FreeBSD: threading.currentThread().ident returns same value even in different processes
As the title says, different calls to threading.currentThread().ident returns 34382823872, even in different processes. (Using Python 3.1 & FreeBSD) Is it FreeBSD's problem with python threads or not?
[ "Are you testing this in the REPL? Or in an actual program? I ask because when I ran the below using the REPL, I got the same result, but when I ran the same as a script, the threads had different identifiers. \nimport threading\n\ndef thid():\n print threading.currentThread().ident\n\nt1 = threading.Thread(targ...
[ 4 ]
[]
[]
[ "freebsd", "multithreading", "python" ]
stackoverflow_0005688503_freebsd_multithreading_python.txt
Q: Help me speed-up this code - Python Guys i am writing this program that goes through list of tweets and returns words which was use the most. I want to make it faster but I wonder if you can help point out some problems or areas which i can improve the speed. thanks see code below #import string import re from...
Help me speed-up this code - Python
Guys i am writing this program that goes through list of tweets and returns words which was use the most. I want to make it faster but I wonder if you can help point out some problems or areas which i can improve the speed. thanks see code below #import string import re from string import punctuation from operator ...
[ "if (len(rawline) == 0):\n\ncould be written as\nif rawline:\n\nYou should never use len(rawline) - 1 as an index, just use rawline[-1].\nI don't know why you use re.split(), when you could just do linestip.lower().split('\\t').\nDon't use dailyMsg.has_key(date), use date in dailyMsg.\nWhen you iterate over tweetsB...
[ 7, 1, 0 ]
[]
[]
[ "algorithm", "dictionary", "performance", "python", "readlines" ]
stackoverflow_0005667132_algorithm_dictionary_performance_python_readlines.txt
Q: Is there something wrong with my Python code? (functions) #tasks.py from celery.decorators import task @task() def add(x, y): add.delay(1, 9) return x + y >>> import tasks >>> res = tasks.add.delay(5, 2) >>> res.result() 7 If I run this code, I expect tasks to be continously added to the queue. But it'...
Is there something wrong with my Python code? (functions)
#tasks.py from celery.decorators import task @task() def add(x, y): add.delay(1, 9) return x + y >>> import tasks >>> res = tasks.add.delay(5, 2) >>> res.result() 7 If I run this code, I expect tasks to be continously added to the queue. But it's not! Only the first task (5,2) gets added to the queue and pr...
[ "As far as I can see, a periodic_task decorator is creating preiodic tasks, task creates just one task. And delay just executes it asynchronically.\nYou should just use periodic_task, instead of recursion.\n", "add inside function body refers to original function, not its decorated version.\nIf you just need to r...
[ 0, 0, 0 ]
[]
[]
[ "celery", "django", "python", "queue", "rabbitmq" ]
stackoverflow_0004552388_celery_django_python_queue_rabbitmq.txt
Q: Qt or EFL for multi-platform Python application When chatting in IRC yesterday about the possibility to use P(C)ython instead of D for multi-platform GUI application, someone suggested me Enlightenment Foundation Libraries (EFL). We have researched a bit about it and considering we would like to target some mobile...
Qt or EFL for multi-platform Python application
When chatting in IRC yesterday about the possibility to use P(C)ython instead of D for multi-platform GUI application, someone suggested me Enlightenment Foundation Libraries (EFL). We have researched a bit about it and considering we would like to target some mobile-platform in the future as well, EFL looks as nice al...
[ "EFL looks good and promising, especially its widget toolkit which can do very smart things when resizing windows, but there are problems with it: first, it comes in a very-beta quality. Second, the widgets will look quite unfamiliar for the users. Qt is mature and stable, and it adapts to the platform look and fee...
[ 2 ]
[]
[]
[ "pyqt", "pyside", "python", "qt" ]
stackoverflow_0005685176_pyqt_pyside_python_qt.txt
Q: Iteration through all 1 dimensional subarrays of a multi-dimensional array What is the fastest way to iterate through all one dimensional sub-arrays of an n dimensional array in python. For example consider the 3-D array: import numpy as np a = np.arange(24) a = a.reshape(2,3,4) The desired sequence of yields fr...
Iteration through all 1 dimensional subarrays of a multi-dimensional array
What is the fastest way to iterate through all one dimensional sub-arrays of an n dimensional array in python. For example consider the 3-D array: import numpy as np a = np.arange(24) a = a.reshape(2,3,4) The desired sequence of yields from the iterator is : a[:,0,0] a[:,0,1] .. a[:,2,3] a[0,:,0] .. a[1,:,3] a[0,0,:]...
[ "Here is a compact implementation of such an iterator:\ndef iter1d(a):\n return itertools.chain.from_iterable(\n numpy.rollaxis(a, axis, a.ndim).reshape(-1, dim)\n for axis, dim in enumerate(a.shape))\n\nThis will yield the subarrays in the order you gave in your post:\nfor x in iter1d(a):\n pri...
[ 10, 5, 0 ]
[]
[]
[ "multidimensional_array", "numpy", "python" ]
stackoverflow_0005687362_multidimensional_array_numpy_python.txt
Q: PyQt signals connect but do not invoke methods.. (PyQt4.8, Python 3.2) Hey guys, i know the question doesn't make it clear enough (couldn't find how to explain the prob in a single line). I'm working on a project where i have a centralized gui included in a main class, with various components of the project made o...
PyQt signals connect but do not invoke methods.. (PyQt4.8, Python 3.2)
Hey guys, i know the question doesn't make it clear enough (couldn't find how to explain the prob in a single line). I'm working on a project where i have a centralized gui included in a main class, with various components of the project made of composed objects of other classes (coded in separate files). To keep excha...
[ "Indeed, the question is far too vague IMHO. Without a concrete, minimal code sample that demonstrates the problem it will be very hard to help you.\nI want to address one troubling thing you wrote though:\n\nto keep exchanging data, each object\n has the object of the main class\n composed in them as well\n\nThi...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "python_3.x", "signals_slots" ]
stackoverflow_0005688666_pyqt_pyqt4_python_python_3.x_signals_slots.txt
Q: counting rows returned in postgresql I need to count the number of rows returned from database.By using following code rv = plpy.execute("SELECT * FROM AA where name = 'active '") rv[0]["id"] works when some values are returned but I need to check if no values are returned: Can someone help please. A: Why do...
counting rows returned in postgresql
I need to count the number of rows returned from database.By using following code rv = plpy.execute("SELECT * FROM AA where name = 'active '") rv[0]["id"] works when some values are returned but I need to check if no values are returned: Can someone help please.
[ "Why don't you just check the size of the rv array?\n", "Why dont you use -\nSELECT Count(*) as rowCount FROM AA where name = 'active'\n\nThis will return you the number of rows from the query. If there are no rows, then it will return 0.\n", "In PL/Python, the way to get the result size is\nrv.nrows\n\nSee the...
[ 4, 3, 3, -1 ]
[]
[]
[ "postgresql", "python", "rowcount", "sql" ]
stackoverflow_0005165284_postgresql_python_rowcount_sql.txt
Q: can any one help figure this out using python? Write a function that takes three arguments: a file-to-read, a file-to-write, and a word (string). It then reads lines from the text file-to-read and writes out only those lines containing the word into the file-to-write. Sample input/output files attached at the end...
can any one help figure this out using python?
Write a function that takes three arguments: a file-to-read, a file-to-write, and a word (string). It then reads lines from the text file-to-read and writes out only those lines containing the word into the file-to-write. Sample input/output files attached at the end of this document. Sample function call: selectline...
[ "Here is a hint for you to get you a bit further:\nfor line in infile:\n if text in line:\n outfile.write(line)\n\n", "What you're currently doing is iterating the file character-by-character; you do not want to do that.\nInstead, you can iterate a file line by line this way:\nfor line in open('myfile....
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005689142_python_python_3.x.txt
Q: problem with installing with easy_install on custom python I have a mac osx As such I have the normal python that comes with the machine, and the new version that I have downlaoded, and that works very well. This is in $ which python /Library/Frameworks/Python.framework/Versions/2.6/bin/python Easy_install was o...
problem with installing with easy_install on custom python
I have a mac osx As such I have the normal python that comes with the machine, and the new version that I have downlaoded, and that works very well. This is in $ which python /Library/Frameworks/Python.framework/Versions/2.6/bin/python Easy_install was only working on the standard version: $ which easy_install /usr/b...
[ "error: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/easy-install.pth: Permission denied\n\nYou have to run easy_install with root privileges. \n", "Did you try doing just : easy_install pymongo ??\nWhat would that return when you import pymongo in IDLE?\n", "A little late to th...
[ 2, 0, 0 ]
[]
[]
[ "easy_install", "egg", "macos", "python" ]
stackoverflow_0004701037_easy_install_egg_macos_python.txt
Q: Python authentication system for a framework with no authentication built in (like web.py)? I'm looking at building a website using Web.py, and there is no built-in authentication system. Having read various things about authentication on websites, a common theme I keep hearing is "Don't roll your own, use someon...
Python authentication system for a framework with no authentication built in (like web.py)?
I'm looking at building a website using Web.py, and there is no built-in authentication system. Having read various things about authentication on websites, a common theme I keep hearing is "Don't roll your own, use someone else's." There are some examples of simple authentication on the site, like this one, but they...
[ "If you can't find one easily, then probably discarding the advice and rolling your own is not a bad choice.\nI don't think you'll find anything out of the box. The authentication system, is coupled with and dependent on the architecture (in your case probably it is Web only). Having said that it'll perhaps be easi...
[ 1, 1 ]
[]
[]
[ "authentication", "python", "web.py" ]
stackoverflow_0005689020_authentication_python_web.py.txt
Q: Get revisions of a spreadsheet with gdata Python api I'm trying to get the revisions of a spreadsheet using the key, but it just returns "Invalid resource id". from gdata.alt import appengine from gdata.spreadsheet import service from gdata.docs.client import DocsClient self.ss_svc = service.SpreadsheetsService()...
Get revisions of a spreadsheet with gdata Python api
I'm trying to get the revisions of a spreadsheet using the key, but it just returns "Invalid resource id". from gdata.alt import appengine from gdata.spreadsheet import service from gdata.docs.client import DocsClient self.ss_svc = service.SpreadsheetsService() # ... login code ... gd_client = DocsClient(self.ss_svc.G...
[ "This code is a bit confusing because you refer to self but this doesn't appear to be part of a class definition. Also, you say you \"also tried\" gd_client.get(rev_uri) but I don't see what you tried before that -- no other method of gd_client is called in the above code. And finally, you're using the get method, ...
[ 1, 0 ]
[]
[]
[ "google_docs_api", "python" ]
stackoverflow_0005689230_google_docs_api_python.txt
Q: Python Web Backend I am an experienced Python developer starting to work on web service backend system. The system feeds data (constantly) from the web to a MySQL database. This data is later displayed by a frontend side (there is no connection between the frontend and the backend). The backend system constant...
Python Web Backend
I am an experienced Python developer starting to work on web service backend system. The system feeds data (constantly) from the web to a MySQL database. This data is later displayed by a frontend side (there is no connection between the frontend and the backend). The backend system constantly downloads flight info...
[ "If You are about to use SQLAlchemy, I would refrain from using Django: Django is fine if You are using the whole stack, but as You are about to rip Models off, I do not see much value in using it and I would take a look at another option (perhaps Pylons or pure old CherryPy would do).\nEven more so if FEs will not...
[ 0 ]
[]
[]
[ "backend", "django", "python" ]
stackoverflow_0005683437_backend_django_python.txt
Q: Can I use my own Python class with numpy or some other matrix library? I'd like to be able to do matrix operations using a Python class as the elements—in this case, a simple Galois field implementation. It implements the necessary __add__, __mul__, __sub__ etc. At first, I thought this should be possible with num...
Can I use my own Python class with numpy or some other matrix library?
I'd like to be able to do matrix operations using a Python class as the elements—in this case, a simple Galois field implementation. It implements the necessary __add__, __mul__, __sub__ etc. At first, I thought this should be possible with numpy arrays, using the dtype parameter, but from the dtype documentation, it s...
[ "You can use object as the dtype, which will allow arbitrary Python objects. I don't think there's any way of specializing a numpy array to accept only one particular class of Python object.\n", "Here is how you can create and initialize a Numpy object array with another array:\nimport numpy as np\n\nclass G:\n ...
[ 8, 2, 2, 1, 0 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0005578172_matrix_numpy_python.txt
Q: Changing a variable inside a class I'm programming a text field class for a game. It's supposed to change a string from outside the class to the string the user enters. The following is pseudo-code, but you should understand my problem :D class txtfield(pygame.sprite.Sprite): def __init__(self, var, name, x, ...
Changing a variable inside a class
I'm programming a text field class for a game. It's supposed to change a string from outside the class to the string the user enters. The following is pseudo-code, but you should understand my problem :D class txtfield(pygame.sprite.Sprite): def __init__(self, var, name, x, y): self.var=var self.va...
[ "You can't. Python is exclusively pass-by-value, you're asking for pass-by-reference. Explaining the full model with everything it builds on etc. would be lengthy and was already done in the official documentation (read: refer to that if you want more details), but long story short, what happens in your code is thi...
[ 5, 1, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005689308_python_variables.txt
Q: Upload a file with web2py on Google App Engine I have a problem deploying my application written in web2py on Google App Engine. Everything works well on localhost, but on GAE I cannot access the content of an uploaded file. When I check the request.vars.my_upload_field var on localhost, I get: FieldStorage('uploa...
Upload a file with web2py on Google App Engine
I have a problem deploying my application written in web2py on Google App Engine. Everything works well on localhost, but on GAE I cannot access the content of an uploaded file. When I check the request.vars.my_upload_field var on localhost, I get: FieldStorage('upload_field', 'my_file.txt', 'File content') But on GAE ...
[ "see detailed instructions for web2py and GAE blobstore upload here: http://web2pyslices.com/main/slices/take_slice/63\n", "I haven't personally used web2py with GAE, but the official documentation\nmentions something about difficulties in uploading files to the app-engine filesystem using web2py. So probably you...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "upload", "web2py" ]
stackoverflow_0005685039_google_app_engine_python_upload_web2py.txt
Q: How do I validate list:string fields with web2py? Searching through gluon.validators I came across IS_LIST_OF() so I tried to add it to my model: db.define_table("emails_list", Field("recipients", "list:string", requires=IS_LIST_OF(IS_EMAIL( error_message="Invalid email"))) ) I verified that recipient...
How do I validate list:string fields with web2py?
Searching through gluon.validators I came across IS_LIST_OF() so I tried to add it to my model: db.define_table("emails_list", Field("recipients", "list:string", requires=IS_LIST_OF(IS_EMAIL( error_message="Invalid email"))) ) I verified that recipients are correctly added to the database (I use SQLFORM by...
[ "From what I can tell through debugging, validators are stripped from list:* fields for some reason. This must be a bug. You can work around it by using the onvalidation attribute of form.accepts. Here's an example:\nIn your model :\ndef validate_email(form):\n for eml in form.vars.recipients:\n out,ers ...
[ 3 ]
[]
[]
[ "python", "validation", "web2py" ]
stackoverflow_0004565069_python_validation_web2py.txt
Q: Data related UnivariateSpline interpolation problem with SCIPY I'm having a weird problem trying to interpolate data using the UnivariateSpline function. Interpolating through all the points (s=0) and the spline function does not give a result on the entire set of data. The result for s>=1 is also very weird. A...
Data related UnivariateSpline interpolation problem with SCIPY
I'm having a weird problem trying to interpolate data using the UnivariateSpline function. Interpolating through all the points (s=0) and the spline function does not give a result on the entire set of data. The result for s>=1 is also very weird. As I think it is related to the data I'm using, I join them in attach...
[ "Your problem is that your input x-coordinates are in decreasing order. UnivariateSpline expects them to be in increasing order.\nHere's a more compact version of your code above that reproduces the problems you were having. (The data you had in your question is expected to be in a file called data.txt).\nimport n...
[ 5 ]
[]
[]
[ "interpolation", "python", "scipy" ]
stackoverflow_0005689861_interpolation_python_scipy.txt
Q: same python interpreter instance running multiple scripts simultaneously? 6-7 years ago i saw an initiative of a way to run python on tight resources env by running the interpreter only once, while allowing several scripts to use it at the same time. the idea was bot the save the interpreter startup overhead and t...
same python interpreter instance running multiple scripts simultaneously?
6-7 years ago i saw an initiative of a way to run python on tight resources env by running the interpreter only once, while allowing several scripts to use it at the same time. the idea was bot the save the interpreter startup overhead and to save RAM. Does something alike exists? this question Python: Execute multiple...
[ "Yes and no. Python itself uses a Global Interpreter Lock (GIL), which you can read a lot about, if you care to. To make a long story short, however, it ensures the interpreter is basically single-threaded. You can create (and run) more than one thread in your Python program, but when/if they use the Python interpr...
[ 9, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005690327_python.txt
Q: PDFtotext - whitespace showing as aacute on commandline I am extracting text using python from a textfile created from pdf using pdftotext. It is one of 2000 files and in this particular one, a line of keywords ends in EU. The remainder of the line is blank to the naked eye and so is the following line. The progr...
PDFtotext - whitespace showing as aacute on commandline
I am extracting text using python from a textfile created from pdf using pdftotext. It is one of 2000 files and in this particular one, a line of keywords ends in EU. The remainder of the line is blank to the naked eye and so is the following line. The program normally strips off any trailing blanks at the end of a li...
[ "The first tip is not to print wildly to all possible output mechanisms using various unstated encodings. Find out exactly what you have got. Do this:\nprint repr(the_line_with_the_problem) # Python 2.x\nprint(ascii(the_line_with_the_problem)) # Python 3.x\n\nand edit your question and copy/paste the result.\nSecon...
[ 0 ]
[]
[]
[ "character_encoding", "pdftotext", "python", "removing_whitespace" ]
stackoverflow_0005690265_character_encoding_pdftotext_python_removing_whitespace.txt
Q: graphing a relationship matrix in python i have a python interface using wxpython which allows the user to fill in a matrix (0/1) and then graphs it for them. The program creates a numpy matrix, then makes a networkx graph out of that matrix, and then uses matplotlib.pylab to display the graph. numpy is a must, be...
graphing a relationship matrix in python
i have a python interface using wxpython which allows the user to fill in a matrix (0/1) and then graphs it for them. The program creates a numpy matrix, then makes a networkx graph out of that matrix, and then uses matplotlib.pylab to display the graph. numpy is a must, because the program also does other things like ...
[ "It seems to me like your main complaint is in the way that wx handles the matplotlib windows. It is possible to embed the Matplotlib figure in your wx window. Here's an example:\nhttp://wiki.scipy.org/Matplotlib_figure_in_a_wx_panel (updated)\nIt gets a bit complicated. Basically, you should copy the code and rep...
[ 2, 0 ]
[]
[]
[ "matplotlib", "networkx", "numpy", "python", "wxpython" ]
stackoverflow_0005422009_matplotlib_networkx_numpy_python_wxpython.txt
Q: character encoding in python I have a byte stream that looks like this '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' str_data = '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' str_data is wrote into text file using the following code file = open("test_doc","w") file.write(str_data) file.close() If test_doc is opened in a web br...
character encoding in python
I have a byte stream that looks like this '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' str_data = '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' str_data is wrote into text file using the following code file = open("test_doc","w") file.write(str_data) file.close() If test_doc is opened in a web browser and character encoding is se...
[ "Here is an answer:\nmessage1 is encoded in shift_jis; message3 and str_data are encoded in UTF-8. All appear to represent Japanese text. See the following IDLE session:\n>>> message1 = '\\202\\261\\202\\352\\202\\315\\225\\275\\220\\254\\226\\276\\222\\251\\202\\305\\202\\267\\201B'\n>>> print message1.decode('shi...
[ 2, 1, 1 ]
[]
[]
[ "character_encoding", "internationalization", "python", "unicode" ]
stackoverflow_0005685352_character_encoding_internationalization_python_unicode.txt
Q: Calling a python method to fetch data, from a javascript function on the html page Technologies being used Google app engine Django Python Jquery Details of the code and code excerpts I have a drop-down list (country) and a text-box (city) { the drop-down list and text-box are generated by a django-form} that ge...
Calling a python method to fetch data, from a javascript function on the html page
Technologies being used Google app engine Django Python Jquery Details of the code and code excerpts I have a drop-down list (country) and a text-box (city) { the drop-down list and text-box are generated by a django-form} that get automatically populated by a GeoIp library Image of how these UI elements look on the ...
[ "You need to use ajax. jQuery gives you a nice set of interfaces for this.\n\nRe: OP edit - try this code instead:\n$.post(\"/AjaxRequest/get_data_for_users_country_city\", {\n selected_country_name: $('#id_country_name').val(),\n selected_city_name: $('#id_city_name').val()\n}, function(data) {\n alert(\"...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0005690147_google_app_engine_javascript_python.txt
Q: Python Dictionary List originally I had my program like so: inst = {} class IContainer: dicList = {} for i in range(10): inst[i] = IContainer() def FindEnd(node): if node.text != None: inst[counter].dicList[node.tag] = node.text else: for subNode in node: FindEnd(s...
Python Dictionary List
originally I had my program like so: inst = {} class IContainer: dicList = {} for i in range(10): inst[i] = IContainer() def FindEnd(node): if node.text != None: inst[counter].dicList[node.tag] = node.text else: for subNode in node: FindEnd(subNode) counter = 0 for el...
[ "dicList is a class attribute.\nclass IContainer:\n def __init__(self):\n self.dicList = {}\n\n", "In your case, dicList is a class attribute, in which you want an instance attribute.\nClass attributes only have one object to refer to(which is exactly the reason why you are getting those results) wherea...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005691228_dictionary_python.txt
Q: Change a specific element of a list in python? I have three lists inside a list. I want to change a specific element of a specific list. So lets say the second list, first element. I tried it like this: Here is the whole thing, I am just learning how to program so don't judge me :) class Board: #creates visible pl...
Change a specific element of a list in python?
I have three lists inside a list. I want to change a specific element of a specific list. So lets say the second list, first element. I tried it like this: Here is the whole thing, I am just learning how to program so don't judge me :) class Board: #creates visible playing board global rows rows = [] def create_row(sel...
[ "Trace this through - assume we enter '3' when prompted, so height = 2; then \nfor i in rows[2]:\n\nthe first value of i is 'x'\n 'x'[2] = 'a'\n\nand this gives you your error - you cannot change a character in the string because strings are immutable (instead you have to construct a new string and replace the o...
[ 2 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0005690822_arrays_python.txt
Q: What's a more pythonic way to write this function declaration This is parred down to the most basic elements for the sake of brevity. I understand that the below is redundant as written, but I digress. I want to know if there's a smarter, more concise way to write this def create_action(context, verb, actor = None...
What's a more pythonic way to write this function declaration
This is parred down to the most basic elements for the sake of brevity. I understand that the below is redundant as written, but I digress. I want to know if there's a smarter, more concise way to write this def create_action(context, verb, actor = None, target = None, permission_level = None): action = Action(cont...
[ "Use unpacking of arguments:\ndef create_action(*args, **kwargs):\n action = Action(*args, **kwargs)\n\n", "First off, remove spaces between the parts of default args. You also probably don't need to use keyword arguments for the call to Action() e.g.\ndef create_action(context, verb, actor=None, target=None, ...
[ 6, 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005691197_django_python.txt
Q: Gamma function plot in Python So I'd like to plot simple gamma function, but I have some problems. My code is: #!/usr/bin/env python # -*- coding: cp1250 -*- #import math from scipy.special import * #from scitools.std import * from pylab import * def f1(x): return gamma(x) x = linspace(-6, 6, 512) y1 = f1(x)...
Gamma function plot in Python
So I'd like to plot simple gamma function, but I have some problems. My code is: #!/usr/bin/env python # -*- coding: cp1250 -*- #import math from scipy.special import * #from scitools.std import * from pylab import * def f1(x): return gamma(x) x = linspace(-6, 6, 512) y1 = f1(x) # Matlab-style syntax: plot(x, y...
[ "One of the modules (pylab, I think) is shadowing the gamma function by the gamma random variable function. This works, but I had to turn off the call to legend (I'm not sure why, yet).\nfrom scipy.special import gamma as Gamma\n#from scitools.std import *\nfrom pylab import *\n\ndef f1(x):\n return Gamma(x)\n\...
[ 3, 2 ]
[]
[]
[ "matplotlib", "plot", "python", "scipy" ]
stackoverflow_0005685576_matplotlib_plot_python_scipy.txt
Q: how to avoid hard-coding urls in webapp templates I'm developing software on google app engine. I'm using the webapp framework. is there any way to avoid hard-coding urls in the html templates? django provides a solution, but I couldn't find one for webapp. thanks in advance.. A: WebApp is really very basic. Dja...
how to avoid hard-coding urls in webapp templates
I'm developing software on google app engine. I'm using the webapp framework. is there any way to avoid hard-coding urls in the html templates? django provides a solution, but I couldn't find one for webapp. thanks in advance..
[ "WebApp is really very basic.\nDjango url templatetag is closely tied to its idea of URL resolving by matching regex patterns. As WebApp does not have any serious URL resolver, I imagine this would be really hard task to implement something in this line.\nBut you are not totally out of luck. Werkzeug has very easy ...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "templates", "url", "web_applications" ]
stackoverflow_0000805751_google_app_engine_python_templates_url_web_applications.txt
Q: How to correctly achieve test isolation with a stateful Python module? The project I'm working on is a business logic software wrapped up as a Python package. The idea is that various script or application will import it, initialize it, then use it. It currently has a top level init() method that does the initiali...
How to correctly achieve test isolation with a stateful Python module?
The project I'm working on is a business logic software wrapped up as a Python package. The idea is that various script or application will import it, initialize it, then use it. It currently has a top level init() method that does the initialization and sets up various things, a good example is that it sets up SQLAlch...
[ "You have a few options:\nMock the database\nThere are a few trade offs to be aware of.\nYour tests will become more complex as you will have to do the setup, teardown and mocking of the connection. You may also want to do verification of the SQL/commands sent. It also tends to create an odd sort of tight couplin...
[ 3, 1, 0 ]
[]
[]
[ "code_structure", "python", "state", "unit_testing" ]
stackoverflow_0005675654_code_structure_python_state_unit_testing.txt
Q: draw rotated font with pygame What's the best way to draw rotated text rendered with fonts with pygame? I can just draw the font then rotozoom it, but it seems better result would be gotten if it were possible to draw the glyphs directly rotated, especially taking AA into account? A: Pygame does not have the fun...
draw rotated font with pygame
What's the best way to draw rotated text rendered with fonts with pygame? I can just draw the font then rotozoom it, but it seems better result would be gotten if it were possible to draw the glyphs directly rotated, especially taking AA into account?
[ "Pygame does not have the functionality you are looking for.\nYou will have to use the method you mention, i.e rotozoom on an the already rendered font. The quality of this method isn't all that bad actually. And concerning speed, you don't want to be rendering the fonts all the time anyway.\nIf you are desperate f...
[ 0, 0 ]
[]
[]
[ "fonts", "pygame", "python", "render", "rotation" ]
stackoverflow_0005007478_fonts_pygame_python_render_rotation.txt
Q: Error when trying to do an import of testbed I would really like to write tests for Google App Engine using their python testbed library, but each time I try to import it using from google.appengine.ext import testbed I get the following error: File "/Users/lhundeboel/Projects/busybeeapp/tests/test_something.py",...
Error when trying to do an import of testbed
I would really like to write tests for Google App Engine using their python testbed library, but each time I try to import it using from google.appengine.ext import testbed I get the following error: File "/Users/lhundeboel/Projects/busybeeapp/tests/test_something.py", line 1, in <module> from google.appengine.ext...
[ "It's the C-based part of PIL. Install PIL properly.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0005691776_google_app_engine_python_unit_testing.txt
Q: What happens if a site package is updated beyond the version I specified in a virtualenv with pip? Assume I have a virtualenv installation that does not use --no-site-packages. I run bin/pip install somepackage==1.0.0, but it's already present in my site-packages so it's not installed. Later, the copy installed si...
What happens if a site package is updated beyond the version I specified in a virtualenv with pip?
Assume I have a virtualenv installation that does not use --no-site-packages. I run bin/pip install somepackage==1.0.0, but it's already present in my site-packages so it's not installed. Later, the copy installed site-packages is updated to somepackage==2.0.0. What will happen in my virtualenv? Will it use the version...
[ "Only the first package/module found in sys.path with the given name will be used. If your venv is earlier than the system directory then your venv will be used.\n", "It depends. If none of the packages that are importing somepackage use the setuptools API, then it works as described above. If any packages in y...
[ 1, 1 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0005691398_pip_python_virtualenv.txt
Q: Render graph in Python and Javascript I am looking for libraries that can render graphs, PRETTY graphs. I need to both render static images, preferably with python, and also to render them dynamically in the browser. A Canvas solution would be great, flash is acceptable too. I googled around a little and found py...
Render graph in Python and Javascript
I am looking for libraries that can render graphs, PRETTY graphs. I need to both render static images, preferably with python, and also to render them dynamically in the browser. A Canvas solution would be great, flash is acceptable too. I googled around a little and found python-graph, but the images look quite ugly....
[ "Check out following:\n\ncanviz - Graphviz graphs in JS\npydot - Graphviz for Python\nyapgvb - Another alternative for Python\n\nYou should be able to use the same graph definition both in Python and JS. I hope those help. :)\n", "Processing.js, a port of the Processing language, is a very powerful JavaScript vis...
[ 3, 1, 0, 0 ]
[]
[]
[ "canvas", "graph", "javascript", "python", "render" ]
stackoverflow_0005687279_canvas_graph_javascript_python_render.txt
Q: Difference between preinstalled Python and MacPorts Python on Mac OS X While trying to install PIL for Python 2.6 on Mac OS X Snow Leopard, I ran into multiple issues and multiple solutions. So I thought of getting basics cleared. What is the difference between installing Python using MacPorts and using the one th...
Difference between preinstalled Python and MacPorts Python on Mac OS X
While trying to install PIL for Python 2.6 on Mac OS X Snow Leopard, I ran into multiple issues and multiple solutions. So I thought of getting basics cleared. What is the difference between installing Python using MacPorts and using the one that comes with the system and what are the advantages? So in my situation, fo...
[ "There's a lot of good advice here on how to fix your problem, but not many people are answering your questions. The major difference between these various versions is where they place and load their binaries and library modules. The diaspora of Mac python installers could place things in /opt/local/Library/Framewo...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005572384_python.txt
Q: how to spinmap in Python? How can i make a similar work with Python ? A example described how does "spinmap" work with MATLAB language is given as follows. matlab code sphere; axis equal; axis off; spinmap(20,1); A: spinmap does nothing other than cyclically shifting the colormap. You can achieve the same effec...
how to spinmap in Python?
How can i make a similar work with Python ? A example described how does "spinmap" work with MATLAB language is given as follows. matlab code sphere; axis equal; axis off; spinmap(20,1);
[ "spinmap does nothing other than cyclically shifting the colormap. You can achieve the same effect with the following MATLAB code:\nsphere;\naxis equal off\ncmap=colormap;\n\nfor i=1:200\n colormap(cmap(circshift(1:64,[0,-i]),:));\n drawnow\nend\n\nThis must be easy to implement in python. I'll leave it to so...
[ 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0005691930_matlab_python.txt
Q: How to open website pages with names made of consecutive numbers (http://website/#.html) so say i had this global a a = 1 def newre(): global a a += 1 b = str(a) print b op = urlopen('http://website/' + b + '.html') ops = op.read() It won't work because maybe its in a function I guess but how you ...
How to open website pages with names made of consecutive numbers (http://website/#.html)
so say i had this global a a = 1 def newre(): global a a += 1 b = str(a) print b op = urlopen('http://website/' + b + '.html') ops = op.read() It won't work because maybe its in a function I guess but how you make it so that each time the class is run then b in op would be 1 higher than before?
[ "Why do you want to use globals and other things. It is quite simple as what you are trying is somewhat like this.\ncontents = []\nfor i in range(10): # or whatever\n url = 'http://website/' + str(i) + '.html'\n content = urlopen(url)\n contents.append(content)\n\nAlso, I would suggest you to start with a ...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005691042_python.txt
Q: API for controlling the OWI-535 robot arm For fun I've been fiddling with the OWI-535 robot arm, and I came across this blog post about controlling the arm in Linux(or OSX). Has anyone done an API for it in .Net? Once again, a case of trying to not reinvent the wheel... I did find this about controlling it in Pyth...
API for controlling the OWI-535 robot arm
For fun I've been fiddling with the OWI-535 robot arm, and I came across this blog post about controlling the arm in Linux(or OSX). Has anyone done an API for it in .Net? Once again, a case of trying to not reinvent the wheel... I did find this about controlling it in Python, but I wanted to check if anyone had done a ...
[ "You can use LibUsbDotNet to control the arm. It's not specifically for this purpose, but it gives you the tools to do it.\nHere is an example program someone wrote using libusbdotnet.\n" ]
[ 3 ]
[]
[]
[ ".net", "c#", "python", "robotics" ]
stackoverflow_0005692261_.net_c#_python_robotics.txt
Q: Sending treeview information from button_press_event in pygtk I am writing an pygtk app that uses a treeview, which has a connection to button_press_event. What I can't figure out is how to pass the information about the treeview (specifically which row is clicked) to a gtk.Menu or another method. If I used the r...
Sending treeview information from button_press_event in pygtk
I am writing an pygtk app that uses a treeview, which has a connection to button_press_event. What I can't figure out is how to pass the information about the treeview (specifically which row is clicked) to a gtk.Menu or another method. If I used the row-activated signal, it passes in the row and column information in...
[ "I remember that one being kindy tricky. I set up my treeview's gtk.TreeSelection to whatever mode of selection preferred. Then this:\ndef get_selected_ids(self):\n ids = []\n store, paths = self.get_selection().get_selected_rows()\n\n # self.adapter is a mapping class from my data-model to a model column ...
[ 2 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0005691976_gtktreeview_pygtk_python.txt
Q: How to completely reset Python stdlib logging module in an ipython session? I'd like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run. For example while debugging cmd.py I might over time want to run: %run cmd...
How to completely reset Python stdlib logging module in an ipython session?
I'd like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run. For example while debugging cmd.py I might over time want to run: %run cmd.py ... logs with default behavior, e.g. to STDERR with root level WARN %run cmd...
[ "Don't use basicConfig() for this style of usage - it's meant for simple one-off configuration and, as the documentation says, subsequent calls after the first have no effect (it only does anything if the root logger has no handlers). This will be fine when your script is run from the shell prompt, but not from the...
[ 4 ]
[]
[]
[ "ipython", "logging", "python" ]
stackoverflow_0005691130_ipython_logging_python.txt
Q: Python Regex "object has no attribute" I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. Here's the general idea of what I'm doing: Iterate through a file structure and ge...
Python Regex "object has no attribute"
I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. Here's the general idea of what I'm doing: Iterate through a file structure and get a list of files For each file read to a ...
[ "Your exception means that urla has a value of None. Since urla's value is determined by the re.search call, it follows that re.search returns None. And this happens when the string doesn't match the pattern.\nSo basically you should use:\nurla = re.search(pattern2, match)\nif urla is not None:\n print filename,...
[ 18, 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001491277_python_regex.txt
Q: Django view/template boxes I am new to python/django (came from PHP) and there is a design problem i have no idea how to solve. Let's say we have main content block and some side column. Side column displayed at each page of website. But boxes can differ(same set, but in some pages particular boxes disabled) Side ...
Django view/template boxes
I am new to python/django (came from PHP) and there is a design problem i have no idea how to solve. Let's say we have main content block and some side column. Side column displayed at each page of website. But boxes can differ(same set, but in some pages particular boxes disabled) Side column has several boxes, like n...
[ "Hi and welcome to Django. The data in the context is available to all blocks. You don't have to do anything specific to pass context data to a block or an include.\nAdditionally, there are template tags that you can use to encapsulate other functionality that you might need at the template level: http://docs.djang...
[ 0, 0 ]
[]
[]
[ "django", "python", "templates", "view" ]
stackoverflow_0005679519_django_python_templates_view.txt
Q: How to get rid of NameError in Python? Hi I just executed the following code : from Tkinter import * class LabelDemo( Frame ): def __init__( self ): Frame.__init__( self ) self.pack( expand = YES, fill = BOTH ) self.master.title( "Labels" ) self.Label3 = Label( self, bitmap = "warn...
How to get rid of NameError in Python?
Hi I just executed the following code : from Tkinter import * class LabelDemo( Frame ): def __init__( self ): Frame.__init__( self ) self.pack( expand = YES, fill = BOTH ) self.master.title( "Labels" ) self.Label3 = Label( self, bitmap = "warning" ) self.Label3.pack( side = LEFT )...
[ "That code worked fine for me also. There must be an indentation error somewhere. Is that the entirety of the file? Have you got tabs mixed with spaces anywhere?\nEdit:\nThis is your traceback:\nTraceback (most recent call last): \n File \"warning.py\", line 3, in <module> class LabelDemo(Frame): \n File \"wa...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005692765_python.txt
Q: Change the color of the text of QLcdNumber Using PyQt4 and Python 3 do you know how I can change the color of a QLcdNumber during the runtime ? A: Didn't use this for some thime, but I think you had to change paletteForegroundColor and change segmentStyle to QLCDNumber::Filled or QLCDNumber::Flat
Change the color of the text of QLcdNumber
Using PyQt4 and Python 3 do you know how I can change the color of a QLcdNumber during the runtime ?
[ "Didn't use this for some thime, but I think you had to change paletteForegroundColor and change segmentStyle to QLCDNumber::Filled or QLCDNumber::Flat\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python", "python_3.x", "qt" ]
stackoverflow_0005692968_pyqt4_python_python_3.x_qt.txt
Q: How to create folder to the network computer using os.mkdir() python command on apache? I am using Win2008 server + Apache2.2 + mod_python. I would make a folder using string value from the web form. It works in local drive os.mkdir('D:\\temp\\" + folederName)` But it does not work on network - os.mkdir('\\\\19...
How to create folder to the network computer using os.mkdir() python command on apache?
I am using Win2008 server + Apache2.2 + mod_python. I would make a folder using string value from the web form. It works in local drive os.mkdir('D:\\temp\\" + folederName)` But it does not work on network - os.mkdir('\\\\192.168.131.200\\temp\\" + folederName) How can I create a folder to the network computer?
[ "Wild Guess:\nMount the Share to a Driveletter, so you can access it via Z:\\xyz.txt\nbecause the \\\\\\host\\path ist not really what can be handled in normal filesystem ops.\nEDIT: and please use os.path.join() instead of hardcoding the path stuff :)\n" ]
[ 2 ]
[]
[]
[ "apache", "mkdir", "mod_python", "python" ]
stackoverflow_0005693079_apache_mkdir_mod_python_python.txt
Q: Store python datetime object in sqlite3 token=uuid.uuid4().bytes.encode("base64") expires=datetime.now()+timedelta(days=1) print token print expires con = sqlite3.connect(dbpath,detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute( "INSERT INTO token VALUES ('%s', ?)" % (token,expires)) ...
Store python datetime object in sqlite3
token=uuid.uuid4().bytes.encode("base64") expires=datetime.now()+timedelta(days=1) print token print expires con = sqlite3.connect(dbpath,detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute( "INSERT INTO token VALUES ('%s', ?)" % (token,expires)) a=cur.fetchone() con.commit() con.close() T...
[ "Never use % operator with SQL - it can lead to SQL injection. Fix your execute statement like this:\ncur.execute(\"INSERT INTO token VALUES (?, ?)\", (token,expires))\n\nActually there is another one problem: you can't use cur.fetchone() after INSERT.\nFull example:\n$ sqlite3 test.db\nsqlite> create table token (...
[ 9, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005693118_python_sqlite.txt
Q: Clicking a button automatically in a web browser with python Sort of like a bot, i have already checked out some sites such as pyjamas and scrapy, I know how to print data of websites, but still dont know how to interact with buttons. Can somebody help me with some demonstarative code? Lets say i have a form <form...
Clicking a button automatically in a web browser with python
Sort of like a bot, i have already checked out some sites such as pyjamas and scrapy, I know how to print data of websites, but still dont know how to interact with buttons. Can somebody help me with some demonstarative code? Lets say i have a form <form name="input" action="html_form_action.asp" method="get"> Username...
[ "You can use mechanize for that. It provides an easy way for interacting with websites.\n", "If you’re looking to really simulate a browser, you might want to look at Selenium, which allows you to control a real web browser.\nIf the website you’re looking to interface with uses a lot of JavaScript (e.g. onclick h...
[ 11, 5 ]
[]
[]
[ "bots", "python" ]
stackoverflow_0005693221_bots_python.txt
Q: Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell? A Python MD5 hash is different than the one created by the md5sum command on the shell. Why? >>> import hashlib >>> h = hashlib.md5() >>> h.update("mystringforhash") >>> print h.hexdigest() 86b6423cb6d211734fc7d81bb...
Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell?
A Python MD5 hash is different than the one created by the md5sum command on the shell. Why? >>> import hashlib >>> h = hashlib.md5() >>> h.update("mystringforhash") >>> print h.hexdigest() 86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python $ echo mystringforhash | md5sum 686687dd68c5de717b34569dbfb8d3c3 - # Resu...
[ "echo appends a \\n since you usually do not want lines not ending with a linebreak in your shell (it looks really ugly if the prompt does not start at the very left).\nUse the -n argument to omit the trailing linebreak and it will print the same checksum as your python script:\n> echo -n mystringforhash | md5sum\n...
[ 203 ]
[]
[]
[ "md5sum", "python", "shell" ]
stackoverflow_0005693360_md5sum_python_shell.txt
Q: zip function help with tuples I am hoping someone can help me with a problem I'm stuck with. I have a large number of tuples (>500) that look like this: (2,1,3,6) (1,2,5,5) (3,0,1,6) (10,1,1,4) (0,3,3,0) A snippet of my code reads: sum1 = (A,B,C,D) # creates a tuple of sums of (A,B,C,D) mysum = map(su...
zip function help with tuples
I am hoping someone can help me with a problem I'm stuck with. I have a large number of tuples (>500) that look like this: (2,1,3,6) (1,2,5,5) (3,0,1,6) (10,1,1,4) (0,3,3,0) A snippet of my code reads: sum1 = (A,B,C,D) # creates a tuple of sums of (A,B,C,D) mysum = map(sum, zip(A, B, C, D)) print(mysum) I...
[ ">>> zip((1,2,3),(10,20,30),(100,200,300))\n[(1, 10, 100), (2, 20, 200), (3, 30, 300)]\n\n>>> [sum(x) for x in zip((1,2,3),(10,20,30),(100,200,300))]\n[111, 222, 333]\n\nTo do this with an arbitrarily large set of tuples:\n>>> myTuples = [(1,2,3), (10,20,30), (100,200,300)]\n>>> [sum(x) for x in zip(*myTuples)]\n[1...
[ 16, 4, 2, 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0005693559_python_tuples.txt
Q: Python/Redis Multiprocessing I'm using Pool.map from the multiprocessing library to iterate through a large XML file and save word and ngram counts into a set of three redis servers. (which sit completely in memory) But for some reason all 4 cpu cores sit around 60% idle the whole time. The server has plenty of RA...
Python/Redis Multiprocessing
I'm using Pool.map from the multiprocessing library to iterate through a large XML file and save word and ngram counts into a set of three redis servers. (which sit completely in memory) But for some reason all 4 cpu cores sit around 60% idle the whole time. The server has plenty of RAM and iotop shows that there is no...
[ "Network latency may be contributing to your idle CPU time in your python client application. If the network latency between client to server is even as little as 2 milliseconds, and you perform 10,000 redis commands, your application must sit idle for at least 20 seconds, regardless of the speed of any other com...
[ 6 ]
[]
[]
[ "multiprocessing", "python", "redis" ]
stackoverflow_0004441886_multiprocessing_python_redis.txt
Q: How to turn an encoded link such as "http%3A%2F%2Fexample.com%2Fwhatever" into "http://example.com/whatever" in python? I always found links in html source stored in such format, the question is how do I change such links back to what it's normally like? Thanks a lot! A: Use urllib.unquote A: urllib.unquote() ...
How to turn an encoded link such as "http%3A%2F%2Fexample.com%2Fwhatever" into "http://example.com/whatever" in python?
I always found links in html source stored in such format, the question is how do I change such links back to what it's normally like? Thanks a lot!
[ "Use urllib.unquote\n", "urllib.unquote() on its own may still cause problems by throwing the exception:\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position n: ordinal not in range(128)\nIn that case try:\nprint urllib.unquote(\"Ober%C3%B6sterreich.txt\").decode(\"utf8\")\n" ]
[ 4, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003949739_html_python.txt
Q: What's difference between a simple webserver and Apache server? Here the simple webserver means a server that deal with simple HTTP request, just like the following one: import BaseHTTPServer class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path == ‘/foo’: ...
What's difference between a simple webserver and Apache server?
Here the simple webserver means a server that deal with simple HTTP request, just like the following one: import BaseHTTPServer class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path == ‘/foo’: self.send_response(200) self.do_something() ...
[ "\nOr in other words, if i want to use python to implement a server which can be put into use of business, what also should i do?\n\nThere are already python-based web servers, such as CherryPy (which I think is intended to be a web server solution on the same stack level as Apache; it is more python-based though, ...
[ 15, 8, 7 ]
[]
[]
[ "apache", "python", "webserver" ]
stackoverflow_0005693741_apache_python_webserver.txt
Q: Subclassing int and overriding the __init__ method - Python Possible Duplicate: inheritance from str or int Hi folks, I'm trying to subclass the int class without any success. Here is my attempt: class SpecialInt(int): def __init__(self, x, base=10, important_text=''): int.__init__(self, x, base) ...
Subclassing int and overriding the __init__ method - Python
Possible Duplicate: inheritance from str or int Hi folks, I'm trying to subclass the int class without any success. Here is my attempt: class SpecialInt(int): def __init__(self, x, base=10, important_text=''): int.__init__(self, x, base) self.important_text=important_text If I perform the follow...
[ "See __new__:\n\n__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.\n\n" ]
[ 7 ]
[]
[]
[ "built_in", "int", "python", "subclassing" ]
stackoverflow_0005693942_built_in_int_python_subclassing.txt
Q: Should I use memcache? My code produces a zip file from Google App Engine for loading in a browser ie 10 KB < size < 1000 KB and I wonder if I can use memcache here or if the file is too large or already cached. I already use both memcache and set the cache control when generating the actual file first. class KMZ...
Should I use memcache?
My code produces a zip file from Google App Engine for loading in a browser ie 10 KB < size < 1000 KB and I wonder if I can use memcache here or if the file is too large or already cached. I already use both memcache and set the cache control when generating the actual file first. class KMZHandler(webapp.RequestHandle...
[ "If the file is under 1mb, and it does not change for each request, then memcaching the KMZ would likely reduce resource usage.\nThe KMZ file is not already in memcache, though it could be in a front-end cache. You are memcaching the results from the query when you generate the KML (see Nick's blog for a descripti...
[ 2 ]
[]
[]
[ "google_app_engine", "kmz", "python" ]
stackoverflow_0005692104_google_app_engine_kmz_python.txt
Q: Adding elements to a set , adds elements to all the instances of the object containing this set Hi I have created a List of Objects. Each object contains a Set. I want to update the set's contents for all the objects in the list. The code that i wrote to accomplish this is class Player: name = "" cardsInH...
Adding elements to a set , adds elements to all the instances of the object containing this set
Hi I have created a List of Objects. Each object contains a Set. I want to update the set's contents for all the objects in the list. The code that i wrote to accomplish this is class Player: name = "" cardsInHand = set() hasBid = False def __init__(self, name): self.name = name class CardDec...
[ "You're creating class attributes.\nclass Player:\n def __init__(self, name):\n self.name = name \n self.cardsInHand = set()\n self.hasBid = False\n\n", "You've defined cardsInHand (as well as name and hasBid) to be class variables instead of instance variables; by defining them in the cla...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005694022_python.txt
Q: django one form multiple tables A form collects first name, email, password and grade. Can I save this information in two tables using something like this? def save(self): new_user = User.objects.create_user(first=self.cleaned_data['first'], email=self.cleaned_data['email'], password=self.cleaned_data['passwo...
django one form multiple tables
A form collects first name, email, password and grade. Can I save this information in two tables using something like this? def save(self): new_user = User.objects.create_user(first=self.cleaned_data['first'], email=self.cleaned_data['email'], password=self.cleaned_data['password']) new_grade = Grade.objects.c...
[ "It's absolutely possible and normal to do such a thing. A form doesn't have to resemble a model just because ModelForms do. Forms are simply a way of describing the input that is required for a particular use case. What you do with that data is entirely up to you. That includes saving it across a number of differe...
[ 5, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "forms", "python" ]
stackoverflow_0005690958_django_django_forms_django_models_forms_python.txt
Q: how to calculate number of items in per user groupby item How can I output a result like this: user I R H ================= atl001 2 1 0 cms017 1 2 1 lhc003 0 1 2 from a list like this: atl001 I atl001 I cms017 H atl001 R lhc003 H cms017 R cms017 I lhc003 H lhc003 R cms017 R i.e. I want to ...
how to calculate number of items in per user groupby item
How can I output a result like this: user I R H ================= atl001 2 1 0 cms017 1 2 1 lhc003 0 1 2 from a list like this: atl001 I atl001 I cms017 H atl001 R lhc003 H cms017 R cms017 I lhc003 H lhc003 R cms017 R i.e. I want to calculate the number of I, H and R per user. Just a note that I...
[ "data='''atl001 I\natl001 I\ncms017 H\natl001 R\nlhc003 H\ncms017 R\ncms017 I\nlhc003 H\nlhc003 R\ncms017 R'''\n\nstats={}\nfor i in data.split('\\n'):\n user, irh = i.split()\n u = stats.setdefault(user, {})\n u[irh] = u.setdefault(irh, 0) + 1\n\nprint 'user I R H'\nfor user in sorted(stats):\n stat...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "python", "python_2.3" ]
stackoverflow_0005692414_python_python_2.3.txt
Q: using output from beautifulsoup in python Hey all, I am using beautifulsoup (after unsuccessfully struggling for two days with scrapy) to scrape starcraft 2 league data however I am encountering a problem. I have this table with the result of which I want the string content of all tags which i do like this: from ...
using output from beautifulsoup in python
Hey all, I am using beautifulsoup (after unsuccessfully struggling for two days with scrapy) to scrape starcraft 2 league data however I am encountering a problem. I have this table with the result of which I want the string content of all tags which i do like this: from BeautifulSoup import * from urllib import urlop...
[ "The u means Unicode string. It doesn't change anything for you as a programmer and you should just disregard it. Treat them like normal strings. You actually want this u there.\nBe aware that all Beautiful Soup output is unicode. That's a good thing, because if you run across any Unicode characters in your scrapin...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005694264_beautifulsoup_python.txt
Q: Pynotify runs fine interactively, but crashes when run programmatically (on Fedora 13) I am attempting to use pynotify for a small project, but am having a strange problem on my Fedora 13 machine. It appears that when pynotify is run programmatically it crashes when show() is called - however if I type that line m...
Pynotify runs fine interactively, but crashes when run programmatically (on Fedora 13)
I am attempting to use pynotify for a small project, but am having a strange problem on my Fedora 13 machine. It appears that when pynotify is run programmatically it crashes when show() is called - however if I type that line myself it runs fine! I have tested it also on my Ubuntu box, where it runs absolutely fine. M...
[ "Since Owen has not accepted my offer to take this answer, here is the solution that worked for me. Note that I have no idea why this works (other than vague guesses), and that I don't make any sort of guarantees about whether this is a good solution or not, but maybe if you are ever in as odd a position as I was t...
[ 0 ]
[]
[]
[ "fedora", "glib", "pynotify", "python" ]
stackoverflow_0005623289_fedora_glib_pynotify_python.txt
Q: Can't figure out how to include *.html files within a site-packages folder I cannot figure out how to write my setup.py script in order to include *.html files within the installed package. Here is my attempt: import os from setuptools import setup, find_packages setup(name='django-testapp', version='0.1', au...
Can't figure out how to include *.html files within a site-packages folder
I cannot figure out how to write my setup.py script in order to include *.html files within the installed package. Here is my attempt: import os from setuptools import setup, find_packages setup(name='django-testapp', version='0.1', author='RadiantHex', license='BSD', keywords='testapp,django', packages=['te...
[ "Add following 'package_data' argument to the setup():\nsetup(...,\n package_data={\n 'testapp' : ['testapp/*.html']\n }, ...)\n\n" ]
[ 4 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0005694394_distutils_python_setuptools.txt
Q: PyQt4: extract values from rawHeaderList I want to read headers from the rawHeaderList using QNetworkReply how to perform this action? I try to iterate but it says QNetworkRaply object is not iterable, simple printing says <PyQt4.QtNetwork.QNetworkReply object at 0x1837958>. Here is my code ... request = QNetwork...
PyQt4: extract values from rawHeaderList
I want to read headers from the rawHeaderList using QNetworkReply how to perform this action? I try to iterate but it says QNetworkRaply object is not iterable, simple printing says <PyQt4.QtNetwork.QNetworkReply object at 0x1837958>. Here is my code ... request = QNetworkRequest(QUrl('http://www.kg')) manager = QNet...
[ "Many ways. You can use reply.rawHeaderPairs(), for example:\nimport pprint, sys\nfrom PyQt4 import QtCore, QtNetwork\n\napp = QtCore.QCoreApplication(sys.argv)\nrequest = QtNetwork.QNetworkRequest(QtCore.QUrl(\"http://stackoverflow.com\"))\nmanager = QtNetwork.QNetworkAccessManager()\nreply = manager.get(request)\...
[ 2 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0005693238_pyqt4_python_qt4.txt
Q: Assistance with Django model relationships class Pinyin(models.Model): pinyinWord = models.CharField(max_length=200) englishWord = models.CharField(max_length=1000) englishPhrase = models.TextField() pinyinPhrase = models.TextField() def __unicode__(self): return u"%s | %s" % (self....
Assistance with Django model relationships
class Pinyin(models.Model): pinyinWord = models.CharField(max_length=200) englishWord = models.CharField(max_length=1000) englishPhrase = models.TextField() pinyinPhrase = models.TextField() def __unicode__(self): return u"%s | %s" % (self.pinyinWord, self.englishWord) class Learned(mod...
[ "You could use the model meta option unique_together:\nclass Learned(models.Model):\n pinyinWord = models.ForeignKey(Pinyin)\n user = models.ForeignKey(User)\n date = models.DateField()\n learned = models.BooleanField()\n class Meta:\n unique_together = ('user', 'pinyinWord')\n\n", "I hope t...
[ 1, 0 ]
[]
[]
[ "database", "database_relations", "django", "python" ]
stackoverflow_0005694626_database_database_relations_django_python.txt
Q: How to get an asynchronous ouput in a Python cmd shell? I use the cmd module to create an interactive shell. The workflow is a usual one: enter command, print result. But the result will be processed asynchronously,then stacked in a queue. I then need some way to get it back into my shell to display it. How can I ...
How to get an asynchronous ouput in a Python cmd shell?
I use the cmd module to create an interactive shell. The workflow is a usual one: enter command, print result. But the result will be processed asynchronously,then stacked in a queue. I then need some way to get it back into my shell to display it. How can I push data from ouside my shell into my shell and print it ? S...
[ "If it's only for display purposes, you can just print the result to c.stdout (c is cmd.Cmd object). Will that work for you?\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "cmd", "python" ]
stackoverflow_0005694699_asynchronous_cmd_python.txt
Q: Python: Putting specific lines of a file into a list Greetings, i got into the following problem: Given a file of the following structure: '>some cookies chocolatejelly peanutbuttermacadamia doublecoconutapple '>some icecream cherryvanillaamaretto peanuthaselnuttiramisu bananacoffee '>some other st...
Python: Putting specific lines of a file into a list
Greetings, i got into the following problem: Given a file of the following structure: '>some cookies chocolatejelly peanutbuttermacadamia doublecoconutapple '>some icecream cherryvanillaamaretto peanuthaselnuttiramisu bananacoffee '>some other stuff letsseewhatfancythings wegotinhere Aim: putting...
[ "The problem is that you only store the current section seq when you hit a line with '>' in it. When the file ends, you still have that section open, but you don't store it. \nThe simplest way to fix your program is this:\ndef parseSequenceIntoDictionary(filename):\n lis=[]\n seq=''\n with open(filename, '...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "file", "iteration", "list", "python" ]
stackoverflow_0005694101_file_iteration_list_python.txt
Q: Pygments to latex better formatting for py code I am trying to include python code in my lyx document by inserting a file. I began by trying to use listings but this was causing code to overflow pages. Now I'm using pygments setting it up as described in this tutorial, http://wiki.lyx.org/Examples/IncludeExternalP...
Pygments to latex better formatting for py code
I am trying to include python code in my lyx document by inserting a file. I began by trying to use listings but this was causing code to overflow pages. Now I'm using pygments setting it up as described in this tutorial, http://wiki.lyx.org/Examples/IncludeExternalProgramListingUsingPygments. This appears to work fair...
[ "You should check out package called minted, although I don't know how well it works together with Lyx. But in regular latex file you can just do:\n\\usepackage{minted}\n...\n\\inputminted[]{python}{python_file.py}\n\n" ]
[ 0 ]
[]
[]
[ "lyx", "pygments", "python", "tex" ]
stackoverflow_0005694728_lyx_pygments_python_tex.txt
Q: How to use struct.unpack and convert it to a value in Objective-c Code in Python struct.unpack("< I",data.read(4))[0] # Unpack to int. The data is read from a file, then read is used, My question is how can we use, read and struct.unpack in Objective-c I have the data in the format NSFileHandle which I could rea...
How to use struct.unpack and convert it to a value in Objective-c
Code in Python struct.unpack("< I",data.read(4))[0] # Unpack to int. The data is read from a file, then read is used, My question is how can we use, read and struct.unpack in Objective-c I have the data in the format NSFileHandle which I could read byte by byte, so reading is not a problem now. The problem is conver...
[ "I don't know about Objective-C but in plain C you could use fread():\n#include <inttypes.h> /* uint32_t and PRIu32 macros */\n#include <stdbool.h> /* bool type */\n#include <stdio.h>\n\n/* \n gcc *.c && \n python -c'import struct, sys; sys.stdout.write(struct.pack(\"<I\", 123))' |\n ./a.out \n*/\n\nstatic bool...
[ 1 ]
[]
[]
[ "objective_c", "python", "struct", "unpack" ]
stackoverflow_0005695064_objective_c_python_struct_unpack.txt
Q: Implementing stack in python by using lists as stacks I am create a stack demo with some functionality: ( Method ) __init__(self, n) => How can I initial the fix n len of stack. ? ( Method ) IsEmpty => Done by using lists as stacks ( Method ) IsFull => Done by using lists as stacks ( Method ) Push ...
Implementing stack in python by using lists as stacks
I am create a stack demo with some functionality: ( Method ) __init__(self, n) => How can I initial the fix n len of stack. ? ( Method ) IsEmpty => Done by using lists as stacks ( Method ) IsFull => Done by using lists as stacks ( Method ) Push => Done by using lists as stacks ( Method ) Pop ...
[ "Check out Using lists as stacks in python.\n", "Python's list probably already has everything you want. If you want some additional functionality like limiting max number of objects you should subclass it or wrap around it with another class.\n", "Python has it built-in, see Using Lists as Stacks. It sounds l...
[ 3, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005695487_python.txt
Q: CSV to Python Dictionary with all column names? I'm still pretty new to using python to program from scratch so as an exercise I though I'd take a file that I process using SQL an try to duplicate the functionality using Python. It seems that I want to take my (compressed, zip) csv file and create a Dict of it (or...
CSV to Python Dictionary with all column names?
I'm still pretty new to using python to program from scratch so as an exercise I though I'd take a file that I process using SQL an try to duplicate the functionality using Python. It seems that I want to take my (compressed, zip) csv file and create a Dict of it (or maybe a dict of dicts?). When I use dict reader I ge...
[ "Are you sure that this is a file with comma-separated values? It seems like the lines are being delimited by tabs.\nIf this is correct, specify a tab delimiter in the DictReader constructor.\nfor row in csv.DictReader(items_file, dialect='excel', delimiter='\\t'):\n for key in row:\n print 'key=%s, value...
[ 6, 1, 0 ]
[]
[]
[ "csv", "dictionary", "import", "python", "sql" ]
stackoverflow_0005695395_csv_dictionary_import_python_sql.txt
Q: Django: get info from same table based on column vsalue for data record I am building a forum application for a website and have a "quote_id" column in the Posts table to put in a post_id if someone quotes a certain post to reply to. That is part of the Posts table just like all other posts. However, when I retrie...
Django: get info from same table based on column vsalue for data record
I am building a forum application for a website and have a "quote_id" column in the Posts table to put in a post_id if someone quotes a certain post to reply to. That is part of the Posts table just like all other posts. However, when I retrieve all records that match the topic that corresponds to the topic chosen, the...
[ "Drop the post_quote_id field and create a recursive m2m-relationship for your Post model.\nquoted_by = models.ManyToManyField('self')\n\nThat way posts can refer to other posts and you should be able to easily fetch the related posts for all your posts matching a certain topic.\nexample_post = Post.objects.get(pk=...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005695383_django_python.txt
Q: web.py and flask For these pythonic web frameworks; They looks similar, except a few minor differences like their url handling schemes. So it is very hard to choose one of them. I want to learn from your experiences that which one more suits for a web application that is small in size, but need long term support ...
web.py and flask
For these pythonic web frameworks; They looks similar, except a few minor differences like their url handling schemes. So it is very hard to choose one of them. I want to learn from your experiences that which one more suits for a web application that is small in size, but need long term support (initial application i...
[ "Flask is a new and a very active project with good documentation and guidelines for new development and plugins. Its community is quite large and Armin (the lead) is an A grade programmer. Hence it is definitely the better contender. \nWeb.py is an older and more mature project which is more a library than a frame...
[ 43 ]
[]
[]
[ "flask", "python", "web.py" ]
stackoverflow_0005695689_flask_python_web.py.txt
Q: Python, len and slices on unicode strings I am handling a situation where I need to make a string fit in the allocated gap in the screen, as I'm using unicode len() and slices[] work apparently on bytes and I end up cutting unicode strings too short, because € only occupies one space in the screen but 2 for len() ...
Python, len and slices on unicode strings
I am handling a situation where I need to make a string fit in the allocated gap in the screen, as I'm using unicode len() and slices[] work apparently on bytes and I end up cutting unicode strings too short, because € only occupies one space in the screen but 2 for len() or slices[]. I have the encoding headers proper...
[ "You're not creating Unicode strings there; you're creating byte strings with UTF-8 encoding (which is variable-length, as you're seeing). You need to use constants of the form u\"...\" (or u'...'). If you do that, you get the expected result:\n% cat test.py\n# -*- coding: utf-8 -*-\na = u\"2 €uros\"\nb = u\"2 Eu...
[ 17 ]
[]
[]
[ "python", "string", "unicode" ]
stackoverflow_0005695714_python_string_unicode.txt
Q: How can i use nosetest to run an shell script or another python script nose is a test runner which extends PyUnit. Is it possible to write e.g $ nosetests --with-shell myTest.py -myargs test If not, then is there a plugin, or do i need to develop it myself. Any suggestions ? A: Nose is not a general test harnes...
How can i use nosetest to run an shell script or another python script
nose is a test runner which extends PyUnit. Is it possible to write e.g $ nosetests --with-shell myTest.py -myargs test If not, then is there a plugin, or do i need to develop it myself. Any suggestions ?
[ "Nose is not a general test harness. It's specifically a Python harness which runs Python unit tests. \nSo, while you can write extensions for it to execute scripts and mark them as successes or failures based on the exit status or an output string, I think it's an attempt to shoehorn the harness into doing somethi...
[ 3 ]
[]
[]
[ "nose", "python" ]
stackoverflow_0005695265_nose_python.txt
Q: python to C conversion error python code for b in range(4): for c in range(4): print myfunc(b/0x100000000, c*8) c code unsigned int b,c; for(b=0;b<4;b++) for(c=0;c<4; c++) printf("%L\n", b/0x100000000); printf("%L\n" , myfunc(b/0x100000000, c*8)); I am getting an error saying: error: int...
python to C conversion error
python code for b in range(4): for c in range(4): print myfunc(b/0x100000000, c*8) c code unsigned int b,c; for(b=0;b<4;b++) for(c=0;c<4; c++) printf("%L\n", b/0x100000000); printf("%L\n" , myfunc(b/0x100000000, c*8)); I am getting an error saying: error: integer constant is too large for "lo...
[ "Your C code needs braces to create the scope that Python does by indentation, so it should look like this:\nunsigned int b,c;\nfor(b=0;b<4;b++)\n{\n for(c=0;c<4; c++)\n {\n printf(\"%L\\n\", b/0x100000000);\n printf(\"%L\\n\" , myfunc(b/0x100000000, c*8)); \n }\n}\n\n", "Try long long. Python ...
[ 3, 1, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0005695152_c_python.txt
Q: pyqt application lost icon after packaged by cx_freeze Possible Duplicate: Images not showing when running a frozen pyqt app on another computer I have a pyqt application whose icon is in a resource file. I can see the icon when run the application using python app.py. But after I package the application using c...
pyqt application lost icon after packaged by cx_freeze
Possible Duplicate: Images not showing when running a frozen pyqt app on another computer I have a pyqt application whose icon is in a resource file. I can see the icon when run the application using python app.py. But after I package the application using cx_freeze, the icon is missing. I can see the compiled resou...
[ "I had this problem and I was using an .ico file for the icon. However when I used a .gif file for the icon instead, I got my icon back. Hope this helps.\nIf not, try not using the icon as a compiled resource, but just a normal file in its directory.\n" ]
[ 0 ]
[]
[]
[ "cx_freeze", "pyqt", "python" ]
stackoverflow_0003499902_cx_freeze_pyqt_python.txt
Q: Serving static html in Google app engine Python I'm having trouble getting static .html pages loaded for my Python app. When I click on a link like index.html, I get a blank page and on the server log a 404 error. This is the same for other static .html files such as about.html. The application works bar the stati...
Serving static html in Google app engine Python
I'm having trouble getting static .html pages loaded for my Python app. When I click on a link like index.html, I get a blank page and on the server log a 404 error. This is the same for other static .html files such as about.html. The application works bar the static files. I've tried looking in numerous places, but I...
[ "Keep your HandlerScripts below the Static Directory handling portion. IOW, just move this to the last.\n- url: /index\\.html\nscript: index.py\n\n- url: /\nscript: index.py\n\n", "Put an /HTML in your static_files path:\n- url: /(.*\\.(html))\n static_files: static/HTML/\\1\n upload: static/HTML/(.*\\.(html))\...
[ 4, 2, 1, 0 ]
[]
[]
[ "google_app_engine", "html", "python", "yaml" ]
stackoverflow_0005693976_google_app_engine_html_python_yaml.txt
Q: Indexing a Music Lyrics Database So I want to index the lyrics from a lyrics website and then perform operations on the lyrics (search for certain artists, terms, patterns etc) . I figure the best scenario is if there is already some structured file format for me to use--> anyone know if anything like this exists?...
Indexing a Music Lyrics Database
So I want to index the lyrics from a lyrics website and then perform operations on the lyrics (search for certain artists, terms, patterns etc) . I figure the best scenario is if there is already some structured file format for me to use--> anyone know if anything like this exists? The next best thing would be a site t...
[ "Downloading the lyric database from a site is bad idea, you can query it for each lyric you want instead. \nEven if you download all the lyrics, don't store them on a flat-file(maybe xml?), instead of use a database like sqlite. Otherwise the operations like searching or listing would be painful.\nBut no idea abou...
[ 3, 2 ]
[]
[]
[ "database", "indexing", "php", "python", "search" ]
stackoverflow_0005696329_database_indexing_php_python_search.txt
Q: Where do I start if I want to customise the WxPython rich text control? Does anyone know of any articles or code samples to get me started customising the WxPython rich text control? I am trying to extend the rich text control to allow me to insert controls (buttons, text boxes etc) into the editing area e.g. inst...
Where do I start if I want to customise the WxPython rich text control?
Does anyone know of any articles or code samples to get me started customising the WxPython rich text control? I am trying to extend the rich text control to allow me to insert controls (buttons, text boxes etc) into the editing area e.g. instead of just inserting images or formatted text I would like to be able to ins...
[ "Download the wxpython demo from their site, it should provide you with an in-depth example of a wxRichTextCtrl. Without providing any information about your specific customizations, there is not much else I can help with.\n" ]
[ 1 ]
[]
[]
[ "python", "richtext", "wxpython" ]
stackoverflow_0005637677_python_richtext_wxpython.txt
Q: Win32 event loop appearing to be the program bottleneck I am making a game in Python with Pyglet. I have just finished the display part, and getting issues with speed. Like a good person, I profiled, and got the following: (uninteresting bits excluded; currently it just redraws the screen when I push an arrow key ...
Win32 event loop appearing to be the program bottleneck
I am making a game in Python with Pyglet. I have just finished the display part, and getting issues with speed. Like a good person, I profiled, and got the following: (uninteresting bits excluded; currently it just redraws the screen when I push an arrow key with random magenta and white) 15085326 function calls (1...
[ "REVISED Answer:\nI deleted the columns that are worthless information, such as self time, call count, and per-call time.\nThen I arranged them in descending order by cumtime, and discarded the small ones.\ncumtime filename:lineno(function)\n 32.168 <string>:1(<module>)\n 32.168 win32.py:46(run)\n 20.531 engine...
[ 2 ]
[]
[]
[ "profiling", "pyglet", "python", "pywin32" ]
stackoverflow_0005696373_profiling_pyglet_python_pywin32.txt
Q: How do I use kd-trees for determining string similarity? I am trying to utilize k-nearest neighbors for the string similarity problem i.e. given a string and a knowledge base, I want to output k strings that are similar to my given string. Are there any tutorials that explain how to utilize kd-trees to efficiently...
How do I use kd-trees for determining string similarity?
I am trying to utilize k-nearest neighbors for the string similarity problem i.e. given a string and a knowledge base, I want to output k strings that are similar to my given string. Are there any tutorials that explain how to utilize kd-trees to efficiently do this k-nearest neighbor lookup for strings? The string len...
[ "Probably one of the hottest blog posts I had read a year or so ago: Levenstein Automata. Take a look at that article. It provides not only a description of the algorithm but also code to follow. Technically, it's not a kd-tree but it's quite related to the string matching and dictionary correction algorithms on...
[ 8 ]
[]
[]
[ "algorithm", "kdtree", "python", "string" ]
stackoverflow_0005696859_algorithm_kdtree_python_string.txt
Q: Why does str() round up floats? The built-in Python str() function outputs some weird results when passing in floats with many decimals. This is what happens: >>> str(19.9999999999999999) >>> '20.0' I'm expecting to get: >>> '19.9999999999999999' Does anyone know why? and maybe workaround it? Thanks! A: It's n...
Why does str() round up floats?
The built-in Python str() function outputs some weird results when passing in floats with many decimals. This is what happens: >>> str(19.9999999999999999) >>> '20.0' I'm expecting to get: >>> '19.9999999999999999' Does anyone know why? and maybe workaround it? Thanks!
[ "It's not str() that rounds, it's the fact that you're using floats in the first place. Float types are fast, but have limited precision; in other words, they are imprecise by design. This applies to all programming languages. For more details on float quirks, please read \"What Every Programmer Should Know About F...
[ 8, 6, 3, 1 ]
[]
[]
[ "python", "rounding", "string" ]
stackoverflow_0005683869_python_rounding_string.txt
Q: wxpython RichtextCtrl event bindings on buttons/images Just wondering whether there is any provision/method to bind clicks on images/(or include a button) to result into some events. Also is there any kind of way to draw a StaticLine kind of thing in a RichTextCtrl in wxPython. A: You can bind to a button if you...
wxpython RichtextCtrl event bindings on buttons/images
Just wondering whether there is any provision/method to bind clicks on images/(or include a button) to result into some events. Also is there any kind of way to draw a StaticLine kind of thing in a RichTextCtrl in wxPython.
[ "You can bind to a button if you like, you could use a bitmapbutton instead, or bind mouse events to your static bitmap. The wxPython demo has examples for all of these methods.\nWith regards to the \"StaticLine kinda thing\", are you trying to resize the richtextctrl on demand? You might want to look at the Expand...
[ 0 ]
[]
[]
[ "python", "user_interface", "wx.textctrl", "wxpython", "wxtextctrl" ]
stackoverflow_0004967307_python_user_interface_wx.textctrl_wxpython_wxtextctrl.txt
Q: Python: How to load and use trained and pickled NLTK tagger to GAE? I have a trained and pickled NLTK tagger (Brill's transformational rule-based tagger). I want to use it on GAE. What the best way to do it? A: If your NLTK tagger code and data is of limited size, then carry it along with your GAE code. If you ...
Python: How to load and use trained and pickled NLTK tagger to GAE?
I have a trained and pickled NLTK tagger (Brill's transformational rule-based tagger). I want to use it on GAE. What the best way to do it?
[ "If your NLTK tagger code and data is of limited size, then carry it along with your GAE code. \nIf you have to act upon it to retrain the set, then storing the content of the file as a BLOB in the datastore would be an option, so that you get, analyze, retrain and put.But that will limit size of dataitem to be les...
[ 3 ]
[]
[]
[ "google_app_engine", "nltk", "pickle", "python" ]
stackoverflow_0005696995_google_app_engine_nltk_pickle_python.txt
Q: Python in memory table data structures for analysis (dict, list, combo) I'm trying to simulate some code that I have working with SQL but using all Python instead.. With some help here CSV to Python Dictionary with all column names? I now can read my zipped-csv file into a dict Only one line though, the last one. ...
Python in memory table data structures for analysis (dict, list, combo)
I'm trying to simulate some code that I have working with SQL but using all Python instead.. With some help here CSV to Python Dictionary with all column names? I now can read my zipped-csv file into a dict Only one line though, the last one. (how do I get a sample of lines or the whole data file?) I am hoping to have ...
[ "You can only read one line at a time from the csv reader, but you can store them all in memory quite easily:\nrows = []\nfor row in csv.DictReader(items_file, dialect='excel', delimiter='\\t'):\n rows.append(row)\n\n# rows[0]\n{'keyA': 13, 'keyB': 'dataB' ... }\n# rows[1]\n{'keyA': 5, 'keyB': 'dataB' ... }\n\nT...
[ 4, 1, 0 ]
[]
[]
[ "csv", "data_structures", "dictionary", "list", "python" ]
stackoverflow_0005696582_csv_data_structures_dictionary_list_python.txt
Q: call python script by php and solve errors I have a php/action.php. That script creats a file in the folder ../data/myfile.kml. After creating this file I want to modify it. So I call a python script by exec("python mypythonscript.py someparams"); Php errors are shown, when I call the website. Is there a way to s...
call python script by php and solve errors
I have a php/action.php. That script creats a file in the folder ../data/myfile.kml. After creating this file I want to modify it. So I call a python script by exec("python mypythonscript.py someparams"); Php errors are shown, when I call the website. Is there a way to show the python erros on the webseite, too? It se...
[ "You can see the output of exec if you pass it an additional array (and later see its contents):\nexec(\"python mypythonscript.py someparams\",$my_output);\nvar_dump($my_output);\n\nYou should be able to debug from there.\n", "The most likely explanation is that php executes the script as a different user and, th...
[ 6, 2 ]
[]
[]
[ "logging", "php", "python" ]
stackoverflow_0005697304_logging_php_python.txt
Q: calculate length of list recursively If you have a list = [1,2,3,4,5] how would you recursively calculate the length of that list without using len(list)? myarray = [1,2,3,4,5] def mylist(myarray): if (myarray == []): print ("The list is empty") return return 1 + ? Don't want to use len ...
calculate length of list recursively
If you have a list = [1,2,3,4,5] how would you recursively calculate the length of that list without using len(list)? myarray = [1,2,3,4,5] def mylist(myarray): if (myarray == []): print ("The list is empty") return return 1 + ? Don't want to use len but just add 1 each time there exists a va...
[ ">>> def list_length(L):\n... if L:\n... return 1 + list_length(L[1:])\n... return 0\n... \n>>> list_length(myarray)\n5\n>>> list_length([])\n0\n>>> list_length([1]*4)\n4\n>>> \n\nIf the list has elements, return 1 + the length of the list minus one element.\nYou can do this a couple different ways,...
[ 8 ]
[ "Use a recursive function.\nBasically call the function again and add the count returned by it to the result. Important thing is to make sure you exit (return) when the function has nothing to do.\nCheck out this post\nPython recursion and return statements\n" ]
[ -2 ]
[ "function", "python", "recursion" ]
stackoverflow_0005697490_function_python_recursion.txt
Q: How to launch a process that connects to a socket you're listening on? I have a process which my code is launching from subprocess.Popen() that attempts to connect to a socket my code is also listening on. The problem is if the code starts listening on this socket first, it cannot launch the subprocess. It was blo...
How to launch a process that connects to a socket you're listening on?
I have a process which my code is launching from subprocess.Popen() that attempts to connect to a socket my code is also listening on. The problem is if the code starts listening on this socket first, it cannot launch the subprocess. It was blocked by sock.accept(), and when sock.accept() is times out, it is obviously ...
[ "Doug Hellman's Python Module of the Week is a good place to find an introduction to a module's basic usage like subprocess.\nFailing that, some code that is causing problems would help us answer your question.\n", "Are you setting socket.setblocking(0) in your listening code?\nAfter you spawn the listening serve...
[ 1, 1, 0 ]
[]
[]
[ "multithreading", "python", "sockets", "tcp" ]
stackoverflow_0005697426_multithreading_python_sockets_tcp.txt
Q: Pyramid (Pylons/repoze.bfg) LDAP authentication Have anybody ever tried to use authentication mechanisms through LDAP / AD (OpenLDAP / ActiveDirectory)? Any middleware to automate these things? A: I'd recommend checking out repoze.who. It has a plugin for LDAP authentication. It's built for handling common authe...
Pyramid (Pylons/repoze.bfg) LDAP authentication
Have anybody ever tried to use authentication mechanisms through LDAP / AD (OpenLDAP / ActiveDirectory)? Any middleware to automate these things?
[ "I'd recommend checking out repoze.who. It has a plugin for LDAP authentication. It's built for handling common authentication methods using WSGI middleware and is the most prevalent solution to handling SSO.\n" ]
[ 5 ]
[]
[]
[ "active_directory", "ldap", "openldap", "pyramid", "python" ]
stackoverflow_0005696632_active_directory_ldap_openldap_pyramid_python.txt
Q: XPath to find all links with just numbers in them? I've selected the element in a page that has the links I want to the pages. They are sort of like <a href="blah">1</a>. I want to use regex with xpath so that I can get all the links like that one, whose text is \d+. I see there is an answer for it here: How to us...
XPath to find all links with just numbers in them?
I've selected the element in a page that has the links I want to the pages. They are sort of like <a href="blah">1</a>. I want to use regex with xpath so that I can get all the links like that one, whose text is \d+. I see there is an answer for it here: How to use regular expression in lxml xpath? but I can't make sen...
[ "You don't need RegExp for this XPath expression:\n//div[\n contains(\n concat(' ',@class,' '),\n ' pagination '\n )\n]/a[\n floor()=.\n]\n\n", "XPath does not provide a means to match a regexp.\nThe extension used in the post to which you link should allow the following to work, though:\n//div[con...
[ 2, 2 ]
[]
[]
[ "mechanize", "python", "regex", "xpath" ]
stackoverflow_0005697585_mechanize_python_regex_xpath.txt
Q: I'm trying to understand just exactly how to use the cmd module Let me preface this by saying: I'm a neophyte to Pyhon! I've written a bunch of modules to drive a user interactive application via the command line. Additionally, someone recommended that I look at using the cmd module. And I've looked at it on some ...
I'm trying to understand just exactly how to use the cmd module
Let me preface this by saying: I'm a neophyte to Pyhon! I've written a bunch of modules to drive a user interactive application via the command line. Additionally, someone recommended that I look at using the cmd module. And I've looked at it on some sites, but still not sure how to use it. I don't have dyslexia or any...
[ "Doug Hellmann's Python Module of the Week series has a good example of using the cmd module.\nAnother good example is the ActiveState recipe \"Console built with Cmd object\", but I think it is more complicated. ActiveState Python recipes and PyMOTW are good sources for python examples. \nYou could also see the c...
[ 8, 3 ]
[]
[]
[ "cmd", "module", "python" ]
stackoverflow_0005696233_cmd_module_python.txt
Q: DFS on a graph using a python generator I am using a generator to do a full search on a graph, the real data set is fairly large, here is a portion of the code i wrote on a small data set: class dfs: def __init__(self): self.start_nodes = [1,2] # not used, see below explanation self.end_nodes...
DFS on a graph using a python generator
I am using a generator to do a full search on a graph, the real data set is fairly large, here is a portion of the code i wrote on a small data set: class dfs: def __init__(self): self.start_nodes = [1,2] # not used, see below explanation self.end_nodes = [5,7] # not used, see below explanation ...
[ "Perhaps I'm misunderstanding your question, but it seems to me that you want to replace your __iter__ function with something like this:\ndef __iter__(self):\n for start in self.start_nodes:\n for end in self.end_nodes:\n for path in self.find_path(self._graph, start, end):\n yi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005696972_python.txt
Q: Recommendations for eCommerce Framework / Products for working with Django? We are building out an app in Django and trying to nail down what the right ecommerce framework will be to work with in Django. We've heard of Satchmo. Any other suggestions on ways to approach ecommerce in Django that's clean, simple, che...
Recommendations for eCommerce Framework / Products for working with Django?
We are building out an app in Django and trying to nail down what the right ecommerce framework will be to work with in Django. We've heard of Satchmo. Any other suggestions on ways to approach ecommerce in Django that's clean, simple, cheap and easy to implement? Thanks!
[ "Take a look on the LFS - it is much simpler then Satchmo is\n", "I did a comparison of the options here.\n" ]
[ 5, 2 ]
[]
[]
[ "django", "e_commerce", "python" ]
stackoverflow_0001674730_django_e_commerce_python.txt
Q: Using the main google maps page (not the API) in order to geocode an address Is there a way (using python) to use maps.google.com in order to get LatLng of an address? (the API doesn't support Israel, but the main page does) I tried using geopy but that doesn't seem to work. A: For Israel it's possible to use wa...
Using the main google maps page (not the API) in order to geocode an address
Is there a way (using python) to use maps.google.com in order to get LatLng of an address? (the API doesn't support Israel, but the main page does) I tried using geopy but that doesn't seem to work.
[ "For Israel it's possible to use waze.co.il instead of google:\nTheir JSON API is\nhttp://www.waze.co.il/WAS/mozi?q=yourAddress&token=yourToken\n(Also, as stated in this thread http://www.waze.co.il/forum/viewtopic.php?f=21&t=6113 reverse geocoding is a paid service.)\n" ]
[ 0 ]
[]
[]
[ "geocoding", "google_maps", "python" ]
stackoverflow_0005695300_geocoding_google_maps_python.txt
Q: web.py shared variables In web.py i need to create a shared variable, for which multiple threads(requests) can read or write to that variable. What is the preferred way, for this kind of a situation. thanks. A: I'm not sure this is really a web.py question, but we do this sort of thing all the time for process-w...
web.py shared variables
In web.py i need to create a shared variable, for which multiple threads(requests) can read or write to that variable. What is the preferred way, for this kind of a situation. thanks.
[ "I'm not sure this is really a web.py question, but we do this sort of thing all the time for process-wide caches (that is, dict caches that are shared by all request threads). We use web.py, but my example below should apply to any multi-threaded Python web server.\nhotels.py:\ncache = {}\n\ndef load_cache():\n ...
[ 2, 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0005677561_python_web.py.txt
Q: Google App Engine: How to get the offset of an object I am using Google App Engine in Python. In My database, I have some Entity which contain score of user. So I wanted to make a page on the ranking of a particular user. To do that, I need to get the 5 user with the higher score than that user and 5 user with low...
Google App Engine: How to get the offset of an object
I am using Google App Engine in Python. In My database, I have some Entity which contain score of user. So I wanted to make a page on the ranking of a particular user. To do that, I need to get the 5 user with the higher score than that user and 5 user with lower score than that user, and also the position of that part...
[ "Why not query the data twice? Once for users with a higher score, in descending order. Once for users with a lower score. Fetch five records in each query.\n", "If you really, really need the user's absolute ranking, you should use the app-engine-ranklist library. Like SQL databases, App Engine has no intrins...
[ 2, 0 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0005688079_database_google_app_engine_python.txt
Q: datetime usage for pagination I want to output the datetime as a HTTP GET parameter like this 2011-04-11 12:09:21.366575 Instead the following output appears April 11, 2011, 12:09 p.m. This change took place with an upgrade of seemingly other components so I don't understand why it changed. The code is the sam...
datetime usage for pagination
I want to output the datetime as a HTTP GET parameter like this 2011-04-11 12:09:21.366575 Instead the following output appears April 11, 2011, 12:09 p.m. This change took place with an upgrade of seemingly other components so I don't understand why it changed. The code is the same and what differs is the environme...
[ "datetime.strptime returns a datetime object from a string (given a formatting parameter). It sounds like you are looking to do the opposite (return a formatted string from a datetime object), which would be datetime.strftime. Using \"%Y-%m-%d %H:%M:%S\" as your formatting in conjunction with strftime should give...
[ 1 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0005685917_datetime_google_app_engine_python.txt
Q: Want data returned by python to javascript to be accessible inside a html div A] Technologies being used: 1] Javascript 2] Jquery (elements currently being used are Jquery tab and Jquery datatable) 3] Python 4] Google App engine B] Problem Summary: 1] I have a javascript function that calls a python class and give...
Want data returned by python to javascript to be accessible inside a html div
A] Technologies being used: 1] Javascript 2] Jquery (elements currently being used are Jquery tab and Jquery datatable) 3] Python 4] Google App engine B] Problem Summary: 1] I have a javascript function that calls a python class and gives it users city and country value. 2] The python class then queries the database an...
[ "It looks like you're using a Django template in your HTML there. This is all parsed server-side so you won't be able to use the data from the object you've returned in the inline code. Instead you need to make changes through the DOM using jQuery.\nYou've got an ajax call there, so you'll be getting a response in ...
[ 2, 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "javascript", "python" ]
stackoverflow_0005697281_ajax_google_app_engine_javascript_python.txt
Q: releasing Mac apps with wxPython and py2app that work on multiple versions of OS X I periodically release a dmg for a Python/wxPython app with py2app, and it has been working great. I only have access to a Snow Leopard machine and I would like to ensure that my app works on as many versions of OS X as possible. ...
releasing Mac apps with wxPython and py2app that work on multiple versions of OS X
I periodically release a dmg for a Python/wxPython app with py2app, and it has been working great. I only have access to a Snow Leopard machine and I would like to ensure that my app works on as many versions of OS X as possible. In the past, I have found that an app created on Snow Leopard worked on Leopard but did ...
[ "Use a Python from one of the 32-bit-only installers from python.org. They are built as 32-bit i386 and ppc using a deployment target of OS X 10.3 so they will run on all Apple systems shipped that support any version of OS X 10.3 through 10.6 (and should run on OS X 10.7 when released). Any C extension modules b...
[ 4 ]
[]
[]
[ "macos", "osx_snow_leopard", "py2app", "python", "wxpython" ]
stackoverflow_0005698175_macos_osx_snow_leopard_py2app_python_wxpython.txt
Q: Django Admin : Grouped data in the list Can I show a grouped result in Django Admin? By default, they are showing all rows, I want to group these rows based on some fields, and display it. Something like "GROUP BY username" or stuff. I've tried to search but no luck :( A: What about using list_filter='my_field' ...
Django Admin : Grouped data in the list
Can I show a grouped result in Django Admin? By default, they are showing all rows, I want to group these rows based on some fields, and display it. Something like "GROUP BY username" or stuff. I've tried to search but no luck :(
[ "What about using list_filter='my_field' in the admin.py file ?\n" ]
[ 0 ]
[ "Yes, you can.\nthis applies to the detail view of the records.\nHere is an example listed below.\nclass GroupAdmin(admin.ModelAdmin):\n form = SpecieForm\n list_display = ('species', 'latin_name', 'family', 'status')\n search_fields = ['species', 'latin_name']\n prepopulated_fields = { 'slug': ['specie...
[ -3 ]
[ "admin", "django", "python" ]
stackoverflow_0005698957_admin_django_python.txt