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: Reading multiple Python pickled data at once, buffering and newlines? to give you context: I have a large file f, several Gigs in size. It contains consecutive pickles of different object that were generated by running for obj in objs: cPickle.dump(obj, f) I want to take advantage of buffering when reading this ...
Reading multiple Python pickled data at once, buffering and newlines?
to give you context: I have a large file f, several Gigs in size. It contains consecutive pickles of different object that were generated by running for obj in objs: cPickle.dump(obj, f) I want to take advantage of buffering when reading this file. What I want, is to read several picked objects into a buffer at a tim...
[ "You don't need to do anything, i think.\n>>> import pickle\n>>> import StringIO\n>>> s = StringIO.StringIO(pickle.dumps('apples') + pickle.dumps('bananas'))\n>>> pickle.load(s)\n'apples'\n>>> pickle.load(s)\n'bananas'\n>>> pickle.load(s)\n\nTraceback (most recent call last):\n File \"<pyshell#25>\", line 1, in <m...
[ 7, 5, 2, 2 ]
[]
[]
[ "buffering", "newline", "pickle", "python" ]
stackoverflow_0005507115_buffering_newline_pickle_python.txt
Q: can django support group by some columns at the same time sum on other columns just like the query below : select sum(T.a), sum(T.b) from Table T group by T.c , T.d is there any way in django support this kind of query? A: This is close: class Test(models.Model): ...
can django support group by some columns at the same time sum on other columns
just like the query below : select sum(T.a), sum(T.b) from Table T group by T.c , T.d is there any way in django support this kind of query?
[ "This is close:\nclass Test(models.Model): \n class Meta: \n app_label = 'ignore' ...
[ 5, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005507982_django_python.txt
Q: Hide Auth section in Django Admin In the Django Admin, is there any way to hide the "Auth" section? Assuming this is a clean installation of Django and barebones project with no apps, only admin. A: You can use admin.site.unregister from django.contrib.auth.models import User from django.contrib.sites.models i...
Hide Auth section in Django Admin
In the Django Admin, is there any way to hide the "Auth" section? Assuming this is a clean installation of Django and barebones project with no apps, only admin.
[ "You can use admin.site.unregister \nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.contrib.auth.models import Group\n\nadmin.site.unregister(User)\nadmin.site.unregister(Group)\nadmin.site.unregister(Site)\n\n" ]
[ 72 ]
[]
[]
[ "authentication", "django", "django_admin", "python" ]
stackoverflow_0005508901_authentication_django_django_admin_python.txt
Q: Harvesting the Power of Visual SVG with PHP/PYTHON/other programming language Me and my friend want to build something with SVG and PHP or PYTHON. Is there any integration/ workflows that connect programming languages together with powerfull visual interfaces, such as SVG? Are there other promising visual ways tha...
Harvesting the Power of Visual SVG with PHP/PYTHON/other programming language
Me and my friend want to build something with SVG and PHP or PYTHON. Is there any integration/ workflows that connect programming languages together with powerfull visual interfaces, such as SVG? Are there other promising visual ways than SVG?
[ "Try pySVG. SVG 'format' is essentially XML so you could use any xml library if you write all the tags yourself.\n", "I think there are a couple of ways you can manipulate SVG dynamically with the Python language.\nFirst, you could use the Apache Batik library, which provides a first-class implementation of SVG b...
[ 1, 1 ]
[]
[]
[ "php", "python", "svg" ]
stackoverflow_0005493716_php_python_svg.txt
Q: Difficulties with sending mail from GAE I'm trying to send an email from within Google App Engine. Whenever I try to send, I get a "Missing subject error". When I run the code on the development server, it seems to work fine - the console output looks right and I'm taken to the page that I was expecting. But when...
Difficulties with sending mail from GAE
I'm trying to send an email from within Google App Engine. Whenever I try to send, I get a "Missing subject error". When I run the code on the development server, it seems to work fine - the console output looks right and I'm taken to the page that I was expecting. But when I upload it and run it, I get: Traceback (mo...
[ "Try this:\ndef email_member(request):\n to_addr = request.POST.get('email_to')\n\n if not mail.is_email_valid(to_addr):\n # Return an error message...\n pass\n else:\n # note we can also send html email, e.g. html='<html><head></head><body>Hello world</body><html>'\n mail.send_mail(\n sender='a...
[ 1, 0, 0 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0005508582_email_google_app_engine_python.txt
Q: App Engine regex issues directing URL to script and handlers I am trying to break my app into separate scripts. Part of this effort meant breaking the api calls into it's own file. However the calls to the api (like http://example.com/api/game/new no longer work). My app.yaml contains this: - url: /api.* script:...
App Engine regex issues directing URL to script and handlers
I am trying to break my app into separate scripts. Part of this effort meant breaking the api calls into it's own file. However the calls to the api (like http://example.com/api/game/new no longer work). My app.yaml contains this: - url: /api.* script: api.py which seems to be redirecting properly because this confi...
[ "The URL patterns you use in the WSGI application have to be the full path - eg, /api/game/.... The App Engine infrastructure uses the regular expressions in app.yaml to route requests, but it does not modify the request path based on them.\n", "My guess is you are trying to pass some arguments to your handler.\n...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0003812566_google_app_engine_python_regex.txt
Q: How do I compare the value in a list to the first value of a nested list and return the nested list results? I have the following two lists. List 1 (a,b,h,g,e,t,w,x) List two ((a,yellow),(h,green),(t,red),(w,teal)) I want to return the following ((a,yellow),(b,null),(h,green),(e,null),(t,red),(w,teal),(x,null)) ...
How do I compare the value in a list to the first value of a nested list and return the nested list results?
I have the following two lists. List 1 (a,b,h,g,e,t,w,x) List two ((a,yellow),(h,green),(t,red),(w,teal)) I want to return the following ((a,yellow),(b,null),(h,green),(e,null),(t,red),(w,teal),(x,null)) for x in List_1: for y in list_2: if x == y print y else print x, "null" ...
[ "Give this a go:\na = ('a', 'b', 'h', 'g', 'e', 't', 'w', 'x')\nb = (('a', 'yellow'), ('h', 'green'), ('t', 'red'), ('w', 'teal'))\nB = dict(b)\nprint [(x, B.get(x, 'null')) for x in a]\n\n", "Your logic is correct. The only thing you need is to form a list, not to print results outright.\nIf you insist on nested...
[ 7, 0, 0, 0 ]
[]
[]
[ "compare", "nested_lists", "python" ]
stackoverflow_0005499286_compare_nested_lists_python.txt
Q: NodeBox error for a verb in python I downloaded the package http://nodebox.net/code/index.php/Linguistics#verb_conjugation I'm getting an error even when I tried to get a tense of a verb . import en print en.is_verb('use') #prints TRUE print en.verb.tense('use') KeyError Tracebac...
NodeBox error for a verb in python
I downloaded the package http://nodebox.net/code/index.php/Linguistics#verb_conjugation I'm getting an error even when I tried to get a tense of a verb . import en print en.is_verb('use') #prints TRUE print en.verb.tense('use') KeyError Traceback (most recent call last) /home/cse/ver...
[ "The reason you are getting this error is because there is a mistake in the ~/Library/Application Support/NodeBox/en/verb/verb.txt file they are using to create the dictionary.\nuse is the infinitive form, however, \"used\" is entered as the infinitive.\nat line 5857:\nused,,,uses,,using,,,,,used,used,,,,,,,,,,,,\n...
[ 5 ]
[]
[]
[ "nodebox", "python" ]
stackoverflow_0005509384_nodebox_python.txt
Q: Python: '\\x41' to '\x41' How can I convert a string like '\\x41' to an escaped string like '\x41', using Python? A: >>> '\\x41'.decode('string_escape') 'A' Gory details here. A: I don't really understand your question, but I'll try to give you some solutions. If you gonna print pure '\x41', you could just ...
Python: '\\x41' to '\x41'
How can I convert a string like '\\x41' to an escaped string like '\x41', using Python?
[ ">>> '\\\\x41'.decode('string_escape')\n'A'\n\nGory details here.\n", "I don't really understand your question, but I'll try to give you some solutions.\n\nIf you gonna print pure '\\x41', you could just\n\n\nprint r'\\x41'\n\n\nAnd if what you want is to print the 'A' out, pls do: \n\n\nprint u'\\x41'\n\n" ]
[ 3, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005509803_python_string.txt
Q: I can select randomly from a list... but how do I use this as a variable for different commands? Python Lets say I have the following: foo = ('animal', 'vegetable', 'mineral') I want to be able to randomly select from the list THEN, depending on which one is selected, have a set of commands to follow. For instanc...
I can select randomly from a list... but how do I use this as a variable for different commands? Python
Lets say I have the following: foo = ('animal', 'vegetable', 'mineral') I want to be able to randomly select from the list THEN, depending on which one is selected, have a set of commands to follow. For instance, if 'animal' was randomly selected, I want the message print('rawr I\'m a tiger'), or if it was 'vegetable'...
[ "import random\nmessages = {\n 'animal': \"rawr I'm a tiger\",\n 'vegetable': \"Woof, I'm a carrot\",\n 'mineral': \"Rumble, I'm a rock\",\n}\nprint messages[random.choice(messages.keys())]\n\nIf you wanted to branch off to some other sections in an app, something like this might suite better:\nimport rand...
[ 5, 1, 1, 0 ]
[]
[]
[ "choice", "list", "printing", "python", "random" ]
stackoverflow_0005509902_choice_list_printing_python_random.txt
Q: python and mysql on mac os x Possible Duplicate: Python import MySQLdb error - Mac 10.6 I've tried everything I can find online. I've installed mysql using the dmg and I've tried installing the mysql-python (which I think worked). But I still get the error when I run in the python interpreter "import MySQLdb": >...
python and mysql on mac os x
Possible Duplicate: Python import MySQLdb error - Mac 10.6 I've tried everything I can find online. I've installed mysql using the dmg and I've tried installing the mysql-python (which I think worked). But I still get the error when I run in the python interpreter "import MySQLdb": >>> import MySQLdb Traceback (most...
[ "I've just installed this on my system and these are the steps I did to make it working:\n\nDownload Mysql-python: http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/ (I've used 1.2.2 version)\nExtract, go there and edit _mysql.c file by removing 37-19 lines (ifdefine)\nIn site.cfg set mysql_conf...
[ 10 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0005509104_macos_mysql_python.txt
Q: Protected method call in Python? I have a sequence of calls that I need to make, all of which could throw an exception and I want a good way of protecting the calls. I am trying to find a more professional way to do the following in python: def protected_call(method): result = None try: result= metho...
Protected method call in Python?
I have a sequence of calls that I need to make, all of which could throw an exception and I want a good way of protecting the calls. I am trying to find a more professional way to do the following in python: def protected_call(method): result = None try: result= method() except: pass return result...
[ "Decorator would be perfect for this:\ndef protected_call(method):\n def wrapper(*args, **kwargs):\n try:\n return method(*args, **kwargs)\n except:\n pass\n return wrapper\n\nSample usage:\n@protected_call\ndef foo():\n raise Exception()\n\n# nothing is being raised\nfo...
[ 3, 3, 1, 0 ]
[]
[]
[ "annotations", "exception_handling", "python" ]
stackoverflow_0005504312_annotations_exception_handling_python.txt
Q: C-extension in Python - return Py_BuildValue() memory leak problem I have a huge memory leak problem involving a C-extension I'm developing. In C, I have an array of doubles called A and an int variable called AnotherIntVariablethat I want to pass to Python. Well, in my C-extension module I do the following: int i...
C-extension in Python - return Py_BuildValue() memory leak problem
I have a huge memory leak problem involving a C-extension I'm developing. In C, I have an array of doubles called A and an int variable called AnotherIntVariablethat I want to pass to Python. Well, in my C-extension module I do the following: int i; PyObject *lst = PyList_New(len_A); PyObject *num; if(!lst) ...
[ "If you look at the documentation for Py_BuildValue (http://docs.python.org/3/c-api/arg.html#c.Py_BuildValue) you can see that under the O typecode, it says that the reference count of the passed in object is incremented by one (Note: an earlier section in that page describes the O typecode for PyArg_ParseTuple, wh...
[ 12, 3 ]
[]
[]
[ "c", "extension_methods", "memory", "memory_leaks", "python" ]
stackoverflow_0005508904_c_extension_methods_memory_memory_leaks_python.txt
Q: How Get Message from TCP/IP Python? how do I get the message that more than two messages in the buffer in the TCP / IP connection in python if I use the XML-RPC. I've tried using Cherrypy if the message is received by a normal state if more than one it will not get the message. A: About the best answer you will ...
How Get Message from TCP/IP Python?
how do I get the message that more than two messages in the buffer in the TCP / IP connection in python if I use the XML-RPC. I've tried using Cherrypy if the message is received by a normal state if more than one it will not get the message.
[ "About the best answer you will get is to switch framework to twisted. Twisted makes networking laughable because of its simplicity \nhttp://twistedmatrix.com/documents/current/web/howto/xmlrpc.html\nHere is a tutorial for xml rpc using twisted.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005510336_python.txt
Q: rpy2 problems, nls passing list() as argument from python to R I am trying to fit a nonlinear curve using rpy2 from numpy array, but are stuck as I do not know how to pass the 'start' argument on the R side. I use R 2.12.1 and python 2.6.6 Error in function (formula, data = parent.frame(), start, control = nls.co...
rpy2 problems, nls passing list() as argument from python to R
I am trying to fit a nonlinear curve using rpy2 from numpy array, but are stuck as I do not know how to pass the 'start' argument on the R side. I use R 2.12.1 and python 2.6.6 Error in function (formula, data = parent.frame(), start, control = nls.control(), : parameters without starting value in 'data': responsev,...
[ "The main error is this one:\nError in function (formula, data = parent.frame(), start, control = \nnls.control(), : parameters without starting value in \n 'data': responsev, predictorv\n\nWhere are declared the variable professions? and DataEmployment?\nseems they don't have a starting value, maybe you have t...
[ 0 ]
[]
[]
[ "arguments", "nls", "python", "r", "rpy2" ]
stackoverflow_0005510431_arguments_nls_python_r_rpy2.txt
Q: How to avoid hardcoded template name in a django app, integrated with django-cms? I have a custom Contact Form App, and I want to integrate it with django-cms. From what I understand I have to register the app with django-cms, and then in my views I have to return a RequestContext instance instead of a regular con...
How to avoid hardcoded template name in a django app, integrated with django-cms?
I have a custom Contact Form App, and I want to integrate it with django-cms. From what I understand I have to register the app with django-cms, and then in my views I have to return a RequestContext instance instead of a regular context instance. So in my views.py, I have return render_to_response('my_template.html', ...
[ "If your apphook is a single view mounted on /, you can just use {% extends request.current_page.get_template %}, however this does not work on subpages in your app.\nFor that you would need to reverse the root view of your app, use cms.utils.page_resolver.get_page_from_request with the use_path argument to get the...
[ 5 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0005507987_django_django_cms_python.txt
Q: Python regular expressions: search and replace weirdness I could really use some help with a Python regular expression problem. You'd expect the result of import re re.sub("s (.*?) s", "no", "this is a string") to be "this is no string", right? But in reality it's "thinotring". The sub function uses the entire ...
Python regular expressions: search and replace weirdness
I could really use some help with a Python regular expression problem. You'd expect the result of import re re.sub("s (.*?) s", "no", "this is a string") to be "this is no string", right? But in reality it's "thinotring". The sub function uses the entire pattern as the group to replace, instead of just the group I a...
[ "Your regex matches everything from the first s to the last s, so if you replace the match with \"no\", you get \"thinotring\". \nThe parentheses don't limit the match, they capture the text matched by whatever is inside them in a special variable called backreference. In your example, backreference number 1 would ...
[ 5, 1, 1, 0 ]
[ "Ok, look-around was possible, just needed a small rewrite. This works:\ndef absolutize(string, prefix):\n return re.sub(r\"(?<=href=['\\\"])((?!http).*?)(?=['\\\"])\", prefix+r'\\1', string)\n\nStill, stupid Python regex system... :(\n" ]
[ -1 ]
[ "python", "regex", "replace" ]
stackoverflow_0003769704_python_regex_replace.txt
Q: Django : Passing multiple args in HttpResponseRedirect reverse function I'm trying to pass multiple args in django's HttpResponseRedirect reverse function, but I keep getting this error Reverse for 'DemoVar.views.success' with arguments '()' and keyword arguments '{'company': u'Company ', 'sid': 47606734}' not fo...
Django : Passing multiple args in HttpResponseRedirect reverse function
I'm trying to pass multiple args in django's HttpResponseRedirect reverse function, but I keep getting this error Reverse for 'DemoVar.views.success' with arguments '()' and keyword arguments '{'company': u'Company ', 'sid': 47606734}' not found. #Calling function return HttpResponseRedirect(reverse('DemoVar.views.s...
[ "My regex inside urls.py for corresponding function url was wrong. Apparently Django looks at urls.py to figure out the type of inputs for the view function, which in my case was 'DemoVar.views.success'. Since the url's regex didn't allow for 'spaces', django gave an error. I changed to regex to accommodate an inpu...
[ 1, 0 ]
[]
[]
[ "django", "django_views", "python", "url" ]
stackoverflow_0005499668_django_django_views_python_url.txt
Q: Linking error when trying to compile The Powder Toy *Full log at Pastebin: * http://pastebin.com/QJyzzxNA Whenever I try to compile The Powder Toy, it gives me a linker error, saying the library is not compatible with x86_64. What should I do? Undefined symbols for architecture x86_64: "_Py_InitModule4", reference...
Linking error when trying to compile The Powder Toy
*Full log at Pastebin: * http://pastebin.com/QJyzzxNA Whenever I try to compile The Powder Toy, it gives me a linker error, saying the library is not compatible with x86_64. What should I do? Undefined symbols for architecture x86_64: "_Py_InitModule4", referenced from: _SDL_main in ccYupbfZ.o ld: symbol(s) not found f...
[ "You're compiling it as 64bit while on site, there is stated that The Powder Toy does not support x86_64. Compile it as 32bit.\n" ]
[ 0 ]
[]
[]
[ "c", "linker", "python", "x86_64" ]
stackoverflow_0005508828_c_linker_python_x86_64.txt
Q: Django : Syncdb incorrectly warns that many-to-many field is stale I have a django application where one application has many-to-many relationship with a UserProfile. But whenever I do a syncdb, it warns me that app_users is stale field The following content types are stale and need to be deleted: Apps | app_...
Django : Syncdb incorrectly warns that many-to-many field is stale
I have a django application where one application has many-to-many relationship with a UserProfile. But whenever I do a syncdb, it warns me that app_users is stale field The following content types are stale and need to be deleted: Apps | app_users #settings.py AUTH_PROFILE_MODULE = 'kprofile.UserProfile' #Apps/...
[ "Pay attention to the message. It's not claiming that your field is stale - it's talking about an entry in the Content Types model.\nIn the shell, do this:\nfrom django.contrib.contenttypes.models import ContentType\nct = ContentType.objects.get(app_label='Apps', model='app_users')\nct.delete()\n\n" ]
[ 20 ]
[]
[]
[ "django", "django_admin", "django_authentication", "django_models", "python" ]
stackoverflow_0005510843_django_django_admin_django_authentication_django_models_python.txt
Q: Python CouchDB can't save dict created from feedparser entry? (no attribute 'read') I have a script that I want to read entries in an RSS feed and store the individual entries in JSON format into a CouchDB database. The interesting part of my code looks something like this: Feed = namedtuple('Feed', ['name', 'url'...
Python CouchDB can't save dict created from feedparser entry? (no attribute 'read')
I have a script that I want to read entries in an RSS feed and store the individual entries in JSON format into a CouchDB database. The interesting part of my code looks something like this: Feed = namedtuple('Feed', ['name', 'url']) couch = couchdb.Server(COUCH_HOST) couch.resource.credentials = (COUCH_USER, COUCH_PA...
[ "I found a way by serializing the structure to JSON, then back to a Python dict that I pass to CouchDB -- which will then reserialize it back to JSON to save(yeah, weird and not favorable, but it works?)\nI had to do a custom serializer method for dumps because the repr of a time_struct can't be eval'd.\nSource: ht...
[ 4, 4, 1 ]
[]
[]
[ "couchdb", "feedparser", "python" ]
stackoverflow_0005505667_couchdb_feedparser_python.txt
Q: how to make a variable immutable in python My python script: N = 2 # 2*2 matrix a = N * [0] b = a print(b) # prints [0, 0] for i in range(N): a[i] = N * [0] for i in range(N): for j in range(N): a[i][j] = 0 print(a) # prints [[0, 0], [0, 0]] print(b) # prints [[0, 0], [0, 0]] Why does my...
how to make a variable immutable in python
My python script: N = 2 # 2*2 matrix a = N * [0] b = a print(b) # prints [0, 0] for i in range(N): a[i] = N * [0] for i in range(N): for j in range(N): a[i][j] = 0 print(a) # prints [[0, 0], [0, 0]] print(b) # prints [[0, 0], [0, 0]] Why does my second print(b) change? How to make it immutabl...
[ "Your understanding of \"objects\" in Python and variable assignments is flawed. \nIn a language like C, when you define a variable (say int a), a tiny area of memory is allocated and reserved for this variable and a is now something that refers to this area of memory. You can poke into this area, change it and fin...
[ 28, 18, 7, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005511128_list_python.txt
Q: Python - Understanding error: IndexError: list index out of range I'm fairly new to python. I have an error that I need to understand. The code: config.py: # Vou definir os feeds feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl"...
Python - Understanding error: IndexError: list index out of range
I'm fairly new to python. I have an error that I need to understand. The code: config.py: # Vou definir os feeds feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa2.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.ht...
[ "Using range for iteration is nearly always not the best way. In Python you can iterate directly over a list, dict, set etc.:\nfor item in d.entries:\n updates.append([{\"url\": feed_a_enviar[\"linktoourpage\"], \"msg\": item.title + \", \"}])\n\nObviously d.entries[i] triggers the error because that list contai...
[ 5, 2 ]
[]
[]
[ "list", "outofrangeexception", "python" ]
stackoverflow_0005511715_list_outofrangeexception_python.txt
Q: Best 3D library to model robotic motion A short while I asked for suggestions on choosing a Python-compatible 3D graphics library for robotic motion modelling (using inverse kinematics in Python). After doing a bit of research and redefining my objectives I hope I can ask once again for a bit of assistance. At the...
Best 3D library to model robotic motion
A short while I asked for suggestions on choosing a Python-compatible 3D graphics library for robotic motion modelling (using inverse kinematics in Python). After doing a bit of research and redefining my objectives I hope I can ask once again for a bit of assistance. At the time I thought Blender was the best option -...
[ "There is a similar project going on that implements a robotic toolbox for matlab and python, it has \"Rudimentary 3D graphics\", but you can always interface it with blender with a well knit script, it will be less work than reinventing the wheel\n", "If movements can be pre-computed, you can use Blender, hand-c...
[ 2, 0 ]
[]
[]
[ "modeling", "opengl", "python", "robotics" ]
stackoverflow_0005507790_modeling_opengl_python_robotics.txt
Q: struggling with binary arrays: python I am currently working on a released bot for a game in the hopes of learning more about programming. Unfortunately, a new command i was adding that seemed simple at first became overwhelmingly difficult when i got into the subject of binary arrays. Basically, i took an already...
struggling with binary arrays: python
I am currently working on a released bot for a game in the hopes of learning more about programming. Unfortunately, a new command i was adding that seemed simple at first became overwhelmingly difficult when i got into the subject of binary arrays. Basically, i took an already made command in which you place an item in...
[ "It seems the only place you use x2,y2,z2 is to set limits on x1,y, and z in these loops:\n while x1 <= x2:\n y = y1\n while y <= y2:\n z = z1\n while z <= z2:\n offset = self.bot.calculateOffset(x1,y,z)\n current_tile = int(self.bot.block_array[o...
[ 1, 0 ]
[]
[]
[ "arrays", "binary", "python" ]
stackoverflow_0005512132_arrays_binary_python.txt
Q: Proper way to automatically test performance in Python (for all developers)? Our Python application (a cool web service) has a full suite of tests (unit tests, integration tests etc.) that all developers must run before committing code. I want to add some performance tests to the suite to make sure no one adds cod...
Proper way to automatically test performance in Python (for all developers)?
Our Python application (a cool web service) has a full suite of tests (unit tests, integration tests etc.) that all developers must run before committing code. I want to add some performance tests to the suite to make sure no one adds code that makes us run too slow (for some rather arbitrary definition of slow). Obvio...
[ "Check out funkload - it's a way of running your unit tests as either functional or load tests to gauge how well your site is performing.\nAnother interesting project which can be used in conjunction with funkload is codespeed. This is an internal dashboard that measures the \"speed\" of your codebase for every com...
[ 5, 2 ]
[]
[]
[ "automated_tests", "performance", "python" ]
stackoverflow_0005510371_automated_tests_performance_python.txt
Q: Removing punctuation/numbers from text problem I had some code that worked fine removing punctuation/numbers using regular expressions in python, I had to change the code a bit so that a stop list worked, not particularly important. Anyway, now the punctuation isn't being removed and quite frankly i'm stumped as t...
Removing punctuation/numbers from text problem
I had some code that worked fine removing punctuation/numbers using regular expressions in python, I had to change the code a bit so that a stop list worked, not particularly important. Anyway, now the punctuation isn't being removed and quite frankly i'm stumped as to why. import re import nltk # Quran subset filenam...
[ "Change\nfor word in word_list:\n word = punctuation.sub(\"\", word)\n\nto\nword_list = [punctuation.sub(\"\", word) for word in word_list] \n\nAssignment to word in the for-loop above, simply changes the value referenced by this temporary variable. It does not alter word_list.\n", "You're not updating your...
[ 7, 3 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005512765_nltk_python.txt
Q: Tab/spaces indention issues in IDE's vs vim For a python project I am trying an IDE, coming from vim but I have troube how my code is shown resp. indentation. Many lines should be indented because they are inside if-then-else statements. In SPE and netbeans there are many lines where the indention-space (four) ar...
Tab/spaces indention issues in IDE's vs vim
For a python project I am trying an IDE, coming from vim but I have troube how my code is shown resp. indentation. Many lines should be indented because they are inside if-then-else statements. In SPE and netbeans there are many lines where the indention-space (four) are collapsed. But I checked the files with tabnan...
[ "\n...Netbeans want to switch from spaces\n to tabs, not the other way around...\n ergh – Rafe Kettler Mar 23 at 15:36\n\nI use netbeans meanwhile and like it. \nYes I converted all spaces to tabs and retab it to 4 in php and python\nregards\n" ]
[ 0 ]
[]
[]
[ "ide", "netbeans", "python", "tabstop" ]
stackoverflow_0005407664_ide_netbeans_python_tabstop.txt
Q: Python httplib2, AttributeError: 'set' object has no attribute 'items' I'm playing with the Python library httplib2. The following is my code. import urllib.parse import httplib2 httplib2.debuglevel = 1 http = httplib2.Http() url = "http://login.sina.com.cn/hd/signin.php" body = {"act": "1", "entry": "v...
Python httplib2, AttributeError: 'set' object has no attribute 'items'
I'm playing with the Python library httplib2. The following is my code. import urllib.parse import httplib2 httplib2.debuglevel = 1 http = httplib2.Http() url = "http://login.sina.com.cn/hd/signin.php" body = {"act": "1", "entry": "vblog", "password": "P@$sW0rd", "reference": "http://vupload....
[ "headers should be a dictionary, not a set:\nheaders = {\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n ...}\n\nNote the colon instead of the comma.\n" ]
[ 21 ]
[]
[]
[ "httplib2", "python" ]
stackoverflow_0005512993_httplib2_python.txt
Q: python mechanize find_link find the final matching link I've got a page with >=1 links with "Display charges" in the text. I can find the first such link with firstLink = br.find_link(text_regex=re.compile("Display charges"),nr=0) I'd love to be able to find the final link. I hoped this would work lastLink = br....
python mechanize find_link find the final matching link
I've got a page with >=1 links with "Display charges" in the text. I can find the first such link with firstLink = br.find_link(text_regex=re.compile("Display charges"),nr=0) I'd love to be able to find the final link. I hoped this would work lastLink = br.find_link(text_regex=re.compile("Display charges"),nr=-1) bu...
[ "You could use br.links() to generate all such links, then use list(...)[-1] to pick off the last one:\nlastLink = list(br.links(text_regex=re.compile(\"Display charges\")))[-1]\n\nFor example:\nIn [29]: import mechanize\n\nIn [30]: import re\n\nIn [31]: br=mechanize.Browser()\n\nIn [32]: br.open('http://www.exampl...
[ 7 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0005513059_mechanize_python.txt
Q: Code for counting the number of syllables in the words in a file I have the following piece of code so far to count the number of syllables in the words in the cmudict ( CMU pronunciation dictionary). It counts the number of syllables for all the words in the dictionary. Now I need to replace cmudict with my input...
Code for counting the number of syllables in the words in a file
I have the following piece of code so far to count the number of syllables in the words in the cmudict ( CMU pronunciation dictionary). It counts the number of syllables for all the words in the dictionary. Now I need to replace cmudict with my input file and find the number of syllables for each word in the file which...
[ "Not sure this will solve the whole problem, but:\nw_words = dict([(w, nsyl(w)) for w in d.keys() if w[0] == 'a'or'z'])\n\nshould probably be\nw_words = dict([(w, nsyl(w)) for w in d.keys() if w[0] == 'a' or w[0] == 'z'])\n\nsince\nif w[0] == 'a'or'z' means if (w[0] == 'a') or ('z'). The string 'z' is Truish, so t...
[ 2 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005513391_nltk_python.txt
Q: How can I handle several regexp cases neatly in python So I get some input in python that I need to parse using regexps. At the moment I'm using something like this: matchOK = re.compile(r'^OK\s+(\w+)\s+(\w+)$') matchFailed = re.compile(r'^FAILED\s(\w+)$') #.... a bunch more regexps for l in big_input: match = ...
How can I handle several regexp cases neatly in python
So I get some input in python that I need to parse using regexps. At the moment I'm using something like this: matchOK = re.compile(r'^OK\s+(\w+)\s+(\w+)$') matchFailed = re.compile(r'^FAILED\s(\w+)$') #.... a bunch more regexps for l in big_input: match = matchOK.search(l) if match: #do something with match ...
[ "class helper:\n def __call__(self, match):\n self.match= match\n return bool(match)\n\nh= helper()\nfor l in big_input: \n if h(matchOK.search(l)):\n # do something with h.match \n elif h(matchFailed.search(l)):\n # do something with h.match \n ... # a bunch more of...
[ 3, 0, 0 ]
[ "Even better, how about a slightly simpler version of eat's code using a nested function:\nimport re\n\nmatchOK = re.compile(\"ok\")\nmatchFailed = re.compile(\"failed\")\nbig_input = [\"ok to begin with\", \"failed later\", \"then gave up\"]\n\nfor l in big_input:\n match = None\n def matches(pattern):\n ...
[ -1 ]
[ "python" ]
stackoverflow_0005510879_python.txt
Q: respond to keypresses in python without generating a window I'm doing some robotics programming in python, and I'd like to enable the keyboard to control the robot's movement. My only experience with something like this is writing a game in Java using SWT, and I imagine the basic idea here would be to make some ke...
respond to keypresses in python without generating a window
I'm doing some robotics programming in python, and I'd like to enable the keyboard to control the robot's movement. My only experience with something like this is writing a game in Java using SWT, and I imagine the basic idea here would be to make some keyboard event handlers and run a main execution loop. From what I'...
[ "You could probably use pykeylogger http://sourceforge.net/apps/mediawiki/pykeylogger/index.php?title=Main_Page\nHowever using something like PyGame or wxpython is easiest, so are you absolutely sure you can't use those? For example, why can't you have a window initialized? Is your robot controlled by some sort of ...
[ 1, 0 ]
[]
[]
[ "arrow_keys", "event_handling", "keypress", "python", "wxpython" ]
stackoverflow_0005506586_arrow_keys_event_handling_keypress_python_wxpython.txt
Q: How to change time formats in python? How do i get the following list [datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)] as ['2011-04','2011-05'] It not only convert to string but remove dups A: Convert the dates to strings using datetime.date.s...
How to change time formats in python?
How do i get the following list [datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)] as ['2011-04','2011-05'] It not only convert to string but remove dups
[ "Convert the dates to strings using datetime.date.strftime.\ndates = [date.strftime('%Y-%m') for date in dates]\n\nYou can remove duplicates by converting the list to a set and then back to a list.\ndates = list(set(dates))\n\nThen combine both methods to do it all in one step.\ndates = list(set([date.strftime('%Y-...
[ 6, 1, 1 ]
[]
[]
[ "python", "string", "time" ]
stackoverflow_0005513922_python_string_time.txt
Q: The best way to schedule a single task at a specified time? Let's take the following example: We have users which asked to post the article with id:5 at 2011-04-19 20:20 So I want to create a task which will change the status of the article at 2011-04-19 20:20. I came up with the following ideas: Implement Celery...
The best way to schedule a single task at a specified time?
Let's take the following example: We have users which asked to post the article with id:5 at 2011-04-19 20:20 So I want to create a task which will change the status of the article at 2011-04-19 20:20. I came up with the following ideas: Implement Celery and use RabbitQM or Django-kombu: using countdown and eta: http:...
[ "My recommendation would be to keep it simple to start, using a management command kicked off by CRON every minute, and when that outgrows your need switch to the distributed job approach. If you separate your code correctly, this shouldn't be that large of a change.\nIf you are going to be doing 100k tasks from th...
[ 4, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005513262_django_python.txt
Q: Getting ID field while using for cycle with objects what is the best way to get for number each time it runs? Code: fields = [] objects = otherobjects.all() for object in objects fields.append(('id_is_#', object)) I want to put an ID to # place. ID would be generated ++ way. A: fields = [] objects = other...
Getting ID field while using for cycle with objects
what is the best way to get for number each time it runs? Code: fields = [] objects = otherobjects.all() for object in objects fields.append(('id_is_#', object)) I want to put an ID to # place. ID would be generated ++ way.
[ "fields = []\nobjects = otherobjects.all() \n\nfor id, obj in enumerate(objects)\n fields.append(('id_is_' + id, obj))\n\n", "List comprehension: \nobjects = otherobjects.all()\nfields = [('id_is_%d' % id, ob) for id, ob in enumerate(objects)]\n\nUsing 'object' as a variable name could cause problems...\n", ...
[ 2, 1, 0 ]
[]
[]
[ "algorithm", "cycle", "for_loop", "python" ]
stackoverflow_0005514025_algorithm_cycle_for_loop_python.txt
Q: Http connection freezes when request's content-length exceeds real content length I have a very basic python script that does HTTP connection. import socket def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.56.21" s.connect((host, 80)) msg = """GET /lol /HTTP1.1 Con...
Http connection freezes when request's content-length exceeds real content length
I have a very basic python script that does HTTP connection. import socket def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.56.21" s.connect((host, 80)) msg = """GET /lol /HTTP1.1 Content-Length: 10 %s""" % ("*" * 9) s.send(msg) print msg print s.recv(1...
[ "OK, it is Timeout directive in apache conf. \nhttp://httpd.apache.org/docs/2.2/mod/core.html#timeout\n" ]
[ 1 ]
[]
[]
[ "apache", "http", "python", "sockets", "tcp" ]
stackoverflow_0005513230_apache_http_python_sockets_tcp.txt
Q: Python documentation for @? Just a quick question, Could someone link me to the documentation for the use of @ in python? Due not being able to google @ and not knowing the use or name of it I'm not sure how to find it on my own :) Many thanks!! A: Symbols starting with "@" (e.g. @staticmethod) are called "decor...
Python documentation for @?
Just a quick question, Could someone link me to the documentation for the use of @ in python? Due not being able to google @ and not knowing the use or name of it I'm not sure how to find it on my own :) Many thanks!!
[ "Symbols starting with \"@\" (e.g. @staticmethod) are called \"decorators\" in Python jargon.\nYou can find the PEP describing them at this url.\nIn short, they are syntactic sugar to invoke a function over the object being decorated, e.g.:\n@staticmethod\ndef myfunc(...): ...\n\nis equivalent to:\ndef myfunc(...):...
[ 8, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005514330_python.txt
Q: Using cyclone or tornado in python, how do i make a simple handler that responds with json? Do i do it like this? import cyclone class MyHandler(cyclone.web.RequestHandler): def get(self, command): details = {'status':'success'} json = json_encode(details) self.write(json) Or is there...
Using cyclone or tornado in python, how do i make a simple handler that responds with json?
Do i do it like this? import cyclone class MyHandler(cyclone.web.RequestHandler): def get(self, command): details = {'status':'success'} json = json_encode(details) self.write(json) Or is there more to it than that?
[ "It's even less than that: You can simply use self.write(details) if it you write a dict, it will be automatically converted to JSON.\n", "I would recommend to use the built in json encoder function : \nself.write(tornado.escape.json_encode(details)\n\nIf the details is of type dict, tornado will json encode the ...
[ 7, 2 ]
[]
[]
[ "json", "python", "tornado" ]
stackoverflow_0005509373_json_python_tornado.txt
Q: dictionary reading from module I have following module root_file.py. This file contains number of blocks like. Name = { '1':'a' '2':'b' '3':'c' } In other file I am using f1= __import__('root_file') Now the requirement is that I have to read values a,b,c at runtime using variables like for reading a id=1 app=N...
dictionary reading from module
I have following module root_file.py. This file contains number of blocks like. Name = { '1':'a' '2':'b' '3':'c' } In other file I am using f1= __import__('root_file') Now the requirement is that I have to read values a,b,c at runtime using variables like for reading a id=1 app=Name print f1[app][id] but getting ...
[ "How about\nimport root_file as f1\n\nid = 1\napp = 'Name'\nprint getattr(f1, app)[id] # or f1.Name[id]\n\n", "Uh, well, if I understand what you are trying to do:\nIn root_file.py\nName = {\n '1':'a', #note the commas here!\n '2':'b', #and here\n '3':'c', #the last one is optional\n}\n\nThen, in the other file:\...
[ 2, 1 ]
[]
[]
[ "dictionary", "module", "python" ]
stackoverflow_0005514606_dictionary_module_python.txt
Q: Python Regex help I would like to use a regex to do the following in Python: I am given a list of strings such as: 'abc01 - [def02] - ghi03 - jkl04' Each string will have a different number of items. Some will have brackets around and some will not. Can someone help me with a regex match that will consist solely o...
Python Regex help
I would like to use a regex to do the following in Python: I am given a list of strings such as: 'abc01 - [def02] - ghi03 - jkl04' Each string will have a different number of items. Some will have brackets around and some will not. Can someone help me with a regex match that will consist solely of items not in brackets...
[ "Is regex really the best tool for the job?\n>>> S = 'abc01 - [def02] - ghi03 - jkl04'\n>>> [x for x in S.split(' - ') if not (x.startswith('[') or x.endswith(']'))]\n['abc01', 'ghi03', 'jkl04']\n\n", ">>> a='abc01 - [def02] - ghi03 - jkl04'\n>>> [ i for i in a.split(\" - \") if \"[\" not in i ]\n['abc01', 'ghi0...
[ 9, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005509181_python_regex.txt
Q: Learning Python: Store values in dict from stdout How can I do the following in Python: I have a command output that outputs this: Datexxxx Clientxxx Timexxx Datexxxx Client2xxx Timexxx Datexxxx Client3xxx Timexxx And I want to work this in a dict like: Client:(date,time), Client2:(date,time) ... A: What abou...
Learning Python: Store values in dict from stdout
How can I do the following in Python: I have a command output that outputs this: Datexxxx Clientxxx Timexxx Datexxxx Client2xxx Timexxx Datexxxx Client3xxx Timexxx And I want to work this in a dict like: Client:(date,time), Client2:(date,time) ...
[ "What about using a dict with tuples?\nCreate a dictionary and add the entries:\ndict = {}\ndict['Client'] = ('date1','time1')\ndict['Client2'] = ('date2','time2')\n\nAccessing the entires:\ndict['Client']\n>>> ('date1','time1')\n\n", "After reading the data into a string subject, you could do this:\nimport re\nd...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005514814_python.txt
Q: Is there a shorthand for querying a dictionary in python? Here's the type of query I want to execute, written in pseudocode: select blob from blobs where blob['color'] == 'red' having maximum(blob['size']) Obviously, I could write that like this in python: redBlobs = []; for blob in blobs: if blob['color'] =...
Is there a shorthand for querying a dictionary in python?
Here's the type of query I want to execute, written in pseudocode: select blob from blobs where blob['color'] == 'red' having maximum(blob['size']) Obviously, I could write that like this in python: redBlobs = []; for blob in blobs: if blob['color'] == 'red': redBlobs.append('blob') largestBlob = None f...
[ "The folowing give the largest blob\nEDIT: catch exception when there is no red blob\nimport operator\ntry:\n largestBlob = max((blob for blob in blobs if blob['color'] == 'red'),key=operator.itemgetter('size'))\nexcept ValueError:\n largestBlob = None\n\n", "This will do the job:\nredBlobs = filter(lambda ...
[ 10, 1, 1, 0 ]
[]
[]
[ "python", "syntactic_sugar" ]
stackoverflow_0005514906_python_syntactic_sugar.txt
Q: Is it possible to import .pyo files Well, Is it possible to import "os" module with "os.pyo" or "os.pyc" instead of "os.py"? Thank you A: Yes. If you started Python without -O you'll need the .pyc file, and with -O you will need .pyo.
Is it possible to import .pyo files
Well, Is it possible to import "os" module with "os.pyo" or "os.pyc" instead of "os.py"? Thank you
[ "Yes. If you started Python without -O you'll need the .pyc file, and with -O you will need .pyo.\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005515051_python.txt
Q: Attempting to create something using dictionaries but am lost I'm not really too sure how to best approach the following in python... I know what I want, and have an idea of how I want it, but I don't know if my idea is the best approach to what I'm looking for. "Name":"path",contains[] "Folder":"C:/blah/blah/fold...
Attempting to create something using dictionaries but am lost
I'm not really too sure how to best approach the following in python... I know what I want, and have an idea of how I want it, but I don't know if my idea is the best approach to what I'm looking for. "Name":"path",contains[] "Folder":"C:/blah/blah/folder",contains["file1","file2","file3"] like things={} things["Fol...
[ "Something like this?\n>>> d = {}\n>>> d[\"Folder\"] = [\"C:/blah/blah/Folder\", [\"file1\",\"file2\",\"file3\"]]\n>>> d[\"more\"] = [\"/home/mydir\", [\"file1\",\"file2\",\"file3\"]]\n>>> d[\"Folder\"][0]\n'C:/blah/blah/Folder'\n>>> d[\"Folder\"][1]\n['file1', 'file2', 'file3']\n>>> d[\"Folder\"][1].append(\"file4...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005514877_dictionary_python.txt
Q: How to iterate over columns of a matrix? In python if a define: a = arange(9).reshape(3,3) as a 3x3 matrix and iterate: for i in a: It'll iterate over the matrix's rows. Is there any way to iterate over columns? A: How about for i in a.transpose(): or, shorter: for i in a.T: This may look expensive but is in...
How to iterate over columns of a matrix?
In python if a define: a = arange(9).reshape(3,3) as a 3x3 matrix and iterate: for i in a: It'll iterate over the matrix's rows. Is there any way to iterate over columns?
[ "How about\nfor i in a.transpose():\n\nor, shorter:\nfor i in a.T:\n\nThis may look expensive but is in fact very cheap (it returns a view onto the same data, but with the shape and stride attributes permuted).\n", "Assuming that a is a well formed matrix, you could try something like:\nb = zip(*a)\nfor index in ...
[ 42, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005515181_numpy_python.txt
Q: How to match non-printable characters in a python regular expression? How do you match non-printable characters in a python regular expression? In my case I have a string that has a combination of printable and non-printable characters. Example String: "Det 3 @ NYY 5 ?7" where the ? is either 0x7f or 0x80. In the...
How to match non-printable characters in a python regular expression?
How do you match non-printable characters in a python regular expression? In my case I have a string that has a combination of printable and non-printable characters. Example String: "Det 3 @ NYY 5 ?7" where the ? is either 0x7f or 0x80. In the above example I need to match 0x7f or 0x80. How do I specify this in a pyt...
[ "Use a character range.\n'[\\x7f\\x80]'\n\n", "Maybe you can try\n[^[:print:]]\n\nfor non-printable. \n" ]
[ 13, 1 ]
[]
[]
[ "non_printing_characters", "python", "regex" ]
stackoverflow_0005515226_non_printing_characters_python_regex.txt
Q: Caching of (fake) static content which is actually dynamic on GAE for Python In my GAE app I have the following handler in app.yaml: - url: /lang/strings.js script: js_lang.py So a call to /lang/strings.js will actually map to the js_lang.py request handler which populates the response as application/javascript...
Caching of (fake) static content which is actually dynamic on GAE for Python
In my GAE app I have the following handler in app.yaml: - url: /lang/strings.js script: js_lang.py So a call to /lang/strings.js will actually map to the js_lang.py request handler which populates the response as application/javascript. I want this response to be cached in the browser so that the request handler onl...
[ "Have a look at Static serving blog post by Nick.\nThere's everything you need to know about Conditional request and how to properly get and set the correct HTTP headers:\n\nHttp Request header handling\n(If-Modified-Since,If-None-Match) \nHttp Response headers handling\n(Last-Modified, ETag)\n\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005512634_google_app_engine_python.txt
Q: Python hooking memory to know number of bytes used I want to hook the memory to know the number of bytes used to create the World objects in my game so as to give me some information to update the loading progressbar http://www.pasteall.org/20441/python A: A simple way to implement a progress bar is by increment...
Python hooking memory to know number of bytes used
I want to hook the memory to know the number of bytes used to create the World objects in my game so as to give me some information to update the loading progressbar http://www.pasteall.org/20441/python
[ "A simple way to implement a progress bar is by incrementing the progress every time you load another object. Depending on how many objects you have to load that may be granular enough, and is very easy to implement.\n" ]
[ 0 ]
[]
[]
[ "hook", "loading", "memory", "progress_bar", "python" ]
stackoverflow_0005515387_hook_loading_memory_progress_bar_python.txt
Q: Pythonic way of intelligently loading data using field mapping table? I have a complicated table (few hundred columns) and I get data in csv files every now and then. All I have to do is update the table with that of the data in the csv file. This is what I use right now : nothing fancy (not using Python power I ...
Pythonic way of intelligently loading data using field mapping table?
I have a complicated table (few hundred columns) and I get data in csv files every now and then. All I have to do is update the table with that of the data in the csv file. This is what I use right now : nothing fancy (not using Python power I guess?). If someone can translate this to something Pythonic, that will be ...
[ "I would start by expressing the code above as a plain english algorithm. Breaking a problem down into the fundamental bits of what you want to get done rather then how you want to do them often simplifies things considerably.\nHave a look into database abstraction layers if you want to simplify access. SQLAlchemy ...
[ 1 ]
[]
[]
[ "data_structures", "mysql", "python" ]
stackoverflow_0005515095_data_structures_mysql_python.txt
Q: How to cache a list of custom-defined models in Django? I have a list of models, [Book1, Book2, Book3], that I need to cache. I get this error, when I try to cache them: can't pickle _Element objects Here is the code that I am using: if cache.get(isbn): sellers = cache.get(isbn) else: sellers = get_all_ama...
How to cache a list of custom-defined models in Django?
I have a list of models, [Book1, Book2, Book3], that I need to cache. I get this error, when I try to cache them: can't pickle _Element objects Here is the code that I am using: if cache.get(isbn): sellers = cache.get(isbn) else: sellers = get_all_amazon_sellers(isbn) cache.set(isbn, sellers, 600) Thank yo...
[ "You might have to convert your data into a python list, as discussed here\n", "May be some value in your list is special type, and not common python object. I met the same trouble when I want to pickle texts which are parsed with lxml.Some useful links:lxml question and my record.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "pickle", "python" ]
stackoverflow_0004702040_django_pickle_python.txt
Q: Need help in HTML submit button and javascript(confirm-button) on django: Scenario: I'm trying to use image button in my HTML form with JavaScript: <form method="post" name="delete"> <input type="image" name="{{a.id}}" src="http://localhost:8000/site_media/web/img/delete_icon.gif" onClick="decision(this,'D...
Need help in HTML submit button and javascript(confirm-button) on django:
Scenario: I'm trying to use image button in my HTML form with JavaScript: <form method="post" name="delete"> <input type="image" name="{{a.id}}" src="http://localhost:8000/site_media/web/img/delete_icon.gif" onClick="decision(this,'Delete this Activity?','http://localhost:8000/delAct/listAct')"/> </form> this ...
[ "The problem you are having is that using an input of type image creates a submit button that looks like an image so when it is clicked the form is submitted to the same page you are on because the <form> tag doesn't specify an action attribute. To prevent the submit from trigering you need to return false from the...
[ 1 ]
[]
[]
[ "django", "html", "javascript", "python" ]
stackoverflow_0005516205_django_html_javascript_python.txt
Q: python -- grabbing email attachments to disk? I have a bunch of 500 emails, each with attachments. I'd like to write a python script that would scroll through all email messages, and saves these attachments to disk. How do I go about it? Also, suppose I could choose which email program will be used to retrieve the...
python -- grabbing email attachments to disk?
I have a bunch of 500 emails, each with attachments. I'd like to write a python script that would scroll through all email messages, and saves these attachments to disk. How do I go about it? Also, suppose I could choose which email program will be used to retrieve the messages from the POP3 server -- would it be best ...
[ "There is no need to use an e-mail client to get your e-mail, not when Python has a perfectly cromulent poplib module and also an email module for parsing out the attachments.\n", "with io.open('emails.txt', 'w') as file:\n for email in elist: file.write(email)\n\n" ]
[ 2, 0 ]
[]
[]
[ "email", "email_attachments", "linux", "python" ]
stackoverflow_0005516341_email_email_attachments_linux_python.txt
Q: timthumb for python? Is there a TimThumb - like script for Django/Python? It's a image crop&rezise&cache script. Simple but very effective, imho. A: This is a good django-app for that http://thumbnail.sorl.net/ from sorl.thumbnail import get_thumbnail im = get_thumbnail(my_file, '100x100', crop='center', qualit...
timthumb for python?
Is there a TimThumb - like script for Django/Python? It's a image crop&rezise&cache script. Simple but very effective, imho.
[ "This is a good django-app for that\nhttp://thumbnail.sorl.net/\nfrom sorl.thumbnail import get_thumbnail\n\nim = get_thumbnail(my_file, '100x100', crop='center', quality=99)\n\n", "You should take a closer look at easy_thumbnails.\nIt should do what you want.\nAnd you can find more django related image tools in ...
[ 5, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005515851_django_python.txt
Q: Python CGI without HTML clutter in source code? I am new to web development. After much consideration I picked Python over Ruby simply because code readability is important to me. I have looked at a few Python cgi code and I wondered if it is possible to polish that code in such a manner that I can focus on progr...
Python CGI without HTML clutter in source code?
I am new to web development. After much consideration I picked Python over Ruby simply because code readability is important to me. I have looked at a few Python cgi code and I wondered if it is possible to polish that code in such a manner that I can focus on program functionality without having to have all the HTML ...
[ "Pick a template engine. And it's still CGI, it just happens to be CGI that uses a template engine; CGI is the interface, not the programming methodology.\n", "\nis possible to polish that code in such a manner that I can focus on program functionality without having to have all the HTML formatting code embedded ...
[ 4, 1, 0 ]
[]
[]
[ "cgi", "html", "python" ]
stackoverflow_0005516766_cgi_html_python.txt
Q: Using python to build a queue How to I use Tuples to setup variables to pass into a threading queue ml =[('A', '2011-04', '2011-05'), ('b', '2011-07', '2011-04', '2011-05'), ('c', '2011-06', '2011-07', '2011-04', '2011-05')] Below is the queing setup: # build a queue with tuples queue = Queue.Queue() for row in m...
Using python to build a queue
How to I use Tuples to setup variables to pass into a threading queue ml =[('A', '2011-04', '2011-05'), ('b', '2011-07', '2011-04', '2011-05'), ('c', '2011-06', '2011-07', '2011-04', '2011-05')] Below is the queing setup: # build a queue with tuples queue = Queue.Queue() for row in ml: if not row or row[0] == "#":...
[ "Not sure I understand the problem.\nqSplit = row.split()\n\nisn't going to work because row is a tuple, not a string. But it seems all you're trying to do is to split the tuple into its components, only to stick them together into a new tuple right away. That doesn't make sense to me.\nYou're also not doing anythi...
[ 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005516642_multithreading_python.txt
Q: Event correlation and filtering - How to, where-to start? Got an asynchronous stream of events, where each event has information like - Agency (one of many Agencies possible to be served by my solution) Agent (one of many Agents in an Agency) Served-Entity (a person/organization served by 1 or more agencies) Date...
Event correlation and filtering - How to, where-to start?
Got an asynchronous stream of events, where each event has information like - Agency (one of many Agencies possible to be served by my solution) Agent (one of many Agents in an Agency) Served-Entity (a person/organization served by 1 or more agencies) Date+Time Class-Data (tags from a fixed but large set of tags) Wha...
[ "Mike,\ndid you consider something like Esper/Nesper to see if they might meet your requirements ? while I've looked at something similar myself -- especially on Erlang (check my post here), and you'd find some useful answers there. \nIC\n", "Your problem is a tactical problem as opposed to a procedural problem. ...
[ 2, 1 ]
[]
[]
[ "classification", "correlation", "erlang", "machine_learning", "python" ]
stackoverflow_0005503820_classification_correlation_erlang_machine_learning_python.txt
Q: Detect Decorator in Python In python, is it possible to detect if there is a decorator on another function? Specifically, I'm trying (in django) to write some middleware that will detect if the view being processed has been wrapped in the @login_required decorator. class SomeMiddleware(object): def process_vi...
Detect Decorator in Python
In python, is it possible to detect if there is a decorator on another function? Specifically, I'm trying (in django) to write some middleware that will detect if the view being processed has been wrapped in the @login_required decorator. class SomeMiddleware(object): def process_view(self, request, view_func, vie...
[ "Just some quick fooling around in the shell shows that the func_closure attribute on a function is empty on undecorated functions, but contains data in decorated functions. Not 100% sure this is true all the time, but maybe this works out for you.\n" ]
[ 3 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0005515520_django_django_views_python.txt
Q: Testing Python code in thread without modifications? Let's say I have this blob of code that's made to be one long-running thread of execution, to poll for events and fire off other events (in my case, using XMLRPC calls). It needs to be refactored into clean objects so it can be unit tested, but in the meantime I...
Testing Python code in thread without modifications?
Let's say I have this blob of code that's made to be one long-running thread of execution, to poll for events and fire off other events (in my case, using XMLRPC calls). It needs to be refactored into clean objects so it can be unit tested, but in the meantime I want to capture some of its current behavior in some inte...
[ "\nThe last big issue is that the code under test is designed to run forever, until a Ctrl-C, and I don't see any way to force it to raise an exception or otherwise kill the thread \n\nThe point of Test-Driven Development is to rethink your design so that it is testable.\nLoop forever -- while seemingly fine for pr...
[ 4, 0 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0004807624_python_testing.txt
Q: What is -s flag in the timeit module in Python? From Python Cookbook python timeit.py -s"import random" -s"x=range(100000); random.shuffle(x)" "sorted(x)" 10 loops, best of 3: 152 msec per loop What does the -s flag do? Searched online, python help and SO. But did not find a good explanation. Thanks. A: From P...
What is -s flag in the timeit module in Python?
From Python Cookbook python timeit.py -s"import random" -s"x=range(100000); random.shuffle(x)" "sorted(x)" 10 loops, best of 3: 152 msec per loop What does the -s flag do? Searched online, python help and SO. But did not find a good explanation. Thanks.
[ "From Python's built-in help() \n>>>import timeit\n>>>help(timeit)\n\n....\nCommand line usage:\n python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [--] [statement]\n\nOptions:\n -n/--number N: how many times to execute 'statement' (default: see below)\n -r/--repeat N: how many times to repeat the timer (de...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005510273_python.txt
Q: Django - How to use a filter with a foreign key field? I'm trying to do this: LogEntry.objects.filter(content_type='visitor') Where LogEntry is my model and content_type is a ForeignKey field pointing to another table with field id, and content_type (varchar). How can I search by the value of the other table? Wh...
Django - How to use a filter with a foreign key field?
I'm trying to do this: LogEntry.objects.filter(content_type='visitor') Where LogEntry is my model and content_type is a ForeignKey field pointing to another table with field id, and content_type (varchar). How can I search by the value of the other table? When I try to run the above it says: invalid literal for int(...
[ "Ahh, found it in another SO answer. Weird it didn't seem to be documented. Or I just skimmed over it.\nAnswer:\nLogEntry.objects.filter(content_type__name='visitor') \n\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005517314_django_django_models_python.txt
Q: Error in mysql query using python script I have wrote an instruction to fetch frequency from database using 2 id's as shown below: cursor = db.cursor() cursor.execute("select freq from matrix_brown where a_id in (%s) and b_id in (%s)",b_item_id,b_after_id) b_freq=cursor.fetchone() but i'm getting this error : cur...
Error in mysql query using python script
I have wrote an instruction to fetch frequency from database using 2 id's as shown below: cursor = db.cursor() cursor.execute("select freq from matrix_brown where a_id in (%s) and b_id in (%s)",b_item_id,b_after_id) b_freq=cursor.fetchone() but i'm getting this error : cursor.execute("select freq from matrix_brown whe...
[ "If you want execute to fill in the string your calling it wrong:\ncursor.execute(\"select freq from matrix_brown where a_id in (?) and b_id in (?)\", (b_item_id,b_after_id))\n\n", "cursor.execute(\"select freq from matrix_brown where a_id in (%s) and b_id in (%s)\",(b_item_id,b_after_id))\n\n" ]
[ 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0005517388_mysql_mysql_python_python.txt
Q: Multithreaded MySql Inserts with Python Below is the multi-thread script I use to upload data into MySQL. Using threading to do multiple inserts, sounds good to me. But there are no performance gains. MySql is set to accept multi connections, but when I check the process list I don't see the 5-10 connections I wou...
Multithreaded MySql Inserts with Python
Below is the multi-thread script I use to upload data into MySQL. Using threading to do multiple inserts, sounds good to me. But there are no performance gains. MySql is set to accept multi connections, but when I check the process list I don't see the 5-10 connections I would expect. The cxn string is Is there any wa...
[ "How many items are there in your queue ?\nAre all the operations on the same table ? If so, multi-threading might not help if you have select and insert/updates/delete because of locks on the table.\nFrom your exemple, we don't see where you create your connection. Is it created in each thread or are you using the...
[ 3 ]
[]
[]
[ "multithreading", "mysql", "python" ]
stackoverflow_0005517293_multithreading_mysql_python.txt
Q: How to import python script files in folders on Google App Engine? I'm fairly new to both Python and Google App Engine. I want to organize my script files by creating a folder structure. However when I do that I can no longer figure out how to import them. For example: main.py /eggs/spam.py How do I import spam...
How to import python script files in folders on Google App Engine?
I'm fairly new to both Python and Google App Engine. I want to organize my script files by creating a folder structure. However when I do that I can no longer figure out how to import them. For example: main.py /eggs/spam.py How do I import spam.py in main.py?
[ "Make eggs a package by adding an __init__.py file in the folder. It can be empty, as long as it's there. Then, import spam like this:\nimport eggs.spam\nMore information on packages.\n" ]
[ 10 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005517625_google_app_engine_python.txt
Q: Trying to implement import-> debug mode module So I am attempting to make a module that, when imported, will cause any exception to drop into pdb. I'm thinking it will look something like this: #file A.py import pdbOnException a = 1/0 print a #file pdbOnException import sys, pdb magic_object = # do magic stuff...
Trying to implement import-> debug mode module
So I am attempting to make a module that, when imported, will cause any exception to drop into pdb. I'm thinking it will look something like this: #file A.py import pdbOnException a = 1/0 print a #file pdbOnException import sys, pdb magic_object = # do magic stuff to get an object that, when called, does what I wan...
[ "That's pretty trivial, you just hook into sys.excepthook:\nfullofeels.py:\nimport sys, pdb\n\ndef except_hook(exctype, value, traceback):\n if previous_except_hook:\n previous_except_hook(exctype, value, traceback)\n\n pdb.post_mortem(traceback)\n\nprevious_except_hook = sys.excepthook\nsys.excepthook...
[ 3 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0005515940_debugging_python.txt
Q: How do I start and stop a Linux program using the subprocess module in Python? I’m writing a web app that uses Selenium to screen-scrape another website. This screen-scraping only happens once a day, so I’d rather not leave Selenium and Xvfb running all the time. I’m trying to figure out how to start Xvfb and Sele...
How do I start and stop a Linux program using the subprocess module in Python?
I’m writing a web app that uses Selenium to screen-scrape another website. This screen-scraping only happens once a day, so I’d rather not leave Selenium and Xvfb running all the time. I’m trying to figure out how to start Xvfb and Selenium from Python, and then stop them once the screen-scraping’s done. If I was doing...
[ "I don't know why you want to run Xvfb as root. Your usual X server only needs to run as root (on many but not all unices) only so that it can access the video hardware; that's not an issue for Xvfb by definition.\ntempdir = tempfile.mkdtemp()\nxvfb = subprocess.Popen(['Xvfb', ':99', '-nolisten', 'tcp', '-fbdir', t...
[ 7, 0 ]
[]
[]
[ "linux", "python", "selenium", "subprocess", "xvfb" ]
stackoverflow_0005516511_linux_python_selenium_subprocess_xvfb.txt
Q: Returning a dict value for a key, or the key if the dict does not contain that key Background: It had been a while since I had read https://stackoverflow.com/questions/228181/the-zen-of-python so I went to the interpreter and typed import this, then out of curiosity I inspected the contents of the newly imported t...
Returning a dict value for a key, or the key if the dict does not contain that key
Background: It had been a while since I had read https://stackoverflow.com/questions/228181/the-zen-of-python so I went to the interpreter and typed import this, then out of curiosity I inspected the contents of the newly imported this module and saw that this has some interesting attributes, most notably: >>> this.s "...
[ "Only way to know is to try :)\nSo here is my setup:\n>>> import timeit\n>>> cmd1 = \"\"\"\\\n... \"\".join(this.d[c] if c in this.d else c for c in this.s)\n... \"\"\"\n>>> cmd2 = \"\"\"\\\n... \"\".join(c in this.d and this.d[c] or c for c in this.s)\n... \"\"\"\n>>> cmd3 = \"\"\"\\\n... \"\".join(this.d.get(c, c...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005505822_python.txt
Q: Python development setup So, id like to start serious python development, and its proven to be a big pain. Im not worried at all about the language itself; I like it well enough and I will have no problems picking it up. But the ecosystem is driving me crazy. First I tried to get up and running under windows. I ga...
Python development setup
So, id like to start serious python development, and its proven to be a big pain. Im not worried at all about the language itself; I like it well enough and I will have no problems picking it up. But the ecosystem is driving me crazy. First I tried to get up and running under windows. I gave up on that after a few days...
[ "On Mac OS X, you can get spyder with macports. This should build everything needed. \nIf you prefer Windows, take a look at Python(x,y). It has a bunch of scientific tools pre-built, including spyder. \nFinally, the Enthought Python distribution is worth considering for scientific work.\n", "Have you tried Activ...
[ 5, 4, 3, 3, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0005405065_macos_python.txt
Q: how to use pyquery to modify a node attribute in python iwant use pyquery to do this. for example: html='<div>arya stark<img src="1111"/>ahahah<img src="2222"/></div>' a=PyQuery(html) i want to modify the html to <div>arya stark<img src="aaaa"/>ahahah<img src="bbbb"/></div> in other words, just need change img...
how to use pyquery to modify a node attribute in python
iwant use pyquery to do this. for example: html='<div>arya stark<img src="1111"/>ahahah<img src="2222"/></div>' a=PyQuery(html) i want to modify the html to <div>arya stark<img src="aaaa"/>ahahah<img src="bbbb"/></div> in other words, just need change img element's src attribute, and get the modified html. any ide...
[ "Since PyQuery is meant you mirror jQuery, perhaps this question would be relevant. Long story short, use the attr() method:\n>>> html='<div>arya stark<img src=\"1111\"/>ahahah<img src=\"2222\"/></div>'\n>>> a=PyQuery(html)\n>>> a.outerHtml()\n'<div>arya stark<img src=\"1111\">ahahah<img src=\"2222\"></div>'\n>>> f...
[ 2, 0 ]
[]
[]
[ "pyquery", "python" ]
stackoverflow_0005518052_pyquery_python.txt
Q: How to use a bundling/packetizing generator in Python? To amortize the function call overhead I have changed my generator so that it yields a fixed-length list of a few values instead of yielding one value at a time. The generator, as it originally stood, unpickled an object from a file that contains several pickl...
How to use a bundling/packetizing generator in Python?
To amortize the function call overhead I have changed my generator so that it yields a fixed-length list of a few values instead of yielding one value at a time. The generator, as it originally stood, unpickled an object from a file that contains several pickled objects, and yielded it. These were then processed inside...
[ "I think this is what you are talking about, let me know if I'm not on the right track.\nfor a, b, c in your_generator:\n # do stuff\n\nAssumes your_generator yields results as a sequence of exactly 3 items.\nYou can construct a generator that yields exactly n items at a time to use in your for loop with the fol...
[ 1 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0005518564_generator_python.txt
Q: How to have a nested inline formset within a form in Django? I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects. For example, I have a Contact model class Contact(mode...
How to have a nested inline formset within a form in Django?
I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects. For example, I have a Contact model class Contact(models.Model): ... And a Communication model class Communication...
[ "Of course it's possible - how do you think the admin does it?\nTake a look at the inline formsets documentation.\nEdited after comment Of course, you need to instantiate and render both the parent form and the nested formset. Something like:\ndef edit_contact(request, contact_pk=None):\n if contact_pk:\n ...
[ 18 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0005518826_django_django_forms_django_templates_python.txt
Q: Nose test coverage permission error I've started using nosetests today and everything works fine until I try: nosetests --with-coverage --cover-html --cover-html-dir=/tmp/cache which throws a permission denied error and I don't understand why it's trying to write to standard library packages: Traceback (most recen...
Nose test coverage permission error
I've started using nosetests today and everything works fine until I try: nosetests --with-coverage --cover-html --cover-html-dir=/tmp/cache which throws a permission denied error and I don't understand why it's trying to write to standard library packages: Traceback (most recent call last): File "/usr/bin/nosetests"...
[ "The nose --cover-html switch is outdated. You'll be happier with the results if you run nose first, then use coverage directly to generate the HTML:\n$ nosetests --with-coverage\n$ coverage html\n\nthen open htmlcov/index.html\n", "I found that I could use the --cover-package= argument with the name of the pack...
[ 4, 0 ]
[]
[]
[ "code_coverage", "nosetests", "python" ]
stackoverflow_0005498551_code_coverage_nosetests_python.txt
Q: wxPython's isChecked() responses are inconsistent- why? I have a graph with a popup menu that appears when the user right-clicks. Sub-option A is checked by default. I would like the user to be able to toggle this check mark for different behaviors. Thus, I would like to know if A is already checked or not, and I ...
wxPython's isChecked() responses are inconsistent- why?
I have a graph with a popup menu that appears when the user right-clicks. Sub-option A is checked by default. I would like the user to be able to toggle this check mark for different behaviors. Thus, I would like to know if A is already checked or not, and I would like this to be handled in its own function. Let's call...
[ "When you click on A, the check mark switches from True to False, which is why you see it output False there. However, you create and destroy your window every time which is why you never see it change the check state.\nHere is an example of how to set up the menu without creating and destroying it every time:\nimp...
[ 0 ]
[]
[]
[ "matplotlib", "popupmenu", "python", "wxpython" ]
stackoverflow_0005517454_matplotlib_popupmenu_python_wxpython.txt
Q: In Python, how do you play musical notes? Possible Duplicate: Python Music Library? Is there a way to play musical notes in Python? Also setting duration would be useful. If there are any built-in modules for it then that will be great, but if there is an outside module I need to download that is also fine. If ...
In Python, how do you play musical notes?
Possible Duplicate: Python Music Library? Is there a way to play musical notes in Python? Also setting duration would be useful. If there are any built-in modules for it then that will be great, but if there is an outside module I need to download that is also fine. If anyone can post exact examples that would be h...
[ "Look here for many audio libraries: http://wiki.python.org/moin/PythonInMusic\nYou probably want MusicKit.\n", "The Python standard library includes the winsound module, which allows you to play tones with a specific frequency and duration on Windows platforms.\n", "This is an interesting question I have never...
[ 5, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005518694_python.txt
Q: Does it make sense to pass a dict together with a key to pass a storage location? Better way? I would like to pass a storage container location to a class. Is there a better way to do it than by passing a dict and the key? Passing keys feels a little odd, though it seems to work. class GuiWidget(): def __init_...
Does it make sense to pass a dict together with a key to pass a storage location? Better way?
I would like to pass a storage container location to a class. Is there a better way to do it than by passing a dict and the key? Passing keys feels a little odd, though it seems to work. class GuiWidget(): def __init__(self, storageDict, storageDictKey): self.storageDict = storageDict self.storageDi...
[ "I guess you want to eliminate the dependence of your class on storage access method. That's my solution:\nclass GuiWidget():\n def __init__(self, accessFunc):\n self.accessFunc = accessFunc\n def inc(self):\n self.accessFunc(self.accessFunc() + 1)\n\nstorage = {\"k1\":0, \"k2\":0}\n\ndef getAcc...
[ 1 ]
[]
[]
[ "dictionary", "key", "python", "storage" ]
stackoverflow_0005517246_dictionary_key_python_storage.txt
Q: Does the firefox IDE for selenium export to regular python code using the selenium lib? The python selenium lib page has this sample: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.keys import Keys from time browser = webdriver.Firefox() # Get loc...
Does the firefox IDE for selenium export to regular python code using the selenium lib?
The python selenium lib page has this sample: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.keys import Keys from time browser = webdriver.Firefox() # Get local session of firefox browser.get("http://www.yahoo.com") # Load page assert browser.title ==...
[ "the first snippet uses the newer WebDriver API.\nthe second snippet uses the original Selenium 1 API.\nhttp://seleniumhq.org/docs/03_webdriver.html\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0005517822_python_selenium.txt
Q: How to color the entire row using xlwt util of pyexcelerator The util talks about a function called this style0 = xlwt.easyxf( 'font: name Times New Roman, colour_index red' ) there is color red instead of color_index too . Is there any provision to color the entire row? A: pattern: pattern solid This can be u...
How to color the entire row using xlwt util of pyexcelerator
The util talks about a function called this style0 = xlwt.easyxf( 'font: name Times New Roman, colour_index red' ) there is color red instead of color_index too . Is there any provision to color the entire row?
[ "pattern: pattern solid\n\nThis can be used to add color to row...\nthen u can add the color u want..\npattern: pattern solid,fore-color \"COLOR NAME\"\n\n", "You asked this question on the python-excel forum and got a comprehensive answer there ...\nBy the way: xlwt is a fork of pyExcelerator, with bug-fixes and...
[ 1, 0 ]
[]
[]
[ "pyexcelerator", "python", "xlwt" ]
stackoverflow_0005466746_pyexcelerator_python_xlwt.txt
Q: Can't import numpy into embedded ironpython engine From an ipy console I can import ironclad import numpy with no problem. However when I try the same imports with an embedded interpreter the numpy import fails. My Python engines is set up like this: public PyEngine() { //Frames option needed to ...
Can't import numpy into embedded ironpython engine
From an ipy console I can import ironclad import numpy with no problem. However when I try the same imports with an embedded interpreter the numpy import fails. My Python engines is set up like this: public PyEngine() { //Frames option needed to use sys.__getframe //used in Numpy and others. ...
[ "There are a couple of things that you can try: \n\nMake sure the you have setup the IRONPYTHONPATH system variable\nproperly to find the numpy module. Most of the time that's installed\nwithin your CPython directory structure, so you need to add the\npaths listed below. \nAs an alternative you can try to set the ...
[ 4, 0 ]
[]
[]
[ "ironclad", "ironpython", "numpy", "python" ]
stackoverflow_0002358731_ironclad_ironpython_numpy_python.txt
Q: Editing Python scripts with Python I'm trying to permanently edit variables within a Python script' source. e.g. urlpatterns = patterns('core.views', ) to urlpatterns = patterns('core.views', url(r'^admin/', include(admin.site.urls)), ) e.g. items = [ 'unicorn', 'cats', ] to items = [ 'unicorn'...
Editing Python scripts with Python
I'm trying to permanently edit variables within a Python script' source. e.g. urlpatterns = patterns('core.views', ) to urlpatterns = patterns('core.views', url(r'^admin/', include(admin.site.urls)), ) e.g. items = [ 'unicorn', 'cats', ] to items = [ 'unicorn', 'cats', 'knights', 'panth...
[ "Python source code is, for this matter, a text file, so you pretty much open it and read/write data the usual way. I don’t think this is an amazingly good idea, but if you’re writing an installer of some sort...\n", "If you're generating from a template, you could use plain old string formatting:\ntmpl = \"\"\"i...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005519416_python.txt
Q: Pass multiple lines in a variable How would I pass variable "tabbing" from NewsTabs.py to GUI.py and have it run in GUI.py GUI.py from Tkinter import * from notebook import * import NewsFeed import NewsTabs root = Tk() n = notebook(root, TOP) f1 = Frame(n()) NewsTabs.Tabs f2 = Frame(n()) lable1 = Label(f2, tex...
Pass multiple lines in a variable
How would I pass variable "tabbing" from NewsTabs.py to GUI.py and have it run in GUI.py GUI.py from Tkinter import * from notebook import * import NewsFeed import NewsTabs root = Tk() n = notebook(root, TOP) f1 = Frame(n()) NewsTabs.Tabs f2 = Frame(n()) lable1 = Label(f2, text="Pre Alpha! \n Version 0.0.0.1 \n Fou...
[ "In any other source file (in your case, probably GUI.py):\nimport NewsTabs\n\ntabs = NewsTabs.Tabs()\n\nor:\nimport NewsTabs\ntabs = NewsTabs.tabbing\n\nThe first would be useful if NewsTab does not have a constant value.\nBe aware that your variable Tabbing is not valid Python. You need to take all of the code in...
[ 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005519753_python_variables.txt
Q: Distributing python application I am writing a quite large Python application; the application is actually to a large part a wrapping of several shared libraries written in C and C++(Qt). I am 'installing' this without administrator rights, so everything including shared libraries, binary and also Python modules m...
Distributing python application
I am writing a quite large Python application; the application is actually to a large part a wrapping of several shared libraries written in C and C++(Qt). I am 'installing' this without administrator rights, so everything including shared libraries, binary and also Python modules must be in non-standard locations, i.e...
[ "Why waste time detesting shell scripts? \nSince you won't install in a standard location, (and can't seem to get sys admins to install needed packages in standard locations) that's almost your only alternative.\nYou can set the PYTHONPATH from within Python. It's in sys.path. Setting an environment variable (li...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005519222_python.txt
Q: Regex and unicode I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that ha...
Regex and unicode
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names (...
[ "Use a subrange of [\\u0000-\\uFFFF] for what you want.\nYou can also use the re.UNICODE compile flag. The docs say that if UNICODE is set, \\w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. \nSee also http://coding.derkeiler.com/Archive/Py...
[ 20, 5, 4, 0 ]
[]
[]
[ "character_properties", "python", "regex", "unicode" ]
stackoverflow_0000014389_character_properties_python_regex_unicode.txt
Q: regular expression and unicode utf-8 in python? I have block of code:( Django code ) list_temp = [] tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE) for key,tag in list.items(): if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG: ...
regular expression and unicode utf-8 in python?
I have block of code:( Django code ) list_temp = [] tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE) for key,tag in list.items(): if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG: raise forms.ValidationError(_('please use ...
[ "ោ (U+17C4 KHMER VOWEL SIGN OO) and ា (U+17B6 KHMER VOWEL SIGN AA) are not letters, they're combining marks, so they don't match \\w.\n", "bobince's answer is certainly correct. However, before you hit that problem there might be another one - is tag definitely a unicode rather than a str? For example:\n>>> str...
[ 5, 4, 4 ]
[]
[]
[ "django", "python", "regex", "unicode" ]
stackoverflow_0005441183_django_python_regex_unicode.txt
Q: Python: How to get the Index of a string How can I write a function that returns the index of a single character in a string without using the index method a.k.a string.index('some random character')? A: Another variant that works with multiple occurrences of char in string. def idx(string, char): for key, x ...
Python: How to get the Index of a string
How can I write a function that returns the index of a single character in a string without using the index method a.k.a string.index('some random character')?
[ "Another variant that works with multiple occurrences of char in string.\ndef idx(string, char):\n for key, x in enumerate(string):\n if x == char:\n print key\n\n", "index() is the same thing as find() except for the error when the string isn't found.\n", "it's a school task?\ndef ind(the_string, the_...
[ 3, 0, 0 ]
[]
[]
[ "indexing", "python", "string" ]
stackoverflow_0005520180_indexing_python_string.txt
Q: Removing carriage return characters from a file using python import os import sys files = os.listdir(sys.argv[1]) for file in files: if file[-4:] == ".png": os.rename(file, file.replace('\r', '')) Am using the above code to remove \r from the file name, but some how when I execute I get the following...
Removing carriage return characters from a file using python
import os import sys files = os.listdir(sys.argv[1]) for file in files: if file[-4:] == ".png": os.rename(file, file.replace('\r', '')) Am using the above code to remove \r from the file name, but some how when I execute I get the following error Traceback (most recent call last): File "renameImages.py"...
[ "You didn't tell it the directory of the file, that was declared in argv[1]\ntry os.rename(sys.argv[1]+\"/file\",sys.argv[1]+\"/\"+replace('\\r'','')\n(or '\\\\' for Windows).\n", "You can use str.rstrip('\\r') method to remove a set of characters from the right side of a string:\n>>> s=\"this is your brain on dr...
[ 5, 1 ]
[]
[]
[ "carriage_return", "python" ]
stackoverflow_0005520251_carriage_return_python.txt
Q: Performance Analysis of mod_python Trac instance I would like to enable a side-logging in our real-world Trac/mod_python installation that has gotten quite slow (lots of plugins, not so many tickets/pages). Can I proxy the request object, or add a python trace (with timestamps for each call) somehow? Is there e me...
Performance Analysis of mod_python Trac instance
I would like to enable a side-logging in our real-world Trac/mod_python installation that has gotten quite slow (lots of plugins, not so many tickets/pages). Can I proxy the request object, or add a python trace (with timestamps for each call) somehow? Is there e mechanism for these kind of wrappers? The main entry poi...
[ "Using the cProfile module, something like this should work:\ndef handler(req):\n pkg_resources.require('Trac==%s' % VERSION)\n gateway = ModPythonGateway(req, req.get_options())\n\n from trac.web.main import dispatch_request\n import cProfile\n from datetime import datetime\n\n def profile_reques...
[ 3, 2 ]
[]
[]
[ "mod_python", "python", "trac" ]
stackoverflow_0005511301_mod_python_python_trac.txt
Q: How to stop iteration when if statement is true? I'm having some troubles with stopping iteration in Python. This problem occurs in function: for z in range(w.steps): for i in range(1,w.x-1): for j in range(1,w.y-1): print (i, j) for r in data.c: if w.world[i][j]...
How to stop iteration when if statement is true?
I'm having some troubles with stopping iteration in Python. This problem occurs in function: for z in range(w.steps): for i in range(1,w.x-1): for j in range(1,w.y-1): print (i, j) for r in data.c: if w.world[i][j] in r: print r ...
[ "If I understood correctly, you need to place a break statement.\nfor z in range(w.steps):\n for i in range(1,w.x-1):\n for j in range(1,w.y-1):\n print (i, j)\n for r in data.c:\n if w.world[i][j] in r:\n print r\n ind = data.c.in...
[ 2, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0005520145_iteration_python.txt
Q: join two lists by interleaving I have a list that I create by parsing some text. Let's say the list looks like charlist = ['a', 'b', 'c'] I would like to take the following list numlist = [3, 2, 1] and join it together so that my combined list looks like [['a', 3], ['b', 2], ['c', 1]] is there a simple method ...
join two lists by interleaving
I have a list that I create by parsing some text. Let's say the list looks like charlist = ['a', 'b', 'c'] I would like to take the following list numlist = [3, 2, 1] and join it together so that my combined list looks like [['a', 3], ['b', 2], ['c', 1]] is there a simple method for this?
[ "If you want a list of lists rather than a list of tuples you could use:\nmap(list,zip(charlist,numlist))\n\n", "The zip builtin function should do the trick.\nExample from the docs:\n>>> x = [1, 2, 3]\n>>> y = [4, 5, 6]\n>>> zipped = zip(x, y)\n>>> zipped\n[(1, 4), (2, 5), (3, 6)]\n\n", "Here's another easy wa...
[ 9, 7, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005520310_python.txt
Q: None Type issues in Python 2.6 I'm doing a script where I get some values from a Database but sometimes this value can be None, but when I assign it to a variable and try to compare it I get this error: TypeError: 'NoneType' object is unsubscriptable I've already tried this: if sgSlate[ 'sg_client_2' ][ 'name' ] ...
None Type issues in Python 2.6
I'm doing a script where I get some values from a Database but sometimes this value can be None, but when I assign it to a variable and try to compare it I get this error: TypeError: 'NoneType' object is unsubscriptable I've already tried this: if sgSlate[ 'sg_client_2' ][ 'name' ] != None: self.ui.brandComboBox_2...
[ "The unsubscriptable error arises when you try to perform a [] operation on a None variable. So in this case, it is most likely the sgSlate['sg_client_2'] value that is None, not the sgSlate['sg_client_2']['name'] itself.\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005520454_python.txt
Q: Can't deploy my app to Google App Engine how am I supposed to import json on Google App Engine? My project works fine locally, but I just can't deploy it online. Here is my code: import json self.response.out.write(json.dumps(Jsonobject)) and this is the snippet from the log: <type 'exceptions.ImportError'>: No m...
Can't deploy my app to Google App Engine
how am I supposed to import json on Google App Engine? My project works fine locally, but I just can't deploy it online. Here is my code: import json self.response.out.write(json.dumps(Jsonobject)) and this is the snippet from the log: <type 'exceptions.ImportError'>: No module named json Traceback (most recent call l...
[ "Try replacing the first line with\nimport simplejson\n\nGoogle App Engine only supports certain packages when running on production.\n", "Brian M. Hunt says:\nfrom django.utils import simplejson as json\n\n" ]
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005520603_google_app_engine_python.txt
Q: Python crashing while calculating SHA-1 hashs for large files in Windows OS I am wondering if I could have some fresh eyes on this python script. It works fine with small and medium size files but with large ones (4-8GB or so) it inexplicable crashes after running for a couple of minutes. Zipped script here Or: i...
Python crashing while calculating SHA-1 hashs for large files in Windows OS
I am wondering if I could have some fresh eyes on this python script. It works fine with small and medium size files but with large ones (4-8GB or so) it inexplicable crashes after running for a couple of minutes. Zipped script here Or: import sys import msvcrt import hashlib #Print the file name (and its location) t...
[ "Stop reading the file in one go; you're consuming all the memory on the system. Read in 16MB or so chunks instead.\ndata = File.read(16 * 1024 * 1024)\n\n", "(In response to Peter's comment that 2 GB are left.)\nI suspect Ignacio is right nonetheless. Try replacing the read/update line with this:\nwhile True:\n ...
[ 9, 8 ]
[]
[]
[ "hash", "large_files", "python", "sha1" ]
stackoverflow_0005520585_hash_large_files_python_sha1.txt
Q: python _2or3 module? I am writing a module to let me write code in python 3, but still run it in 2. It looks surprisingly easy actually... anything else I should add? From my (limited) flailing on the interactive interpreter, the future imports do not affect python 3 and are viewed as redundant. # _2or3.py ''' C...
python _2or3 module?
I am writing a module to let me write code in python 3, but still run it in 2. It looks surprisingly easy actually... anything else I should add? From my (limited) flailing on the interactive interpreter, the future imports do not affect python 3 and are viewed as redundant. # _2or3.py ''' Common usage: from __futur...
[ "Check out six, that already does this, and loads more. It also has methods that helps you do binary and Unicode in both versions. Not all techniques you need to do can be done this way, though, especially if you need to support Python 2.5 or earlier. I tried to cover most of them in the book, but I'm sure I've mis...
[ 3 ]
[]
[]
[ "programming_languages", "python", "python_2.x", "python_3.x" ]
stackoverflow_0005520286_programming_languages_python_python_2.x_python_3.x.txt
Q: Why won't pygame accept more than 2 keyboard inputs? In every game I make with pygame it won't register any more then 2 simultaneous key presses. (e.g. if I'm holding up and left to move it won't let me press space to fire.) Is this software? Hardware? Is there anything I can do about it? EDIT: I use a Digital ...
Why won't pygame accept more than 2 keyboard inputs?
In every game I make with pygame it won't register any more then 2 simultaneous key presses. (e.g. if I'm holding up and left to move it won't let me press space to fire.) Is this software? Hardware? Is there anything I can do about it? EDIT: I use a Digital Media Keyboard 3000 on one computer and it does pretty goo...
[ "I have no experience with pygame, but is probably a hardware issue. You can use the KeyScan program mentioned in one of the answers posted there to test your keyboard.\n", "http://www.sjbaker.org/wiki/index.php?title=Keyboards_Are_Evil\n", "This varies widely from keyboard to keyboard; it's cheap hardware desi...
[ 2, 1, 0 ]
[]
[]
[ "events", "keyboard", "pygame", "python" ]
stackoverflow_0003893189_events_keyboard_pygame_python.txt
Q: python multithreaded server What I'm trying to program is a simple multithreaded python game server for fun. After much frustration, I've not been able to figure out why my test client connection times out. Here's my server.py code: import socket import threading import clientThread import struct import string cl...
python multithreaded server
What I'm trying to program is a simple multithreaded python game server for fun. After much frustration, I've not been able to figure out why my test client connection times out. Here's my server.py code: import socket import threading import clientThread import struct import string class Server: def __init__(sel...
[ "Do you have two systems? Does the server system have an IP of 192.168.1.1? If you only have one system, the localhost address is 127.0.0.1. That was the first change I had to make to your code to get a connection when running the server and client on the same system.\nAnother issue is your client thread doesn't...
[ 7 ]
[]
[]
[ "multithreading", "python", "sockets" ]
stackoverflow_0005520821_multithreading_python_sockets.txt
Q: How can this Python Scrabble word finder be made faster? I have no real need to improve it, it's just for fun. Right now it's taking about a second on a list of about 200K words. I've tried to optimize it as much as I know how (using generators instead of list comprehensions made a big difference), and I've run ou...
How can this Python Scrabble word finder be made faster?
I have no real need to improve it, it's just for fun. Right now it's taking about a second on a list of about 200K words. I've tried to optimize it as much as I know how (using generators instead of list comprehensions made a big difference), and I've run out of ideas. Do you have any? #!/usr/bin/env python # let's ch...
[ "Without going too far from your basic code, here are some fairly simple optimizations:\nFirst, change your word reader to be:\ndef word_reader(filename, L):\n L2 = L+2\n # returns an iterator\n return (word.strip() for word in open(filename) \\\n if len(word) < L2 and len(word) > 2)\n\nand call it as\n...
[ 17, 2, 2, 1, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0005485654_optimization_python.txt
Q: Python timing - There must be a better way! I hope someone can help me out with this. I'd like to measure sorting algorithms. Here's how I currently do it: M = 1000 # number of executions N = [1000, 2000, 4000, 16000] # size of the list L = [100, 1000, 2000,16000] # max element of the list # timing: print 'Number...
Python timing - There must be a better way!
I hope someone can help me out with this. I'd like to measure sorting algorithms. Here's how I currently do it: M = 1000 # number of executions N = [1000, 2000, 4000, 16000] # size of the list L = [100, 1000, 2000,16000] # max element of the list # timing: print 'Number of executions: %i' % (M) print '-'*80 print '\tL...
[ "timeit. Best way to time in Python, period. Refactor your algorithms into functions and use timeit to test the execution time.\n", "It is possible for you replace this code:\nA = [random.randint(0,l-1) for r in xrange(n)]\n\nWith generator? eg\ndef A(n):\n for r in xrange(n):\n yield random.randint(0,l...
[ 12, 2, 1, 0, 0 ]
[]
[]
[ "performance", "python", "testing", "timing" ]
stackoverflow_0004160006_performance_python_testing_timing.txt
Q: SQLalchemy: Mapping columns into different properties I am trying to store some simulation measurements (times and values) using sqlalchemy. Here are the relevant table definitions. If there is a more sensible table definition, I'd love to see it. from sqlalchemy import create_engine, schema, orm engine = creat...
SQLalchemy: Mapping columns into different properties
I am trying to store some simulation measurements (times and values) using sqlalchemy. Here are the relevant table definitions. If there is a more sensible table definition, I'd love to see it. from sqlalchemy import create_engine, schema, orm engine = create_engine('sqlite:///:memory:', echo=True) metadata = schema...
[ "class EmailAddress(object):\n\n @property\n def email(self):\n return self._email\n\n @email.setter\n def email(self, email):\n self._email = email\n\nmapper(EmailAddress, addresses_table, properties={\n '_email': addresses_table.c.email\n})\n\n" ]
[ 1 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0005007121_orm_python_sqlalchemy.txt
Q: Pygtk threading long command line process I am in PyGtk on Windows. My program converts PDF's to images using GraphicsMagick then displays the image. The conversion can be very long on multi-page PDF's so the program has to wait for the command line to return and I need to get around this and allow the user to use...
Pygtk threading long command line process
I am in PyGtk on Windows. My program converts PDF's to images using GraphicsMagick then displays the image. The conversion can be very long on multi-page PDF's so the program has to wait for the command line to return and I need to get around this and allow the user to use the GUI while the image is created. My attempt...
[ "Just use subprocess.Popen: \nimport subprocess\nsubprocess.Popen([\"command\", \"arg1\", \"arg2\"])\n\nFor more information see:\nhttp://docs.python.org/library/subprocess.html#using-the-subprocess-module\nIf you really need to use threads use gtk.gdk.threads_init() before gtk.main()\nhttp://library.gnome.org/deve...
[ 1, 0 ]
[]
[]
[ "command_line", "graphicsmagick", "pygtk", "python" ]
stackoverflow_0005503677_command_line_graphicsmagick_pygtk_python.txt
Q: Generating python code from ArgoUML UML model using Open Source tools? The open source UML tools can be really tricky. Even though exporting/importing in XMI, there seem to be a lot of incompatibilities between tools. Thus, I wonder if anybody found a good workflow for generating python code from UML models create...
Generating python code from ArgoUML UML model using Open Source tools?
The open source UML tools can be really tricky. Even though exporting/importing in XMI, there seem to be a lot of incompatibilities between tools. Thus, I wonder if anybody found a good workflow for generating python code from UML models created in ArgoUML, using Open Source tools?
[ "Did you try http://argouml-python.tigris.org/ ? If that doesn't suit, perhaps you could file bug reports so that people could fix the problems.\nIf you're looking for a different tool, you'll want one which accepts UML 1.4 which is what most recent versions of ArgouML implement.\nBTW, the UML/XMI compatibility pr...
[ 1, 1 ]
[]
[]
[ "argouml", "code_generation", "python", "uml" ]
stackoverflow_0005518309_argouml_code_generation_python_uml.txt
Q: Get all available combinations of two fields through the Django ORM? I have this Django model: class Lecture(models.Model): lecture_number = models.CharField(_('lecture number'), max_length=20) title = models.CharField(_('title'), max_length=100) term = models.IntegerField(_('term'), choices=TERM, db_i...
Get all available combinations of two fields through the Django ORM?
I have this Django model: class Lecture(models.Model): lecture_number = models.CharField(_('lecture number'), max_length=20) title = models.CharField(_('title'), max_length=100) term = models.IntegerField(_('term'), choices=TERM, db_index=True) year = models.IntegerField(_('year'), db_index=True) term ...
[ "if you have all the data in the database, then it will work. but if data is not there, you should generate it yourselves.\nIn [1]: import itertools\nIn [2]: list(itertools.product((2006,2007,2008), (1,2)))\nOut[2]: [(2006, 1), (2006, 2), (2007, 1), (2007, 2), (2008, 1), (2008, 2)]\n\ndirectly from the database (bu...
[ 5, 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0005521489_django_django_orm_python.txt