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: Different implementations of decorators in python Sorry for long question, but I don't know how to make it shorter. 1. Decorators without args Implementation 1.1 (through function) import time import functools def pause(f): @functools.wraps(f) def wrapper(*args, **kwargs): time.sleep(1) re...
Different implementations of decorators in python
Sorry for long question, but I don't know how to make it shorter. 1. Decorators without args Implementation 1.1 (through function) import time import functools def pause(f): @functools.wraps(f) def wrapper(*args, **kwargs): time.sleep(1) return f(*args, **kwargs) return wrapper @pause def...
[ "It sure is good that the implementations 1.2 & 2.2 are \"less common than\" 1.1 and 2.1, because they do different things. In fact, I wouldn't call them \"decorators\", because they don't really wrap (\"decorate\") the function. Instead, they only perform their action once, at the moment the decorated function is ...
[ 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0004112873_decorator_python.txt
Q: twisted web: how do I properly images from an images directory I've successfully written a twisted web server that displays dynamically generated content. However, when I attempt to display image (png) files from a directory (~cwd/plots/image.png), the server fails without error and the browser either displays the...
twisted web: how do I properly images from an images directory
I've successfully written a twisted web server that displays dynamically generated content. However, when I attempt to display image (png) files from a directory (~cwd/plots/image.png), the server fails without error and the browser either displays the alt text or the broken image icon. What am I doing wrong? import s...
[ "\nFirst: View Source at\nhttp://localhost:8007/10.53.174.1,\nyou must change code to render\ncorrect link to image.\nSecond: Use twisted.web.static.File to\nserve static content\n\nCorrected code:\nimport sys\nimport os\nfrom twisted.internet import reactor\nimport twisted.python.filepath\nfrom twisted.web.static ...
[ 1 ]
[]
[]
[ "python", "twisted", "webserver" ]
stackoverflow_0004110579_python_twisted_webserver.txt
Q: List in HTTP request I have an HTTP POST request with the following variables: "UnicodeMultiDict: ... (u'ids[]', u'568236498'), (u'ids[]', u'528900768')". It seems like it is a list, so how can I retireve these variables? When I use self.request.POST.get('ids[]') it only returns the first element. I am using the w...
List in HTTP request
I have an HTTP POST request with the following variables: "UnicodeMultiDict: ... (u'ids[]', u'568236498'), (u'ids[]', u'528900768')". It seems like it is a list, so how can I retireve these variables? When I use self.request.POST.get('ids[]') it only returns the first element. I am using the webapp framework. Thanks, J...
[ "self.request.POST.getall('ids[]') - see http://pythonpaste.org/webob/modules/webob.html#webob.multidict.MultiDict\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004113014_google_app_engine_python.txt
Q: .so module doesnt import in python: dynamic module does not define init function I am trying to write a python wrapper for a C function. After writing all the code, and getting it to compile, Python can't import the module. I am following the example given here. I reproduce it here, after fixing some typos. There ...
.so module doesnt import in python: dynamic module does not define init function
I am trying to write a python wrapper for a C function. After writing all the code, and getting it to compile, Python can't import the module. I am following the example given here. I reproduce it here, after fixing some typos. There is a file myModule.c: #include <Python.h> /* * Function to be called from Python */...
[ "Since you're using a C++ compiler, function names will be mangled (for instance, my g++ mangles void initmyModule() into _Z12initmyModulev). Therefore, the python interpreter won't find your module's init function.\nYou need to either use a plain C compiler, or force C linkage throughout your module with an extern...
[ 5 ]
[]
[]
[ "c", "c++", "python", "python_c_api", "python_extensions" ]
stackoverflow_0004112375_c_c++_python_python_c_api_python_extensions.txt
Q: How can I represent this in a Django model? I'm having trouble working out what the relationships should be with this: class Airport(models.Model): airlines = models.ManyToManyField(Airline) class Airline(models.Model): terminal = models.CharField(max_length=200) The problem is that each Airline is assoc...
How can I represent this in a Django model?
I'm having trouble working out what the relationships should be with this: class Airport(models.Model): airlines = models.ManyToManyField(Airline) class Airline(models.Model): terminal = models.CharField(max_length=200) The problem is that each Airline is associated with a different terminal depending on whic...
[ "Surprised that there are so many different answers, I guess people each have their own preferences. This is how I'd do it:\nclass Airport(models.Model):\n name = models.CharField(max_length=200)\n\nclass Airline(models.Model):\n name = models.CharField(max_length=200)\n terminals = models.ManyToManyField(...
[ 3, 0, 0 ]
[]
[]
[ "data_modeling", "django", "django_models", "python" ]
stackoverflow_0004112412_data_modeling_django_django_models_python.txt
Q: What is the Python equivalent of a Ruby class method? In ruby you can do this: class A def self.a 'A.a' end end puts A.a #-> A.a How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error: unb...
What is the Python equivalent of a Ruby class method?
In ruby you can do this: class A def self.a 'A.a' end end puts A.a #-> A.a How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error: unbound method METHOD must be called with CLASS instance as fi...
[ "What you're looking for is the staticmethod decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:\nclass A(object):\n @staticmethod\n def a():\n return 'A.a'\n\nOn the other hand, if you wish to access the class (not the instance) from the...
[ 18, 10, 0 ]
[]
[]
[ "class_method", "oop", "python", "ruby", "static_methods" ]
stackoverflow_0004112608_class_method_oop_python_ruby_static_methods.txt
Q: Writing to a .txt file (UTF-8), python I want to save the output (contents) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. file2.txt So, I fists open a file.txt, encode it in UTF-8, do some stuff and then wanna save it to file2.txt in UTF-8. How do I do ...
Writing to a .txt file (UTF-8), python
I want to save the output (contents) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. file2.txt So, I fists open a file.txt, encode it in UTF-8, do some stuff and then wanna save it to file2.txt in UTF-8. How do I do this? import codecs def openfile(filename): ...
[ "The short way:\nfile('file2.txt','w').write( file('file.txt').read().encode('utf-8') )\n\nThe long way:\ndata = file('file.txt').read()\n... process data ...\ndata = data.encode('utf-8')\nfile('file2.txt','w').write( data )\n\nAnd using 'codecs' explicitly:\ncodecs.getwriter('utf-8')(file('/tmp/bla3','w')).write(d...
[ 16, 10, 2 ]
[]
[]
[ "python", "save" ]
stackoverflow_0004112894_python_save.txt
Q: Boost::Python raw_function returning void Using Boost::Python, the normal mechanism for wrapping functions works correctly with C++ functions returning void. Unfortunately, the normal mechanism also has limitations, specifically with regards to the function arity it supports. So I need to use boost::python::raw_...
Boost::Python raw_function returning void
Using Boost::Python, the normal mechanism for wrapping functions works correctly with C++ functions returning void. Unfortunately, the normal mechanism also has limitations, specifically with regards to the function arity it supports. So I need to use boost::python::raw_function to wrap my function, but it doesn't co...
[ "I think this is the way that raw_function() works. It expects your function to return a Python object.\nIn Python the closest thing you will get to a function returning void is a function returning None. I think that approach would be best (and not even that ugly) in your case:\n#include <boost/python.hpp>\n#inclu...
[ 2 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0004111021_boost_boost_python_c++_python.txt
Q: Creating any kind of restful API with four HTTP methods only? At the moment I'm trying to build a restful HTTP backend framework. I've read a book called "Restful webservices" and it kicked off some brainwork on this area. I have now a bigger picture about why resource oriented architecture is a good thing but the...
Creating any kind of restful API with four HTTP methods only?
At the moment I'm trying to build a restful HTTP backend framework. I've read a book called "Restful webservices" and it kicked off some brainwork on this area. I have now a bigger picture about why resource oriented architecture is a good thing but there are still blurry parts I cannot understand. I'll try to explain ...
[ "You can create any system using only two methods, GET and POST, by equating GET = Read and POST = Write.\nThe other methods just help to add some visibility to the requests.\nIf you really want to try and model the REST request in terms of objects, I would do this:\nresult = new Search(Books,\"Foo\").Get();\n\nHow...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "javascript", "python", "rest", "ruby" ]
stackoverflow_0004111756_java_javascript_python_rest_ruby.txt
Q: Handle a blocking function call in Python I'm working with the Gnuradio framework. I handle flowgraphs I generate to send/receive signals. These flowgraphs initialize and start, but they don't return the control flow to my application: I imported time while time.time() < endtime: # invoke GRC flowgraph for...
Handle a blocking function call in Python
I'm working with the Gnuradio framework. I handle flowgraphs I generate to send/receive signals. These flowgraphs initialize and start, but they don't return the control flow to my application: I imported time while time.time() < endtime: # invoke GRC flowgraph for 1st sequence if not seq1_sent: ...
[ "First of all - the use of signals should be avoided at all cost:\n1) It may lead to a deadlock. SIGALRM may reach the process BEFORE the blocking syscall (imagine super-high load in the system!) and the syscall will not be interrupted. Deadlock.\n2) Playing with signals may have some nasty non-local consequences. ...
[ 6, 4, 2, 2, 1, 0, 0 ]
[ "If you want to set a timeout on a blocking function, threading.Thread as the method join(timeout) which blocks until the timeout.\nBasically, something like that should do what you want :\nimport threading\nmy_thread = threading.Thread(target=send_seq_2.top_block)\nmy_thread.start()\nmy_thread.join(TIMEOUT)\n\n" ]
[ -1 ]
[ "blocking", "gnuradio", "multithreading", "python" ]
stackoverflow_0004051261_blocking_gnuradio_multithreading_python.txt
Q: package data not installed from python .egg file I'm trying to include some data files in a python package using the setuptools package_data option. I'm then accessing the files with pkg_resources. This works perfectly when the python .egg file is installed as-is (i.e. still zipped). But when the egg file is unzip...
package data not installed from python .egg file
I'm trying to include some data files in a python package using the setuptools package_data option. I'm then accessing the files with pkg_resources. This works perfectly when the python .egg file is installed as-is (i.e. still zipped). But when the egg file is unzipped during installation, the data files are not instal...
[ "Problem solved, thanks to help from P.J. Eby on the distutils-sig email list:\nhttp://mail.python.org/pipermail/distutils-sig/2010-November/017054.html\nJust needed to rename files to avoid the '..' string.\n" ]
[ 1 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0004043315_python_setuptools.txt
Q: How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup? I'm trying to write a script so I can log into a website, but in order to do that I need to present the captcha. The only way to get that direct image of the captcha from the URL is to extract the giant string name 'chal...
How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup?
I'm trying to write a script so I can log into a website, but in order to do that I need to present the captcha. The only way to get that direct image of the captcha from the URL is to extract the giant string name 'challenge' but I have not been able to do it with BeautifulSoup for some reason. What is the best way to...
[ "BeautifulSoup does not parse js, you need to dothis with a regex or similar.\n", "I'd just use a regular expression. Not sure about this, but I don't think beautifulsoup parses javascript--only (x)html:\nchallenge = re.search(r\"challenge *: *'(\\S+)'\", x).group(1)\n\nGives: \n'03AHJ_VusE_PgNB0vfBpD2h53o8uGMt1M...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "javascript", "python" ]
stackoverflow_0004113552_beautifulsoup_javascript_python.txt
Q: Escape special character in Django Templates i'm generating password with letters, digits and special characters ('¿"&$%/\>]{}(=?)*@!<-_¡+[') and i need to escape special character in templates like ASCII symbols, i generate a list of values like this ['0iw0Vqds)*\xc2Ni1P', '<gFLbKi}55(dN[R', '5G<E\\3}+vz72vu{', '...
Escape special character in Django Templates
i'm generating password with letters, digits and special characters ('¿"&$%/\>]{}(=?)*@!<-_¡+[') and i need to escape special character in templates like ASCII symbols, i generate a list of values like this ['0iw0Vqds)*\xc2Ni1P', '<gFLbKi}55(dN[R', '5G<E\\3}+vz72vu{', 'q3ojs$S33rQW$vs', 'IhAV$@3H3uNx\xbfOI', 'uA>>u\\g\...
[ "If you're going to be using ¿ and ¡ then you're going to need to be using unicodes instead of strs.\nUnicode in Python, Completely Demystified\n" ]
[ 3 ]
[]
[]
[ "django", "django_templates", "encoding", "python", "utf_8" ]
stackoverflow_0004113559_django_django_templates_encoding_python_utf_8.txt
Q: Turn an AppEngine Blacklist into a Whitelist AppEngine allows the definition of blacklists, to disallow access from certain IP Ranges (http://code.google.com/appengine/docs/python/config/dos.html). What I would like to do is the inverse: A whitelist, that only allows access from certain IP Ranges. I am not much of...
Turn an AppEngine Blacklist into a Whitelist
AppEngine allows the definition of blacklists, to disallow access from certain IP Ranges (http://code.google.com/appengine/docs/python/config/dos.html). What I would like to do is the inverse: A whitelist, that only allows access from certain IP Ranges. I am not much of a network specialist, so I would appreciate some ...
[ "No, the AppEngine blacklist functionality (which is documented here serves more to prevent denial of service attacks and so on. So, the file containing blacklisted IPs can, at most, contain 100 IPs. Thus, the blacklist isn't really intended for industrial strength access control.\nGiven this, it seems your only op...
[ 3, 0 ]
[]
[]
[ "blacklist", "firewall", "google_app_engine", "python", "whitelist" ]
stackoverflow_0004113583_blacklist_firewall_google_app_engine_python_whitelist.txt
Q: Importing a *.pyd library in IronPython's interpreter (ipy.exe) Following this example, I've created a little hello.pyd library file, the contents of which are at the end of this question. When I enter python interpreter I get the following: D:\test\build\lib.win32-2.6>C:\Python26\python.exe Python 2.6.6 (r266:842...
Importing a *.pyd library in IronPython's interpreter (ipy.exe)
Following this example, I've created a little hello.pyd library file, the contents of which are at the end of this question. When I enter python interpreter I get the following: D:\test\build\lib.win32-2.6>C:\Python26\python.exe Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type ...
[ "You can try using Ironclad, but it hasn't seen much work recently.\n", "The answer is most likely that your .pyd library isn't in the correct path for IronPython to pick it up. Since you used Python and not IronPython's setup tools, it probably got built and setup in the PYTHONPATH rather than where it needs to ...
[ 3, 0 ]
[]
[]
[ "c++", "ironpython", "python", "python_extensions" ]
stackoverflow_0004113643_c++_ironpython_python_python_extensions.txt
Q: Hadoop/Elastic Map Reduce with binary executable? I am writing and distributed image processing application using hadoop streaming, python, matlab, and elastic map reduce. I have compiled a binary executable of my matlab code using the matlab compiler. I am wondering how I can incorporate this into my workflow so ...
Hadoop/Elastic Map Reduce with binary executable?
I am writing and distributed image processing application using hadoop streaming, python, matlab, and elastic map reduce. I have compiled a binary executable of my matlab code using the matlab compiler. I am wondering how I can incorporate this into my workflow so the binary is part of the processing on Amazon's elasti...
[ "The following is not exactly an answer to your Hadoop question, but I couldn't resist not asking why you don't execute your processing jobs on the Grid resources? There are proven solutions for executing compute intensive workflows on the Grid. And as far as I know matlab runtime environment is usually available o...
[ 0, 0 ]
[]
[]
[ "amazon_web_services", "hadoop", "mapreduce", "matlab", "python" ]
stackoverflow_0004101815_amazon_web_services_hadoop_mapreduce_matlab_python.txt
Q: python psycogp2 inserting into postgresql help I have the following code to insert do an insert into my postgresql database conn = psycopg2.connect("my connection setting are in here") cur = conn.cursor() cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % ...
python psycogp2 inserting into postgresql help
I have the following code to insert do an insert into my postgresql database conn = psycopg2.connect("my connection setting are in here") cur = conn.cursor() cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % (1441, "concert", item['title'], item['artists'] )) ...
[ "You really, really shouldn't use python string formatting to build queries - they are prone to SQL injection. And your actual problem is that you use \" for quoting while you have to use ' for quoting (\" quotes table/column names etc, ' quotes strings).\nUse the following code instead:\ncur.execute('INSERT INTO s...
[ 13 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0004113910_postgresql_psycopg2_python_sql.txt
Q: 8 Character Random Code I've been through answers to a few similar questions asked on SO, but could not find what I was looking for. Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until yo...
8 Character Random Code
I've been through answers to a few similar questions asked on SO, but could not find what I was looking for. Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has no...
[ "One option is to do it the other way round: generate a huge number of them in the database whenever you need to, then either fetch a single one from the DB when you need one, or reserve a whole bunch of them for your particular process (i.e. mark them as \"potentially used\" in the database) and then dole them out...
[ 10, 7, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "database", "java", "python", "unique" ]
stackoverflow_0004102409_algorithm_database_java_python_unique.txt
Q: .pyc files and naive encryption I have a fairly naive thing I want to do and I want to know if someone can answer can tell me if this is just flat out stupid. If what I am going to ask is not stupid but perhaps naive, I'd appreciate if I can get a nudge in a correct direction. I have a file named pwds.py. Its cont...
.pyc files and naive encryption
I have a fairly naive thing I want to do and I want to know if someone can answer can tell me if this is just flat out stupid. If what I am going to ask is not stupid but perhaps naive, I'd appreciate if I can get a nudge in a correct direction. I have a file named pwds.py. Its contents are import hashlib class Pwds: ...
[ "The .pyc file simply contains the compiled python code so it doesn't need to be recompiled everytime you run your program. Thus all strings in it are still readable (you could always look at the binary contents or step through the program via the pdb debugger).\nIf you want to protect something in your code with a...
[ 2 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0004113987_encryption_python.txt
Q: What would be the proper way of handling arguments for a method that could be ints or chars in python? For example, I want to have a method that, depending on the first argument passed, can take either an int or a char as the second argument. The way I thought of doing it is to have an if right after the method it...
What would be the proper way of handling arguments for a method that could be ints or chars in python?
For example, I want to have a method that, depending on the first argument passed, can take either an int or a char as the second argument. The way I thought of doing it is to have an if right after the method it calls to check what the first argument is, it can be one of 4. At this point, if it's of say, type 1 or 2 t...
[ "You better have two different methods if inner code is different in both cases.\n", "If the code is same, with some transformation of parameteres (getting ASCII value of char for example - btw, char in python is just a string with length of 1), you should do the cast at the start of function and the rest of the ...
[ 1, 0 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0004114055_arguments_python.txt
Q: ValueError when using Whoosh and Django Haystack I'm trying to set up Haystack with Whoosh but am getting this value error "ValueError: dictionary update sequence element #0 has length 9; 2 is required" when I run the count method on the SearchQuerySet object in ./manage shell >>> sqs.count() Traceback (most recen...
ValueError when using Whoosh and Django Haystack
I'm trying to set up Haystack with Whoosh but am getting this value error "ValueError: dictionary update sequence element #0 has length 9; 2 is required" when I run the count method on the SearchQuerySet object in ./manage shell >>> sqs.count() Traceback (most recent call last): File "<console>", line 1, in <module> ...
[ "Found my answer here https://github.com/toastdriven/django-haystack/issues/closed#issue/281 It turns out it was a version problem.\nIt works if I use these specific versions of Haystack and Whoosh\npip install django-haystack==1.0.1-final\n\neasy_install \"Whoosh==1.0.0.b11\"\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_haystack", "python", "whoosh" ]
stackoverflow_0004114040_django_django_haystack_python_whoosh.txt
Q: How can I store files on Google Storage, but skip the GAE part for fetching them? I like Google App Engine for the Datastore (and the fact that I can develop in Python) but they have 1MB limits on fetching and uploading files. On the other hand it wasn't made for that I guess. I managed to create a service that is...
How can I store files on Google Storage, but skip the GAE part for fetching them?
I like Google App Engine for the Datastore (and the fact that I can develop in Python) but they have 1MB limits on fetching and uploading files. On the other hand it wasn't made for that I guess. I managed to create a service that is getting a URL (or a file from user), fetching it on GAE and then putting it on Google ...
[ "No. Google Storage doesn't support fetching the file for you.\n", "It doesn't matter where the file is stored. Not only is there a 1MB datastore entity size limit, but there is a 1MB in-memory datastructure limit. So even if you stored the file somewhere else, you would have to split it into pieces to be able to...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_storage", "python" ]
stackoverflow_0004112903_google_app_engine_google_cloud_storage_python.txt
Q: lxml can't parse ? I want to parse tables in html, but i found lxml can't parse it? what's wrong? # -*- coding: utf8 -*- import urllib import lxml.etree keyword = 'lxml+tutorial' url = 'http://www.baidu.com/s?wd=' if __name__ == '__main__': page = 0 link = url + keyword + '&pn=' + str(page) f = urll...
lxml can't parse ?
I want to parse tables in html, but i found lxml can't parse it? what's wrong? # -*- coding: utf8 -*- import urllib import lxml.etree keyword = 'lxml+tutorial' url = 'http://www.baidu.com/s?wd=' if __name__ == '__main__': page = 0 link = url + keyword + '&pn=' + str(page) f = urllib.urlopen(link) con...
[ "lxml's documentation says, \"The support for parsing broken HTML depends entirely on libxml2's recovery algorithm. It is not the fault of lxml if you find documents that are so heavily broken that the parser cannot handle them. There is also no guarantee that the resulting tree will contain all data from the origi...
[ 3, 2 ]
[]
[]
[ "lxml", "parsing", "python", "web_crawler" ]
stackoverflow_0004093745_lxml_parsing_python_web_crawler.txt
Q: Pythonic way to select list elements with different probability import random pos = ["A", "B", "C"] x = random.choice["A", "B", "C"] This code gives me either "A", "B" or "C" with equal probability. Is there a nice way to express it when you want "A" with 30%, "B" with 40% and "C" with 30% probability? A: Weigh...
Pythonic way to select list elements with different probability
import random pos = ["A", "B", "C"] x = random.choice["A", "B", "C"] This code gives me either "A", "B" or "C" with equal probability. Is there a nice way to express it when you want "A" with 30%, "B" with 40% and "C" with 30% probability?
[ "Weights define a probability distribution function (pdf). Random numbers from any such pdf can be generated by applying its associated inverse cumulative distribution function to uniform random numbers between 0 and 1.\nSee also this SO explanation, or, as explained by Wikipedia:\n\nIf Y has a U[0,1] distribution ...
[ 52, 30, 9, 8, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004113307_python.txt
Q: what is a quick way to delete all elements from a list that do not satisfy a constraint? I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0? A: [x for x in lst if fn(x) != 0] This is a "list comprehension", on...
what is a quick way to delete all elements from a list that do not satisfy a constraint?
I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0?
[ "[x for x in lst if fn(x) != 0]\n\nThis is a \"list comprehension\", one of Python's nicest pieces of syntactical sugar that often takes lines of code in other languages and additional variable declarations, etc.\nSee: \nhttp://docs.python.org/tutorial/datastructures.html#list-comprehensions\n", "I would use a ge...
[ 7, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003895424_python.txt
Q: how to get the full contents of a node using xpath & lxml? I am using lxml's xpath function to retrieve parts of a webpage. I am trying to get contents of a <font> tag, which includes html tags of its own. If I use //td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"] I get the right a...
how to get the full contents of a node using xpath & lxml?
I am using lxml's xpath function to retrieve parts of a webpage. I am trying to get contents of a <font> tag, which includes html tags of its own. If I use //td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"] I get the right amount of nodes, but they are returned as lxml objects (<Element ...
[ "I'm not sure I understand -- is this close to what you are looking for?\nimport lxml.etree as le\nimport cStringIO\ncontent='''\\\n<font face=\"verdana\" color=\"#ffffff\" size=\"2\"><a href=\"url\">inside</a> something</font>\n'''\ndoc=le.parse(cStringIO.StringIO(content))\n\nxpath='//font[@face=\"verdana\" and @...
[ 3, 2 ]
[]
[]
[ "html", "lxml", "python", "xpath" ]
stackoverflow_0004114731_html_lxml_python_xpath.txt
Q: Vector normalization The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector. Am I doing this right in Python code? Vvx = 0-xi # view vector (calculating it from surface points) Vvy = 0-yi Vvz = 0-zi Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz)) # norm...
Vector normalization
The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector. Am I doing this right in Python code? Vvx = 0-xi # view vector (calculating it from surface points) Vvy = 0-yi Vvz = 0-zi Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz)) # normalizing Vvx = Vvx / Vv Vvy...
[ "This is misnamed. What you've written is simple vector addition of two vectors, with the result being a normalized unit vector.\nHere's how I'd do it:\nimport math\n\ndef magnitude(v):\n return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))\n\ndef add(u, v):\n return [ u[i]+v[i] for i in range(len(u)) ]\n...
[ 22 ]
[]
[]
[ "math", "python" ]
stackoverflow_0004114921_math_python.txt
Q: Greedy execution of statements? I have something like this using BeautifulSoup: for line in lines: code = l.find('span', {'class':'boldHeader'}).text coded = l.find('div', {'class':'Description'}).text definition = l.find('ul', {'class':'definitions'}).text print code, coded, def However, not all ...
Greedy execution of statements?
I have something like this using BeautifulSoup: for line in lines: code = l.find('span', {'class':'boldHeader'}).text coded = l.find('div', {'class':'Description'}).text definition = l.find('ul', {'class':'definitions'}).text print code, coded, def However, not all elements exist at all times. I can en...
[ "First of all, you can test for None instead of catching an exception. l.find should return None if it doesn't find your item. Exceptions should be reserved for errors and really extraordinary situations.\nSecond thing you can do is to create an array of all HTML elements you want to check and then have a nested fo...
[ 3, 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0004114886_beautifulsoup_python.txt
Q: Python html parsing that actually works I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds. beautifulsoup has problems after SGMLParser went away html5lib cannot parse half of what's "out there" lxml i...
Python html parsing that actually works
I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds. beautifulsoup has problems after SGMLParser went away html5lib cannot parse half of what's "out there" lxml is trying to be "too correct" for typical html...
[ "Make sure that you use the html module when you parse HTML with lxml:\n>>> from lxml import html\n>>> doc = \"\"\"<html>\n... <head>\n... <title> Meh\n... </head>\n... <body>\n... Look at this interesting use of <p>\n... rather than using <br /> tags as line breaks <p>\n... </body>\"\"\"\n>>> html.document_froms...
[ 19, 7, 3, 3, 2 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0004114722_html_parsing_python.txt
Q: python threading and shared variables how can i update a shared variable between different threading.Thread in python? lets say that i have 5 threads working down a Queue.Queue(). after the queue is done i want to do an other operation but i want it to happen only once. is it possible to share and update a variabl...
python threading and shared variables
how can i update a shared variable between different threading.Thread in python? lets say that i have 5 threads working down a Queue.Queue(). after the queue is done i want to do an other operation but i want it to happen only once. is it possible to share and update a variable betweeen the threads. so when Queue.empty...
[ "If you are using a queue to run your thread (thread pool) so you are making sure that there will not be a race condition (thread safe) because the queue run your thread in a sequential way, so i think you can share a variable between the thread and you can be sure that there will not be a race condition over this ...
[ 0, 0, 0 ]
[]
[]
[ "python", "queue", "thread_safety" ]
stackoverflow_0004115033_python_queue_thread_safety.txt
Q: Remove characters from beginning and end or only end of line I want to remove some symbols from a string using a regular expression, for example: == (that occur both at the beginning and at the end of a line), * (at the beginning of a line ONLY). def some_func(): clean = re.sub(r'= {2,}', '', clean) #Removes 2...
Remove characters from beginning and end or only end of line
I want to remove some symbols from a string using a regular expression, for example: == (that occur both at the beginning and at the end of a line), * (at the beginning of a line ONLY). def some_func(): clean = re.sub(r'= {2,}', '', clean) #Removes 2 or more occurrences of = at the beg and at the end of a line. ...
[ "If you only want to remove characters from the beginning and the end, you could use the string.strip() method. This would give some code like this:\n>>> s1 = '== foo bar =='\n>>> s1.strip('=')\n' foo bar '\n>>> s2 = '* foo bar'\n>>> s2.lstrip('*')\n' foo bar'\n\nThe strip method removes the characters given in the...
[ 12, 3, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004113716_python_regex.txt
Q: When Popen.communicate() is not enough? I found a lot of threads more or less related to this topic and still almost nothing like full answer... I'm looking for your advice on it. So, here is my problem: I really need to communicate with a subprocess in both ways: I have to wright a lot of data to its input and ge...
When Popen.communicate() is not enough?
I found a lot of threads more or less related to this topic and still almost nothing like full answer... I'm looking for your advice on it. So, here is my problem: I really need to communicate with a subprocess in both ways: I have to wright a lot of data to its input and get its output on the fly. There is no way arou...
[ "The easiest way is to split you own program in two: one which writes to LAME and the other which reads from lame and writes to the user. This is much easier to do than to have bidirectional communication.\nIf that doesn't work for you I have found development with named pipes much easier than traditional pipe IPC....
[ 2 ]
[]
[]
[ "ipc", "popen", "python", "subprocess" ]
stackoverflow_0004115051_ipc_popen_python_subprocess.txt
Q: Google Voice API Is there a way to extract the text of a transcribed voicemail using pygooglevoice? Printing the message simply prints the filename. A: As of right now, according to the pygooglevoice docs, the Python binding for the Google Voice API doesn't have any methods to get the text of a transcribed voice...
Google Voice API
Is there a way to extract the text of a transcribed voicemail using pygooglevoice? Printing the message simply prints the filename.
[ "As of right now, according to the pygooglevoice docs, the Python binding for the Google Voice API doesn't have any methods to get the text of a transcribed voicemail. However, the project is only on version 0.5, and you can make a feature request (if one hasn't already been made).\nYou can also always contribute y...
[ 0 ]
[]
[]
[ "python", "voice" ]
stackoverflow_0004115103_python_voice.txt
Q: Simple function error code: date=int(raw_input("Date:")) ammount=int(raw_input("Ammount:")) desc=str(raw_input("Description:")) account=str(raw_input("Account:")) def addEntry(date, ammount, desc, account): transact=open("transactions.txt", "w") transact.write(date, ammount, desc, account) transact.cl...
Simple function error
code: date=int(raw_input("Date:")) ammount=int(raw_input("Ammount:")) desc=str(raw_input("Description:")) account=str(raw_input("Account:")) def addEntry(date, ammount, desc, account): transact=open("transactions.txt", "w") transact.write(date, ammount, desc, account) transact.close() addEntry(date, ammou...
[ "date=int(raw_input(\"Date:\"))\nammount=int(raw_input(\"Ammount:\"))\ndesc=str(raw_input(\"Description:\"))\naccount=str(raw_input(\"Account:\"))\n\ndef addEntry(date, ammount, desc, account):\n transact=open(\"transactions.txt\", \"w\")\n transact.write('%s, %s, %s , %s' % (date, ammount, desc, account))\n ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004115275_python.txt
Q: Python argparse: nargs + or * depending on prior argument I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top: # Parse arguments p = argparse.ArgumentParser() g = p.add_mutually_exclusive_group(required=True) g.add_argument('--odam', dest='query_type', action='sto...
Python argparse: nargs + or * depending on prior argument
I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top: # Parse arguments p = argparse.ArgumentParser() g = p.add_mutually_exclusive_group(required=True) g.add_argument('--odam', dest='query_type', action='store_const', const='odam', help="Odamex Master query.") g...
[ "You can do this with an custom argparse.Action:\nimport argparse\nimport sys\n\nclass AddressAction(argparse.Action):\n def __call__(self, parser, args, values, option = None):\n args.address=values\n if args.query_type=='odam' and not args.address:\n args.address=[\n 'ma...
[ 12 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0004114996_argparse_python.txt
Q: Python sorted() key function weirdness While I was debugging some illogical behavour I came to the following weirdness in Python 2.5 sorted() function calls: >>> aa = [10, 5, 20] >>> sorted(range(len(aa))) [0, 1, 2] sorted(range(len(aa)), key=lambda a: aa[a]) [1, 0, 2] sorted(range(len(aa)), key=lambda a: -aa[a]) ...
Python sorted() key function weirdness
While I was debugging some illogical behavour I came to the following weirdness in Python 2.5 sorted() function calls: >>> aa = [10, 5, 20] >>> sorted(range(len(aa))) [0, 1, 2] sorted(range(len(aa)), key=lambda a: aa[a]) [1, 0, 2] sorted(range(len(aa)), key=lambda a: -aa[a]) [2, 0, 1] First two calls work as expected,...
[ "The value returned by the key function acts as a proxy for the values being sorted.\nSo when you say\nsorted(range(len(aa)), key=lambda a: -aa[a])\n\nyou are sorting range(len(aa)), that is [0, 1, 2], but using the values\n-aa[0], -aa[1], -aa[2] as the proxy values.\nrange(len(aa)) 0 1 2 <-- values\naa[...
[ 8, 1, 0 ]
[]
[]
[ "key", "python", "sorting" ]
stackoverflow_0004115636_key_python_sorting.txt
Q: transforming url's, python I have a txt file which contains some url's: [http://igu.org.ru/ International Geographical Union - Russian National Committee] [http://www.geografos.org Colegio de Geógrafos - España] [http://www.geografs.org Col.legi de Geògrafs - Catalunya] [http://www.geografs.org] now I want to tra...
transforming url's, python
I have a txt file which contains some url's: [http://igu.org.ru/ International Geographical Union - Russian National Committee] [http://www.geografos.org Colegio de Geógrafos - España] [http://www.geografs.org Col.legi de Geògrafs - Catalunya] [http://www.geografs.org] now I want to transform this external links in th...
[ "re1 = re.compile(r'\\[(http[^\\s]*)\\s(.*)\\]')\nre2 = re.compile(r'\\[(http[^\\s]*)\\]')\nwith codecs.open(filename, encoding='utf-8') as F:\n text = F.read()\n pre_filter = re1.sub('\\g<2>', text)\n result = re2.sub('\\g<1>', pre_filter)\n\nto process the your text. \nFor further informations in the bac...
[ 2 ]
[]
[]
[ "python", "regex", "url" ]
stackoverflow_0004115585_python_regex_url.txt
Q: Import error and PythonPath I'm trying to understand what the issue is: I'm trying to import a module: from main.models import Main from django.contrib import admin admin.site.register(Main) However, when I attempt to hit the admin site, I get a django error page: ImportError at /admin/ cannot import name Main ...
Import error and PythonPath
I'm trying to understand what the issue is: I'm trying to import a module: from main.models import Main from django.contrib import admin admin.site.register(Main) However, when I attempt to hit the admin site, I get a django error page: ImportError at /admin/ cannot import name Main I noticed that it provides a dump...
[ "PYTHONPATH can be accessed via:\nimport sys\nprint sys.path\n\nA bit of debugging to try would be to use:\nfrom main import models\nfrom django.contrib import admin\n\nadmin.site.register(models.Main)\n\nand see if that gives you any more information.\n", "Do you have an __init__.py in /Users/brian/src/SampleApp...
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004115827_django_python.txt
Q: Tkinter Toplevel Widget def WhoisWin(): win1 = Toplevel() win1.title("Whois") win1.config(bg="black") win1.geometry("300x300") win1.resizable(0,0) text = Text() text1 = Text() text1.config(width=15, height=1) text1.config(bg="black", fg="white") text1.pack() def button1(): s = socket.socket(socket....
Tkinter Toplevel Widget
def WhoisWin(): win1 = Toplevel() win1.title("Whois") win1.config(bg="black") win1.geometry("300x300") win1.resizable(0,0) text = Text() text1 = Text() text1.config(width=15, height=1) text1.config(bg="black", fg="white") text1.pack() def button1(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
[ "You don't provide a parent for text or text1. When you call Text() you need to give it an argument like Text(win1) or Text(frame) so that Tkinter knows what to pack the Text widget on.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004116157_python_tkinter.txt
Q: TypeError when running Mercurial on AppEngine When I run "ported" Mercurial on GAE (from http://bitbucket.org/durin42/mercurial-appengine/), I meet: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(...
TypeError when running Mercurial on AppEngine
When I run "ported" Mercurial on GAE (from http://bitbucket.org/durin42/mercurial-appengine/), I meet: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/yt-source/1.3...
[ "Found the problems: We need to use Mercurial 1.6.4 or older... Newest version (1.7) is not supported by appengine-mercurial\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "mercurial", "python", "syntax" ]
stackoverflow_0004112441_google_app_engine_mercurial_python_syntax.txt
Q: How I am doing Ajax with Django now: looking for advices/comments I would like share with you how I am doing my Ajax stuff with Django for the moment. I would like have your advices/comments to see if I am doing it right. I will of course oversimplified the code, just to show the process. Here is my template code:...
How I am doing Ajax with Django now: looking for advices/comments
I would like share with you how I am doing my Ajax stuff with Django for the moment. I would like have your advices/comments to see if I am doing it right. I will of course oversimplified the code, just to show the process. Here is my template code: <!-- I store the full url to access object details so I can use url fe...
[ "Nothing wrong with the Django code but you may want it to work for non javascript clients as well and use valid HTML:\n<ul>\n{% for item in items %}\n <li><a href=\"{{ item.get_absolute_url }}\">{{ item.name }}</a></li>\n{% endfor %}\n<ul>\n\n$(\"a\").click(function(){\n // I just reuse the url attribute fro...
[ 2, 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0004116402_ajax_django_python.txt
Q: Match specific string + any float number in python I am writing a script for Luxology modo (3D and VFX application), which is using python as scripting language. Somewhere in my script i am reading text file outputted from other app, and creating materials and image maps from the lines of this text file. one of th...
Match specific string + any float number in python
I am writing a script for Luxology modo (3D and VFX application), which is using python as scripting language. Somewhere in my script i am reading text file outputted from other app, and creating materials and image maps from the lines of this text file. one of the things i am doing there is creating a dictionary of th...
[ "You can do this using standard string methods to strip the coefficient from the string if it begins with 'displacement':\nfor material in materials[mat].keys():\n if material.startswith('displacement'):\n # coefficient = float(material.split('displacement')[1])\n material = material.rstrip('012345...
[ 1, 0, 0 ]
[]
[]
[ "3d", "python" ]
stackoverflow_0004113948_3d_python.txt
Q: anyone knows why my program is not giving result? import copy class Polynomial(dict): def __init__(self, coefficients): self.coeff = coefficients def dictionary(self,x): sum=0.0 d=self.coeff for k in d: sum +=d[k]*x**k return sum def __add__(self, ot...
anyone knows why my program is not giving result?
import copy class Polynomial(dict): def __init__(self, coefficients): self.coeff = coefficients def dictionary(self,x): sum=0.0 d=self.coeff for k in d: sum +=d[k]*x**k return sum def __add__(self, other): new=copy.deepcopy(self) for k,d i...
[ "Iterating over a dict yields keys, not items.\nfor k, value in other.coeff.iteritems():\n\n", " for k in d:\n sum +=d[k]*x**k\n return sum\n\nchange to\n for k, v in d.iteritems():\n sum +=v*x**k\n return sum\n\nEDIT: I see the problem...\nin __add__(), value is not defined therefore it...
[ 4, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004117038_class_python.txt
Q: Confused by self["name"] = filename I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes: class FileInfo(UserDict): "store file metadata" def __in...
Confused by self["name"] = filename
I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes: class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDi...
[ "[...] isn't just for lists. Any type can support it, and the index doesn't necessarily have to be an integer. self is the current object, which according to your code derives from UserDict, which supports the item manipulation methods.\n", "You're extending a dictionary, by doing class FileInfo(UserDict), that's...
[ 6, 2, 2, 2, 2 ]
[]
[]
[ "python", "self" ]
stackoverflow_0004117060_python_self.txt
Q: How do I use the Twitter streaming API? stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41],track=["twitpic"]) This works. However, it's not "AND". It's "OR". This line gets the location OR keyword. How do I make it "AND"? Here's the code to the library I'm using: def filter(self, follow=None, trac...
How do I use the Twitter streaming API?
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41],track=["twitpic"]) This works. However, it's not "AND". It's "OR". This line gets the location OR keyword. How do I make it "AND"? Here's the code to the library I'm using: def filter(self, follow=None, track=None, async=False, locations=None): ...
[ "http://dev.twitter.com/pages/streaming_api_methods#locations\n\nBounding boxes are logical ORs. A\n locations parameter may be combined\n with track parameters, but note that\n all terms are logically ORd, so the\n query string\n track=twitter&locations=-122.75,36.8,-121.75,37.8\n would match any tweets cont...
[ 2 ]
[]
[]
[ "api", "http", "python", "streaming", "twitter" ]
stackoverflow_0004116799_api_http_python_streaming_twitter.txt
Q: how to speed up my couchdb views written with python I'm writing my couchdb views with python. I think it's not very ... pythonic to do something like def fun(doc): import re # do something with re yield 1, 1 because re is for every document imported. putting import re at the beginning gives me an err...
how to speed up my couchdb views written with python
I'm writing my couchdb views with python. I think it's not very ... pythonic to do something like def fun(doc): import re # do something with re yield 1, 1 because re is for every document imported. putting import re at the beginning gives me an error (string should compile to a proper function), a del r...
[ "View server handles many documents with same context. So import re really imports module only while handles first document. All other map calls will only lookup sys.modules.\n", "I got into the same trouble recently and solved it like this:\nimport re\n\ndef foo(doc, re_xx=re.compile(\"required-pattern\")):\n ...
[ 1, 1, 0 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0004079838_couchdb_python.txt
Q: Better ways to handle AppEngine requests that time out? Sometimes, with requests that do a lot, Google AppEngine returns an error. I have been handling this by some trickery: memcaching intermediate processed data and just requesting the page again. This often works because the memcached data does not have to be...
Better ways to handle AppEngine requests that time out?
Sometimes, with requests that do a lot, Google AppEngine returns an error. I have been handling this by some trickery: memcaching intermediate processed data and just requesting the page again. This often works because the memcached data does not have to be recalculated and the request finishes in time. However... ...
[ "I have been handling something similar by building a custom automatic retry dispatcher on the client. Whenever an ajax call to the server fails, the client will retry it.\nThis works very well if your page is ajaxy. If your app spits entire HTML pages then you can use a two pass process: first send an empty page c...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004112235_google_app_engine_python.txt
Q: Is it a bad idea to nest importing declarations in Python? I'm reading App Engine's documentation and i saw that i could nest some imports, for example: from google.appengine.ext import db, webapp #so on Is it a bad thing to do so? If it's not (since it works), what's the limit/advantages/disadvantages of that? ...
Is it a bad idea to nest importing declarations in Python?
I'm reading App Engine's documentation and i saw that i could nest some imports, for example: from google.appengine.ext import db, webapp #so on Is it a bad thing to do so? If it's not (since it works), what's the limit/advantages/disadvantages of that?
[ "That's not nesting, that's just importing specific names. There's nothing wrong with that per se, but as always consult PEP 8 for style guidelines.\n", "No it's not. See the PEP8 python styling standards. Here's the pertinent excerpt:\nImports\n\n- Imports should usually be on separate lines, e.g.:\n\n Yes: ...
[ 3, 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0004112042_import_python.txt
Q: PHP in command line Using Python I can test my code in the terminal / command line by typing python python> print "hello world" I would like to do this with PHP too, but when typing: php echo "hello world"; it does not work.. Is this possible? what should I do? A quick search on the internet gives a lot of res...
PHP in command line
Using Python I can test my code in the terminal / command line by typing python python> print "hello world" I would like to do this with PHP too, but when typing: php echo "hello world"; it does not work.. Is this possible? what should I do? A quick search on the internet gives a lot of results that call an actual ...
[ "Try \nphp -a\n\nwhich starts an interactive PHP shell. Be aware that this requires PHP to be built with --with-readline (which is not the case if you're using the bundeled PHP with Mac OS X e.g.).\nAlternatively, if you don't require the interactivity of a separate shell, use\nphp -r 'print_r(get_defined_constants...
[ 8, 1, 1 ]
[]
[]
[ "code_testing", "command_line", "php", "python", "terminal" ]
stackoverflow_0004117447_code_testing_command_line_php_python_terminal.txt
Q: Clearing a log file which is in use On my job, I am working with a big .NET application which writes to a log file. Let's call the application CompanyApplication. I have written a simple Python script which clears the log: file_object = open('C:\\log.txt', 'w') file_object.write("") file_object.close() When Compa...
Clearing a log file which is in use
On my job, I am working with a big .NET application which writes to a log file. Let's call the application CompanyApplication. I have written a simple Python script which clears the log: file_object = open('C:\\log.txt', 'w') file_object.write("") file_object.close() When CompanyApplication.exe is not running this wor...
[ "You need to fill out the FileShare parameter for the open call on the log file in your .NET program.\nSpecifically you will want to allow read/write sharing.\nDepending on how your .NET application works when writing to the log though, what you are suggesting might not work as expected and may cause problems with ...
[ 3, 1, 0 ]
[]
[]
[ ".net", "file_io", "file_permissions", "python" ]
stackoverflow_0004117596_.net_file_io_file_permissions_python.txt
Q: Error when importing module, dlopen(): Symbol not found I have written a python extension in C (using cython, actually, though that's beside the point) which uses the AudioUnit framework in Mac OSX. The module builds correctly, but when I try to import it from the python command line, I get the following error: I...
Error when importing module, dlopen(): Symbol not found
I have written a python extension in C (using cython, actually, though that's beside the point) which uses the AudioUnit framework in Mac OSX. The module builds correctly, but when I try to import it from the python command line, I get the following error: ImportError: dlopen(myproject/audiomodule.so, 2): Symbol not f...
[ "Bah, as was written in this answer regarding a similar question, the key was to pass the -framework and AudioUnit arguments as two separate tuple items. Furthermore, my platform detection was incorrect, so these flags were not being applied correctly during the build.\n" ]
[ 2 ]
[]
[]
[ "dlopen", "python" ]
stackoverflow_0004115702_dlopen_python.txt
Q: Properly evaluating double integral in python I am trying to compute a definite double integral using scipy. The integrand is a bit complicated, as it contains some probability distributions to give weight to how likely is each value of x and y (like a mixture model). The following code evaluated to a negative num...
Properly evaluating double integral in python
I am trying to compute a definite double integral using scipy. The integrand is a bit complicated, as it contains some probability distributions to give weight to how likely is each value of x and y (like a mixture model). The following code evaluated to a negative number, but it should be bound by [0,1]. Additionally,...
[ "There are several ways to increase the speed of your computation.\n\nYou can use the epsabs and epsrel parameters to dblquad to increase the tolreance of your integration. Of course, your results will be less accurate, but for debugging this is fine.\nYou can considerably reduce the number of function evaluations...
[ 1, 0 ]
[]
[]
[ "integration", "python", "scipy" ]
stackoverflow_0004035369_integration_python_scipy.txt
Q: 3D grid interpolation in Python I have a regularly sampled grid, x,y,z and variable v. I would like to interpolate based on given x,y, &z values. I do not want to use numpy or scipy, because they are not installed on the platform I will be running on. If I can locate the surrounding 8 grid nodes what math can I u...
3D grid interpolation in Python
I have a regularly sampled grid, x,y,z and variable v. I would like to interpolate based on given x,y, &z values. I do not want to use numpy or scipy, because they are not installed on the platform I will be running on. If I can locate the surrounding 8 grid nodes what math can I use to interpolate? Thanks
[ "This actually seems to be a math question, but you also mentioned Python, so I try to give some code. You would usually use trilinear interpolation.\nSo we assume your grid has the corners (0.0, 0.0, 0.0) and (max_x, max_y, max_z) and is aligned with the coordinate system. We denote the number of cells along eac...
[ 2 ]
[]
[]
[ "grid", "interpolation", "python" ]
stackoverflow_0004117172_grid_interpolation_python.txt
Q: Find in a dynamic pythonic way the minimum elements in a partially ordered set Let Os be a partially ordered set, and given any two objects O1 and O2 in Os, F(O1,O2) will return 1 if O1 is bigger than O2, -1 if O1 is smaller than O2, 2 if they are incomparable, and 0 if O1 is equal to O2. I need to find the subset...
Find in a dynamic pythonic way the minimum elements in a partially ordered set
Let Os be a partially ordered set, and given any two objects O1 and O2 in Os, F(O1,O2) will return 1 if O1 is bigger than O2, -1 if O1 is smaller than O2, 2 if they are incomparable, and 0 if O1 is equal to O2. I need to find the subset Mn of elements is Os that are the minimum. That is for each A in Mn, and for each B...
[ "GetMinOs2 below, \"dynamically\" removes elements which are known to be non-minimal. It uses a list Ol which starts with all the elements of Os. \nA \"pointer\" index l points to the \"end\" of the list Ol. When a non-minimal element is found, its position is swapped with the value in Ol[l] and the pointer l is d...
[ 2 ]
[]
[]
[ "algorithm", "math", "python" ]
stackoverflow_0004117859_algorithm_math_python.txt
Q: How to gain root privileges in python via a graphical sudo? Part of my python program needs administrator access. How can I gain root privileges using a GUI popup similar to the gksudo command? I only need root privileges for a small part of my program so it would be preferable to only have the privileges for a pa...
How to gain root privileges in python via a graphical sudo?
Part of my python program needs administrator access. How can I gain root privileges using a GUI popup similar to the gksudo command? I only need root privileges for a small part of my program so it would be preferable to only have the privileges for a particular function. I'm hoping to be able to do something like: gk...
[ "gksudo can be used to launch programs running with administrator privileges. The part of your application that needs to run as root, must be able to be invoked as a separate process from the command line. If you need some form of communication between the two, you could use sockets or watch for a file, etc.\n", ...
[ 4, 3 ]
[]
[]
[ "gksudo", "python" ]
stackoverflow_0004112737_gksudo_python.txt
Q: Django model formsets - modifying form labels and defaults I'm building a formset like so: InterestFormSet = modelformset_factory(Interest, \ formset=BaseInterestFormSet, exclude=('userid',), extra=2) And I want set default labels and values for elements of this form. I know that in simple forms I can use th...
Django model formsets - modifying form labels and defaults
I'm building a formset like so: InterestFormSet = modelformset_factory(Interest, \ formset=BaseInterestFormSet, exclude=('userid',), extra=2) And I want set default labels and values for elements of this form. I know that in simple forms I can use the fields dict to change these things for specific fields of the ...
[ "Something like this should do what you want:\nclass InterestForm(ModelForm):\n pub_date = DateField(label='Publication date')\n\n class Meta:\n model = Interest\n exclude = ('userid',)\n\n\nInterestFormSet = modelformset_factory(Interest, form=InterestForm, extra=2)\n\n", "Formsets don't have...
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004115541_django_django_forms_python.txt
Q: Get second element text with XPath? <span class='python'> <a>google</a> <a>chrome</a> </span> I want to get chrome and have it working like this already. q = item.findall('.//span[@class="python"]//a') t = q[1].text # first element = 0 I'd like to combine it into a single XPath expression and just get one it...
Get second element text with XPath?
<span class='python'> <a>google</a> <a>chrome</a> </span> I want to get chrome and have it working like this already. q = item.findall('.//span[@class="python"]//a') t = q[1].text # first element = 0 I'd like to combine it into a single XPath expression and just get one item instead of a list.I tried this but it ...
[ "\nI tried this but it doesn't work.\nt = item.findtext('.//span[@class=\"python\"]//a[2]')\n\n\nThis is a FAQ about the // abbreviation. \n.//a[2] means: Select all a descendents of the current node that are the second a child of their parent. So this may select more than one element or no element -- depending on ...
[ 42, 2, 2 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0004117953_lxml_python_xpath.txt
Q: MemoryError, python I got a MemoryError when processing a .xml file = 1,45 Gb. I tried to run it on a smaller file and it works, so there shouldn't be any bugs in the code. The code, itself, implies to open a xml file, do some stuff inside and save it back to a new txt file. I run Win7 x86, 2 Gb RAM, Python 2.6 Tr...
MemoryError, python
I got a MemoryError when processing a .xml file = 1,45 Gb. I tried to run it on a smaller file and it works, so there shouldn't be any bugs in the code. The code, itself, implies to open a xml file, do some stuff inside and save it back to a new txt file. I run Win7 x86, 2 Gb RAM, Python 2.6 Traceback (most recent call...
[ "Since building an in-memory tree is not desirable (and in your case not practical either, given the amount of physical memory you have), there are two techniques you can use with lxml:\n\nSupplying a target parser class\nUsing the iterparse method\n\nRefer to the documentation here to see how this can be done. \n"...
[ 8, 0 ]
[]
[]
[ "error_handling", "python", "xml" ]
stackoverflow_0004118409_error_handling_python_xml.txt
Q: Is 'if q and r:' evaluated separately? It's a very simple question. Is if q and r: always guaranteed to be equivalent to this? if q: if r: A: Python's and and or are short-circuiting operators, so yes: in your example, if "q" is false, then the interpreter will not evaluate "r". edit — after a little thought ...
Is 'if q and r:' evaluated separately?
It's a very simple question. Is if q and r: always guaranteed to be equivalent to this? if q: if r:
[ "Python's and and or are short-circuiting operators, so yes: in your example, if \"q\" is false, then the interpreter will not evaluate \"r\".\nedit — after a little thought it occurs to me that it's important to note that Python's and and or work kind-of like Javascript && and ||. They do not produce a boolean res...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0004118433_python.txt
Q: Adding audio to video produced from OpenCV I've been using OpenCV under python to record video from a capture device. Two output AVI's are written each hour, at the top of each hour the file names are changed. One of the files is the original capture and one uses some of OpenCV's detection functions. As always, th...
Adding audio to video produced from OpenCV
I've been using OpenCV under python to record video from a capture device. Two output AVI's are written each hour, at the top of each hour the file names are changed. One of the files is the original capture and one uses some of OpenCV's detection functions. As always, things change and audio needs to be recorded which...
[ "The pyaudio module may fit your needs, it is a wrapper aroung portaudio. On MacOsX, this hack installs the portaudio libray:\nsvn co https://www.portaudio.com/repos/portaudio/trunk portaudio\ncd portaudio/\n./configure\nmake\nsudo make install\nsudo /usr/bin/install -c -m 644 -m 644 ./include/pa_mac_core.h /usr/lo...
[ 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0003846634_opencv_python.txt
Q: django Facebook Registration Process I've been searching some topics concerning facebook registration. Its just that i cant find any topics on how to save the user's facebook data to my users model. Currently, users can Login successfully in my site. here's my code: base.html <div id="fb-root"></div> <script type=...
django Facebook Registration Process
I've been searching some topics concerning facebook registration. Its just that i cant find any topics on how to save the user's facebook data to my users model. Currently, users can Login successfully in my site. here's my code: base.html <div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = fu...
[ "Does this help you: Facebook Connect: capturing user data with django-profiles and django-socialregistration or you need a more verbose answer?\nEDIT:\nthat facebook.GraphAPI thing can be imported from this: https://github.com/facebook/python-sdk/\n" ]
[ 1 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0004117898_django_facebook_python.txt
Q: Prevent OpenCV function CreateVideoWriter from printing to console in Python I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally redir...
Prevent OpenCV function CreateVideoWriter from printing to console in Python
I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally redirect it into a variable. Output #0, avi, to 'temp/Temp.0433.avi': Stream #0.0: ...
[ "I think the easiest way for you to do this is temporarily to redirect sys.stdout while calling the messy function -- anything else will force you to change the Python bindings.\nFortunately, this is easy: just use a contextmanager:\n>>> import contextlib\n>>> @contextlib.contextmanager\n... def stdout_as(stream):\...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0004118460_opencv_python.txt
Q: Is there a (simple) way to parse CRL in Python? I'm trying to do something stupid: load a CRL and output the list of revoked certificates serials. With M2Crypto loading the CRL is done with: import M2Crypto crl = M2crypto.X509.load_crl('my.crl') But i'm really surpised that the returned object has only one useful...
Is there a (simple) way to parse CRL in Python?
I'm trying to do something stupid: load a CRL and output the list of revoked certificates serials. With M2Crypto loading the CRL is done with: import M2Crypto crl = M2crypto.X509.load_crl('my.crl') But i'm really surpised that the returned object has only one usefull which is crl.as_text() With some regexp, i can pa...
[ "Job's done thanks to pyOpenSSL. Here is the code to use :\nimport OpenSSL\n\nwith open('path_to_the_crl', 'r') as _crl_file:\n crl = \"\".join(_crl_file.readlines())\n\ncrl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)\n\nrevoked_objects = crl_object.get_revoked()\n\nfor rvk in revoked_obje...
[ 10, 3 ]
[]
[]
[ "certificate_revocation", "pki", "python", "x509" ]
stackoverflow_0004115523_certificate_revocation_pki_python_x509.txt
Q: read a file contains list and comma separation in python I have a file(.txt) which contains: [0 1,1 1,3 2,4 1] I want to read the file in this way: 0 1 /n 1 1 /n 3 2 /n 4 1 /n I have problem how to eliminate brackets and separate each line by comma. Thanks for your suggestions :) A: >>> s = "[0 1,1 1,3 2,4 1]"...
read a file contains list and comma separation in python
I have a file(.txt) which contains: [0 1,1 1,3 2,4 1] I want to read the file in this way: 0 1 /n 1 1 /n 3 2 /n 4 1 /n I have problem how to eliminate brackets and separate each line by comma. Thanks for your suggestions :)
[ ">>> s = \"[0 1,1 1,3 2,4 1]\"\n>>> print '\\n'.join(s[1:-1].split(','))\n0 1\n1 1\n3 2\n4 1\n\n", "A different method that will also work if the brackets are not the first and the last character:\nprint s[s.index(\"[\")+1:s.index(\"]\")].replace(\",\", \"\\n\")\n\nIf the brackets always are the ifrst and the las...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004118748_python.txt
Q: I want to nest loop ten times, Is there any better way than this? Something like this. I want to brute force all characters with word of 10 size lookup = map(chr, range(32, 127)) for i in lookup: for j in lookup: for k in lookup: for l in lookup: for m in lookup: ...
I want to nest loop ten times, Is there any better way than this?
Something like this. I want to brute force all characters with word of 10 size lookup = map(chr, range(32, 127)) for i in lookup: for j in lookup: for k in lookup: for l in lookup: for m in lookup: for n in lookup: for o in lookup: ...
[ "While using the existing itertools package is normally better than rolling your own code, for educational value it's good to know how to do this yourself.\nObviously, nesting ten loops is not the best approach. I say \"obviously\" because it should immediately raise a red flag in your mind when you have to copy an...
[ 13, 8, 1, 0 ]
[]
[]
[ "perl", "programming_languages", "python" ]
stackoverflow_0004118684_perl_programming_languages_python.txt
Q: How do I update information in my datastore? I need to check if the item is in datastore before I update it. I have 2 lists: UNIQUES = ["B","K","V"] and COUNTS = [5, 10, 3] This is the model: class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.TextProperty() mCOUNT = db....
How do I update information in my datastore?
I need to check if the item is in datastore before I update it. I have 2 lists: UNIQUES = ["B","K","V"] and COUNTS = [5, 10, 3] This is the model: class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.TextProperty() mCOUNT = db.IntegerProperty() mDATE = db.DateTimeProperty(...
[ "The problem is that the query is trying to filter mUNIQUE. However, you declared mUNIQUE as a db.TextProperty which is never indexed. As a result, you query never finds any results.\nSolution: Change mUNIQUE to a db.StringProperty (which is indexed by default).\nYou should also consider updating Rep in a transac...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004118776_google_app_engine_google_cloud_datastore_python.txt
Q: How to search a Python List via Object Attribute? Consider the following python class: class Event(Document): name = StringField() time = DateField() location = GeoPointField() def __unicode__(self): return self.name Now I create a list of Events: x = [Event(name='California Wine Mixer'), Event(nam...
How to search a Python List via Object Attribute?
Consider the following python class: class Event(Document): name = StringField() time = DateField() location = GeoPointField() def __unicode__(self): return self.name Now I create a list of Events: x = [Event(name='California Wine Mixer'), Event(name='American Civil War'), Event(name='Immaculate Conce...
[ "By unique I think you want something like \"if a.name not in x(Event.name):\", which can be written as\nif not any(y.name == a.name for y in x):\n ...\n\nBut if the name acts as an index, it is better to use a dictionary to avoid the O(N) searching time and the more complex interface.\nevent_list = [Event(name='C...
[ 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004119248_list_python.txt
Q: redefine default filtering behavior in Django templates I have a project with many DecimalFields that are rendered in more than 300 templates. I would like that these decimal fields are rendered normalized. I don't care about precission or anything: decimal.Decimal("10.0000").normalize() I haven't found a way to ...
redefine default filtering behavior in Django templates
I have a project with many DecimalFields that are rendered in more than 300 templates. I would like that these decimal fields are rendered normalized. I don't care about precission or anything: decimal.Decimal("10.0000").normalize() I haven't found a way to change default rendering system. I know there is a humanize a...
[ "You could create a subclass of DecimalField where you override DecimalField.__str__ or DecimalField.__unicode__ to suit your needs. This method is called whenever the value needs to be rendered in a template or whatnot. You would only need to change your models.\nThe code for theField class is here. DecimalField i...
[ 2 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0004119151_django_django_models_django_templates_python.txt
Q: Python urlparse: small issue I'm making an app that parses html and gets images from it. Parsing is easy using Beautiful Soup and downloading of the html and the images works too with urllib2. I do have a problem with urlparse to make absolute paths out of relative ones. The problem is best explained with an examp...
Python urlparse: small issue
I'm making an app that parses html and gets images from it. Parsing is easy using Beautiful Soup and downloading of the html and the images works too with urllib2. I do have a problem with urlparse to make absolute paths out of relative ones. The problem is best explained with an example: >>> import urlparse >>> urlpar...
[ "\"..\" would bring you up one directory (\".\" is current directory), so combining that with a domain name url doesn't make much sense. Maybe what you need is:\n>>> urlparse.urljoin(\"http://www.example.com\",\"./test.png\")\n'http://www.example.com/test.png'\n\n", "I think the best you can do is to pre-parse th...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "urllib2", "urlparse" ]
stackoverflow_0004114225_python_urllib2_urlparse.txt
Q: Find the closest hour I have a list with these items: hours = ['19:30', '20:10', '20:30', '21:00', '22:00'] Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide. A: >>> import datetime >>> hours = ['19:30', '20:10', '20:30', '2...
Find the closest hour
I have a list with these items: hours = ['19:30', '20:10', '20:30', '21:00', '22:00'] Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide.
[ ">>> import datetime\n>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']\n>>> now = datetime.datetime.strptime(\"20:18\", \"%H:%M\")\n>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, \"%H:%M\")))\n'20:10'\n\n", "easy but dirty way\nmax(t for t in sorted(hours) if t<=now)\n\n", "I'm no...
[ 10, 5, 2, 1, 1, 1 ]
[]
[]
[ "arrays", "python", "time" ]
stackoverflow_0004118526_arrays_python_time.txt
Q: Dictionaries in Python I have a dictionary that has a place name as a key and as the value it has several lists of words, eg, 1 entry looks like: {'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell'...
Dictionaries in Python
I have a dictionary that has a place name as a key and as the value it has several lists of words, eg, 1 entry looks like: {'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell', u'yet,', u'but', u'all', u...
[ "This function takes a list of a list of words, and returns all words that are found in all the lists.\neg get_common_words([['hi', 'hello'], ['bye', 'hi']]) returns ['hi']\ndef get_common_words(places):\n common_words = []\n for word in places[0]:\n is_common = all(word in place for place in places[1:...
[ 2, 1, 1 ]
[]
[]
[ "dictionary", "keyword", "python" ]
stackoverflow_0004119404_dictionary_keyword_python.txt
Q: Python Regular Expression I'd like to extract the designator and ops from the string designator: op1 op2, in which there could be 0 or more ops and multiple spaces are allowed. I used the following regular expression in Python import re match = re.match(r"^(\w+):(\s+(\w+))*", "des1: op1 op2") The problems is th...
Python Regular Expression
I'd like to extract the designator and ops from the string designator: op1 op2, in which there could be 0 or more ops and multiple spaces are allowed. I used the following regular expression in Python import re match = re.match(r"^(\w+):(\s+(\w+))*", "des1: op1 op2") The problems is that only des1 and op2 is found i...
[ "both are 'found', but only one can be 'captured' by the group. if you need to capture more than one group, then you need to use the regular expression functionality multiple times. You could do something like this, first by rewriting the main expression: \nmatch = re.match(r\"^(\\w+):(.*)\", \"des1: op1 op2\")...
[ 4, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004119599_python_regex.txt
Q: Django - converting URL into links, images, objects I'm creating simple comment-like application and need to convert normal urls into links, image links into images and yt/vimeo/etc. links into flash objects. E.g.: http://foo.bar to <a href="http://foo.bar">http://foo.bar</a> http://foo.bar/image.gif to <img src="...
Django - converting URL into links, images, objects
I'm creating simple comment-like application and need to convert normal urls into links, image links into images and yt/vimeo/etc. links into flash objects. E.g.: http://foo.bar to <a href="http://foo.bar">http://foo.bar</a> http://foo.bar/image.gif to <img src="http://foo.bar/image.gif"/> etc. Of course i can write a...
[ "Write a custom filter to handle all the necessary cases. Look at the source code for urlize to get started. You'll also need the urlize function from utils.\nIn your filter, first test for the first case and call urlize on that. Handle the second case and any other cases you may have.\n" ]
[ 4 ]
[]
[]
[ "django", "filter", "parsing", "python" ]
stackoverflow_0004119813_django_filter_parsing_python.txt
Q: Interpreter in Python: Making your own programming language? Remember, this is using python. Well, I was fiddling around with an app I made called Pyline, today. It is a command line-like interface, with some cool features. However, I had an idea while making it: Since its like a "OS", wont it have its own languag...
Interpreter in Python: Making your own programming language?
Remember, this is using python. Well, I was fiddling around with an app I made called Pyline, today. It is a command line-like interface, with some cool features. However, I had an idea while making it: Since its like a "OS", wont it have its own language? Well, I have seen some articles online on how to make a interpr...
[ "You need some grounding first in order to actually create a programming language.\nI strongly suggest picking up a copy of Programming Language Pragmatics, which is quite readable (much more so than the Dragon book) and suitable for self study.\nOnce you are ready to start messing with parsers, ANTLR is the \"gold...
[ 10, 2, 1, 1 ]
[]
[]
[ "compiler_construction", "interpreter", "parsing", "python" ]
stackoverflow_0003115971_compiler_construction_interpreter_parsing_python.txt
Q: QTreeView and QDataWidgetMapper interaction So I have a QTreeView witdget connected to a model, and the same model connected to a QDataWidgetMapper object which connects to a few LineEdits. My problem is that I can't figure out how to change the QDataWidgetMapper index when I click on another item in the QTreeView...
QTreeView and QDataWidgetMapper interaction
So I have a QTreeView witdget connected to a model, and the same model connected to a QDataWidgetMapper object which connects to a few LineEdits. My problem is that I can't figure out how to change the QDataWidgetMapper index when I click on another item in the QTreeView... I tried this connect: i = QtCore.QModelIndex...
[ "You cannot connect the result of method execution as slot, but you try.\nWhat you need to do is:\nself.ui.MyQTree.clicked.connect(self.MyDataMapper.setCurrentIndex)\n\nand the index, that view will provide when 'clicked' fires will be transferred to slot.\n" ]
[ 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0004112720_pyqt_python.txt
Q: Threading to quickly create a large number of charts I have been trying to find ways to make the following piece of code perform faster: def do_chart(target="IMG_BACK", xlabel="xlabel", ylabel="ylabel", title="title", ydata=pylab.arange(1961, 2031, 1)): global MYRAMDICT MYRAMDICT = {} print "here...
Threading to quickly create a large number of charts
I have been trying to find ways to make the following piece of code perform faster: def do_chart(target="IMG_BACK", xlabel="xlabel", ylabel="ylabel", title="title", ydata=pylab.arange(1961, 2031, 1)): global MYRAMDICT MYRAMDICT = {} print "here" for i in range(70): MYRAMDICT[i] = cStringIO...
[ "For the description, you'd be far better off using multiprocessing than threading... You have an \"embarrassingly parallel\" problem, and no disk IO constraints (you're writing to memory) Of course, passing large stuff back and forth between the processes will get expensive, but returning a string representing a ....
[ 3, 2 ]
[]
[]
[ "matplotlib", "multithreading", "optimization", "python" ]
stackoverflow_0004119473_matplotlib_multithreading_optimization_python.txt
Q: Global Name Error when deploying with Fabric The other person on my dev team has been deploying our Django app to the server via Fabric. Since I need to be able to deploy as well I setup Fabric on my system, but when I try to deploy I get a Global Name error: File ".../fabfile.py", line 4, in staging config.set...
Global Name Error when deploying with Fabric
The other person on my dev team has been deploying our Django app to the server via Fabric. Since I need to be able to deploy as well I setup Fabric on my system, but when I try to deploy I get a Global Name error: File ".../fabfile.py", line 4, in staging config.settings = 'staging' NameError: global name 'config' ...
[ "ohhh i know this error , this error is happening because you have installed in your machine fabric version higher than 0.9 and the fabric file that you want to use has been developed using and old version of fabric < 0.9.\nFor more detail the config obj has been replaced with env in fabric 0.9 so if you run yor fa...
[ 7 ]
[]
[]
[ "django", "fabric", "python" ]
stackoverflow_0004119700_django_fabric_python.txt
Q: app engine python setup << Big update below implies it's simply a logging issue >> I'm trying to get app engine setup with python and having some problem that I suspect is some simple step I've missed. My app.yaml says this: application: something #name here is the one I used to register i.e. something.appspot.c...
app engine python setup
<< Big update below implies it's simply a logging issue >> I'm trying to get app engine setup with python and having some problem that I suspect is some simple step I've missed. My app.yaml says this: application: something #name here is the one I used to register i.e. something.appspot.com version: 1 runtime: python...
[ "You don't have RequestHandler subclass for the \"/Sample\" path, like you do for the \"/\" path (i.e., MainPage).\nTo get logs, either start your SDK app server with dev_appserver.py and look at the logs it spits out, or click the Logs button in the Google App Engine Launcher GUI.\n", "I discovered that indeed i...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "installation", "python" ]
stackoverflow_0004119050_google_app_engine_installation_python.txt
Q: How to translate this to SQLObject: SELECT DISTINCT columnname WHERE I've been going through the sqlobject and sqlbuilder documentation and forums and I cannot seem to grasp the information there. I have a specific SQL query that I need: select distinct author from blogtable where keyword = "dust"; Multiple auth...
How to translate this to SQLObject: SELECT DISTINCT columnname WHERE
I've been going through the sqlobject and sqlbuilder documentation and forums and I cannot seem to grasp the information there. I have a specific SQL query that I need: select distinct author from blogtable where keyword = "dust"; Multiple authors can post about multiple subjects. The query works on the MySQL databas...
[ "I don't have much experience with SQLObject, but from the docs I deduce that it should be something like this:\nclass Blog(SQLObject):\n class sqlmeta:\n table = 'blogtable'\n\n author = StringCol()\n keyword = StringCol()\n\nBlog.select(Blog.q.keyword=='dust', distinct=True)\n\nVersion 2\nselect =...
[ 1 ]
[]
[]
[ "python", "sql", "sqlobject" ]
stackoverflow_0004120165_python_sql_sqlobject.txt
Q: Problems with Toplevel Widget and Portscanner def PortScanWin(): win2 = Toplevel() win2.title("PortScan") win2.wm_maxsize(width='190',height='370') win2.wm_minsize(width='190',height='370') def go(): global app result.delete(1.0,END) app=scan() app.start() def stop(): app.flag='stop' def c...
Problems with Toplevel Widget and Portscanner
def PortScanWin(): win2 = Toplevel() win2.title("PortScan") win2.wm_maxsize(width='190',height='370') win2.wm_minsize(width='190',height='370') def go(): global app result.delete(1.0,END) app=scan() app.start() def stop(): app.flag='stop' def clear(): host_e.delete(0,END) start_port_e.d...
[ "This isn't really an answer to your question, but you may like to check out Scapy. Scapy lets you build your own packets and read raw data from a network interface. Both are obviously very helpful in writing a port scanner. So, depending on what you need, you may wish to replace your port-scanner with one written ...
[ 0, 0 ]
[]
[]
[ "multithreading", "python", "tkinter", "widget" ]
stackoverflow_0004116378_multithreading_python_tkinter_widget.txt
Q: Load a tag library for a template externally in Django? I have a template tag that includes a template: def WidgeLoaderNode(IncludeNode): def __init__(tpl, scopes=None): self.scopes = scopes self.tpl = tpl super(WidgeLoaderNode, self).__init__('""') def render(self, con...
Load a tag library for a template externally in Django?
I have a template tag that includes a template: def WidgeLoaderNode(IncludeNode): def __init__(tpl, scopes=None): self.scopes = scopes self.tpl = tpl super(WidgeLoaderNode, self).__init__('""') def render(self, context): self.template_name = self.tpl.reso...
[ "Maybe you could use something like this: http://djangosnippets.org/snippets/342/ - i.e. django.template.add_to_builtins\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004119904_django_django_templates_python.txt
Q: Python bisect.bisect() counterpart in R? I want to draw from discrete distribution. I have a matrix, pi, which consists of vectors of probabilities (with the same number of columns, and sum of each row is 1). In Python, I can do the following cumsumpi = cumsum(pi, axis = 1) [bisect.bisect(k, random.rand()) for k ...
Python bisect.bisect() counterpart in R?
I want to draw from discrete distribution. I have a matrix, pi, which consists of vectors of probabilities (with the same number of columns, and sum of each row is 1). In Python, I can do the following cumsumpi = cumsum(pi, axis = 1) [bisect.bisect(k, random.rand()) for k in cumsumpi] to get the vector of draws by th...
[ "here is an alternate approach that avoids using apply and instead vectorizes the operation. initial checks indicate that it is twice as fast, but one needs to explore more in detail.\ncumsumpi = t(apply(pi, 1, cumsum));\nu = runif(nrow(cumsumpi));\n\nmax.col((cumsumpi > u) * 1, \"first\")\n\nto speed it up further...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "r" ]
stackoverflow_0004111685_python_r.txt
Q: How to combine Cmd and Matplotlib in python I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this? Can I use threading? I tried the following: from cmd import Cmd import matplotlib.pylab as plt from threading import Thread class MyCmd(Cmd): def...
How to combine Cmd and Matplotlib in python
I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this? Can I use threading? I tried the following: from cmd import Cmd import matplotlib.pylab as plt from threading import Thread class MyCmd(Cmd): def __init__(self): Cmd.__init__(self) ...
[ "I found something that works, but is rather ugly\nfrom cmd import Cmd\nimport matplotlib.pylab as plt\nfrom threading import Thread\nimport time\n\nclass MyCmd(Cmd):\n\n def __init__(self):\n Cmd.__init__(self)\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(1,1,1)\n\n def do_...
[ 3, 0 ]
[]
[]
[ "cmd", "interactive", "matplotlib", "plot", "python" ]
stackoverflow_0003472088_cmd_interactive_matplotlib_plot_python.txt
Q: Python Cookies and PHP virtual() I narrowed down the problem: os.environ.get('HTTP_COOKIE') This always seems to be None when calling the Python file with that line using PHP's virtual(). Does anyone know why this is? I'm using Python 2.7 because of how much I need the Python Imaging Library. EDIT: Never mind, it...
Python Cookies and PHP virtual()
I narrowed down the problem: os.environ.get('HTTP_COOKIE') This always seems to be None when calling the Python file with that line using PHP's virtual(). Does anyone know why this is? I'm using Python 2.7 because of how much I need the Python Imaging Library. EDIT: Never mind, it's been fixed. It was because I'm an i...
[ "Try to set cookies by your own with apache_setenv function.\nBut if the only thing that you need from python is PIL, then you probably don't need python at all. PHP have very powerful tools like MagickWand, a frontend to image magick.\n" ]
[ 0 ]
[]
[]
[ "cgi", "php", "python" ]
stackoverflow_0004120258_cgi_php_python.txt
Q: Keyword search using python and sqlite I have a plugin to a game server that writes down changes made to a map.The database contains entries formatted like this - id INTEGER PRIMARY KEY,matbefore INTEGER, matafter INTEGER, name VARCHAR(50), date DATE. I am trying to create a function that, when given a column name...
Keyword search using python and sqlite
I have a plugin to a game server that writes down changes made to a map.The database contains entries formatted like this - id INTEGER PRIMARY KEY,matbefore INTEGER, matafter INTEGER, name VARCHAR(50), date DATE. I am trying to create a function that, when given a column name, an integer, string, or tuple of an integer...
[ "If entry is a list (like in yesterday's question) , it's not going to work.\n>>> returncolumn = \"*\"\n>>> column = \"name\"\n>>> entry = [\"Able\", \"Baker\", \"Charlie\"]\n>>> qmarks = (\"? OR \" * len(entry))[:-4]\n>>> statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,\ncolumn,qmarks)\...
[ 1, 0 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0004119972_database_python_sqlite.txt
Q: python module layout I'm just starting to get to the point in my python projects that I need to start using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the __init__.py of the package? Some projects I see just have blank inits and a...
python module layout
I'm just starting to get to the point in my python projects that I need to start using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the __init__.py of the package? Some projects I see just have blank inits and all of their code are in mo...
[ "__init__.py can be empty, but what it really does is make sure Python treats your directories correctly, provide any initialization you might need for when your package is imported (configuring the environment or something along those lines), or defining __all__ so that Python knows what to do when someone uses fr...
[ 8, 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0004120759_python_python_module.txt
Q: Python read() seems to return less data than it reads Can anyone tell me why the length of data is much less than the position of the end of the file? I would have expected these to be equal. >>> target = open('target.jpg') >>> print target.tell() 0 >>> data = target.read() >>> print target.tell() 40962 >>> print ...
Python read() seems to return less data than it reads
Can anyone tell me why the length of data is much less than the position of the end of the file? I would have expected these to be equal. >>> target = open('target.jpg') >>> print target.tell() 0 >>> data = target.read() >>> print target.tell() 40962 >>> print len(data) 52
[ "Open the file in binary mode:\ntarget = open('target.jpg','rb')\n\nI would not trust tell() on a file not opened as binary.\n\nLater: actually, on reviewing the comments, I should have said I would not trust a read on a binary file opened as text.\n" ]
[ 6 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004121003_file_io_python.txt
Q: Scraping site that requires Javascript enabled with Mechanize + BeautifulSoup (Python) So.. i got this site I am tryign to scrape, but as I understand lack of support of mechanize for .js, and a stuborn site that requires javascript enabled browser is not a good mix... I am looking for ideas, on how to do this... ...
Scraping site that requires Javascript enabled with Mechanize + BeautifulSoup (Python)
So.. i got this site I am tryign to scrape, but as I understand lack of support of mechanize for .js, and a stuborn site that requires javascript enabled browser is not a good mix... I am looking for ideas, on how to do this... URL : https://members.iracing.com/membersite/login.jsp
[ "Depending on what you need to do, you could use webkit to parse the page, which will allow you to get the final html after the javascript has been executed. You could then use any decent html parser, beautifulsoup for example, to do the rest.\n", "With JavaScript I use Chickenfoot for simple websites and Webkit ...
[ 0, 0 ]
[]
[]
[ "javascript", "mechanize", "python", "screen_scraping" ]
stackoverflow_0004114219_javascript_mechanize_python_screen_scraping.txt
Q: Date sensitive regression testing using python Hey, I am helping to set up a regression testing suite for our python web application. Many of our tests are scheduling style tests where the current date is important. For example: create a recurring event that runs every week for a month starting on Feb 1. In order ...
Date sensitive regression testing using python
Hey, I am helping to set up a regression testing suite for our python web application. Many of our tests are scheduling style tests where the current date is important. For example: create a recurring event that runs every week for a month starting on Feb 1. In order to test this, what I really want to do is override t...
[ "You could do something like this:\nfrom datetime import datetime\norig_datetime_now = datetime.now\n\ndatetime.now = lambda: datetime(2010, 2, 1)\n\n# tests here\n\ndatetime.now = orig_datetime_now\n\nThough, it's probably a better idea (as not to screw with third party libraries, etc.) to put a helper method on y...
[ 1, 0 ]
[]
[]
[ "automated_tests", "date", "python", "regression_testing" ]
stackoverflow_0004047049_automated_tests_date_python_regression_testing.txt
Q: Python: what does self.control in a subclass of wx.Frame mean? I am following the Getting started with wxPython tutorial, to this part. What is control in the following line? I have searched in the Frame class reference and googled for a while but still no clue. self.control = wx.TextCtrl(self, style=wx.TE_MULTILI...
Python: what does self.control in a subclass of wx.Frame mean?
I am following the Getting started with wxPython tutorial, to this part. What is control in the following line? I have searched in the Frame class reference and googled for a while but still no clue. self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) Just in case next time I need information like this, where shou...
[ "Never mind, I found it from The Python Language Reference\n\nTo create instance variables, they can be set in a method with self.name = value\n\nSo, control is just an instance variable, no more no less.\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004121198_python_wxpython.txt
Q: How to set python IDLE to use pythonpath variable in Ubuntu 10.04 I have set a pythonpath variable in my ~/.bashrc and it works fine when using python interpreter from the command line and bpython, but IDLE is not recognizing it. How can I configure it to load the pythonpath variable? Thanks in advance A: You ...
How to set python IDLE to use pythonpath variable in Ubuntu 10.04
I have set a pythonpath variable in my ~/.bashrc and it works fine when using python interpreter from the command line and bpython, but IDLE is not recognizing it. How can I configure it to load the pythonpath variable? Thanks in advance
[ "\nYou can upgrade Ubuntu, because it works fine on my 10.10 machine with the idle-python2.7 package and PYTHONPATH set in my ~/.profile (which shouldn't matter because bash normally loads both)\nOr you can change sys.path in /usr/bin/idle* as per Setting PYTHONPATH for idle?\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_idle", "pythonpath" ]
stackoverflow_0004096223_python_python_idle_pythonpath.txt
Q: Accessing all objects created from ClientFactory in Twisted? I'm working on a basic Twisted application to help me learn how reactors work with multiple services. The basic outline of what I'd like my script to do is as follows: My script will be both a Web Server and an IRC Client. Every time a request is made...
Accessing all objects created from ClientFactory in Twisted?
I'm working on a basic Twisted application to help me learn how reactors work with multiple services. The basic outline of what I'd like my script to do is as follows: My script will be both a Web Server and an IRC Client. Every time a request is made to the web server, the script should say a message on IRC. I've ...
[ "One of the Twisted FAQ entries entries discusses a problem like this one. Just remember that a Site is a factory and it should be easy to apply a similar solution to your case.\n" ]
[ 1 ]
[]
[]
[ "events", "python", "reactor", "twisted" ]
stackoverflow_0004120996_events_python_reactor_twisted.txt
Q: Django Sphinx Text Search I am trying out Sphinx search in my Django project. All setup done & it works but need some clarification from someone who has actually used this setup. In my Sphinx search while indexing, I have used 'name' as the field in my MySQL to be searchable & all other fields in sql_query to be a...
Django Sphinx Text Search
I am trying out Sphinx search in my Django project. All setup done & it works but need some clarification from someone who has actually used this setup. In my Sphinx search while indexing, I have used 'name' as the field in my MySQL to be searchable & all other fields in sql_query to be as attributes (according to Sphi...
[ "Here's a shot in the dark - \nTry to get the name of your index in sphinx.conf same as the table_name you are trying to index. This is a quirk which is missed by lot of people.\n" ]
[ 1 ]
[]
[]
[ "django", "django_sphinx", "full_text_search", "python", "search" ]
stackoverflow_0003897650_django_django_sphinx_full_text_search_python_search.txt
Q: Version of Canvas create_text() that supports word wrap? Is there a create_text() mode or technique that supports word wrap? I'm stuck using create_text() vs. a Label or Text widget because I'm placing text on top of an image on my Canvas. Also, is there a Tkinter API that truncates text that doesn't fit a certain...
Version of Canvas create_text() that supports word wrap?
Is there a create_text() mode or technique that supports word wrap? I'm stuck using create_text() vs. a Label or Text widget because I'm placing text on top of an image on my Canvas. Also, is there a Tkinter API that truncates text that doesn't fit a certain width with an ellipsis like suffix, eg. Where very, very, ver...
[ "There is indeed a word wrap feature in create_text(). You'd call it like so:\ncanvas.create_text(x, y, width=80)\n\nYou can set the width parameter to whatever max length you want, or 0 if you want no word wrapping. See this article for all the options, arguments etc. for create_text().\nI'm not sure about truncat...
[ 9 ]
[]
[]
[ "python", "tkinter_canvas", "user_interface", "word_wrap" ]
stackoverflow_0004121362_python_tkinter_canvas_user_interface_word_wrap.txt
Q: pyGTK - gtk.Entry in gtk.Dialog Yields no Text In pyGTK (2.22 - version is very important), I'm encountering the bug detailed below. I think it's a pyGTK issue, but I could be wrong and don't want to report a non-bug. Basically, I am extracting text from a gtk.Entry() using .get_text(), and this returns an empty s...
pyGTK - gtk.Entry in gtk.Dialog Yields no Text
In pyGTK (2.22 - version is very important), I'm encountering the bug detailed below. I think it's a pyGTK issue, but I could be wrong and don't want to report a non-bug. Basically, I am extracting text from a gtk.Entry() using .get_text(), and this returns an empty string even with text in the widget. Here is some rel...
[ "destroy() will among other things cause the widget and its children to be unrealized, which means the entry loses its text. Always read the state of a dialog (or any other widget) before destroying it.\nThere are some other minor issues with your code:\n\nFor clarity, you should replace the maps with simple loops:...
[ 3 ]
[]
[]
[ "gtkentry", "pygtk", "python" ]
stackoverflow_0004121004_gtkentry_pygtk_python.txt
Q: How to run a .py (Python) file in ASP.NET? I have a GetList.py file which consumes Web Service and saves the output in XML on the server. How do I invoke GetList.py so it saves the output in XML on the server before displaying the XML output in .ASPX page? A: You can create one batch file which contains call to ...
How to run a .py (Python) file in ASP.NET?
I have a GetList.py file which consumes Web Service and saves the output in XML on the server. How do I invoke GetList.py so it saves the output in XML on the server before displaying the XML output in .ASPX page?
[ "You can create one batch file which contains call to python file and call that batch file from you .net application.\nTo call batch file, you can use Process class.\nFor example, suppose you have test.py file containing following code :\nprint \"hello world\"\n\nthen create one batch file (file having .bat extensi...
[ 9, 6 ]
[]
[]
[ "asp.net", "python" ]
stackoverflow_0004121993_asp.net_python.txt
Q: Python regex help a = Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st') What I want is escape the ' to html entities, which is &#39; remember, the string after path can be anything, I need a generic way to do this. The output of this string is Account(unit = 2, path=&#39;/real/os/win/today/ax...
Python regex help
a = Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st') What I want is escape the ' to html entities, which is &#39; remember, the string after path can be anything, I need a generic way to do this. The output of this string is Account(unit = 2, path=&#39;/real/os/win/today/axl.xls&#39;, realname = ...
[ "re.sub(r\"path=\\'([^\\']*)\\'\", \"path=&#39;\\1&#39;\", str)\n\n", "If you want to convert '/real/os/win/today/axl.xls' to &#39;/real/os/win/today/axl.xls&#39; you can use \"'/real/os/win/today/axl.xls'\".replace(\"'\", '&#39;') instead of using regex.\n", "What you have are non-HTML entities. If I remember ...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004121240_python_regex.txt
Q: What type of collection of mutable objects will allow me to quickly remove items in python? Suppose I have profiled my program, and the vast majority of runtime is spent in method 'remove' of 'list' objects. The program manipulates a collection of collections, and the collections do not need to be ordered. What ...
What type of collection of mutable objects will allow me to quickly remove items in python?
Suppose I have profiled my program, and the vast majority of runtime is spent in method 'remove' of 'list' objects. The program manipulates a collection of collections, and the collections do not need to be ordered. What would be the most straightforward way to implement these collections in python (preferably using ...
[ "If you can live with equality defined as identity, you can create a hashable list subtype and use these as set members for fast access/removal:\nclass hlist(list):\n\"Hashable list\"\n def __hash__(self):\n return id(self)\n def __eq__(self, other):\n return self is other\n def __ne__{self, ...
[ 4, 2, 2, 1, 0 ]
[ "Why not have something like a master list of sets and then another set that contains the indices to the list for the set you want to keep track of? Sure it might be a little extra work, but you should be able to abstract it out into a class.\n" ]
[ -1 ]
[ "linked_list", "optimization", "python", "set" ]
stackoverflow_0004119698_linked_list_optimization_python_set.txt
Q: How to print textfield's value in Django and Python? I'm trying to create a very simple web page with 2 textfields, 1 button and 3 labels to make it look like so: First Name: [..........] <-- label + textfield Last Name: [...........] <-- label + textfield (Submit) <-- button {Your full name is %FirstName% ...
How to print textfield's value in Django and Python?
I'm trying to create a very simple web page with 2 textfields, 1 button and 3 labels to make it look like so: First Name: [..........] <-- label + textfield Last Name: [...........] <-- label + textfield (Submit) <-- button {Your full name is %FirstName% + %LastName% } <-- label As you can see it's an extremely...
[ "zomboid's comment is correct. It looks like you need to learn more about Django. You might want to take a look at this chapter from The Django Book. That text is a bit outdated, but the fundamentals are the same.\nSome general guidance: you need to point a URL (e.g., /namegrabber) to a view function. Inside that v...
[ 2, 1 ]
[]
[]
[ "django", "python", "textbox" ]
stackoverflow_0004121503_django_python_textbox.txt
Q: Not need CSRF feature in django 1.2.3 I upgrading from django 1.1.1 to django 1.2.3, I know that CSRF feature have changed. But I don't need this feature for now , How can I make my code run properly.? A: You can remove the corresponding middleware from the MIDDLEWARE_CLASSES constant in your settings file. MIDD...
Not need CSRF feature in django 1.2.3
I upgrading from django 1.1.1 to django 1.2.3, I know that CSRF feature have changed. But I don't need this feature for now , How can I make my code run properly.?
[ "You can remove the corresponding middleware from the MIDDLEWARE_CLASSES constant in your settings file.\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n #'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004121486_django_python.txt