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: 2D table format Python I want to create a 2D table format from my data stored in a dictionary. Example: d = {'ID1':[('Experiment1', 40), (Experiment2, 59), (Experiment3, 65)], 'ID2':[('Experiment1', 68), (Experiment2, 21), (Experiment3, 39)], 'ID3':[('Experiment1', 57), (Experiment2, 15), (Experiment4, 9...
2D table format Python
I want to create a 2D table format from my data stored in a dictionary. Example: d = {'ID1':[('Experiment1', 40), (Experiment2, 59), (Experiment3, 65)], 'ID2':[('Experiment1', 68), (Experiment2, 21), (Experiment3, 39)], 'ID3':[('Experiment1', 57), (Experiment2, 15), (Experiment4, 99)]} Should give the follow...
[ "A quick and dirty implementation (fixing your typos in the question ...)\nd = {'ID1':[('Experiment1', 40), ('Experiment2', 59), ('Experiment3', 65)], \n 'ID2':[('Experiment1', 68), ('Experiment2', 21), ('Experiment3', 39)], \n 'ID3':[('Experiment1', 57), ('Experiment2', 15), ('Experiment4', 99)]}\n\nCOLUMN_WI...
[ 4 ]
[]
[]
[ "2d", "python", "tabular" ]
stackoverflow_0007414226_2d_python_tabular.txt
Q: python sdist recursive-include folder, where is it once installed? I have this in my MANIFEST.in recursive-include tables *.csv and I can see the folder included in the created .tar.gz /mypackage-0.0.1 /mypackage /mypackage.egg-info /tables but I can't find my folder once I install the package with: ...
python sdist recursive-include folder, where is it once installed?
I have this in my MANIFEST.in recursive-include tables *.csv and I can see the folder included in the created .tar.gz /mypackage-0.0.1 /mypackage /mypackage.egg-info /tables but I can't find my folder once I install the package with: pip install mypackage-0.0.1.tar.gz or easy_install mypackage-0.0.1.tar....
[ "With MANIFEST.in, you specify the files to embedd in the archive, not the way they will be installed. \nTo tell python/distutils where you want to install your files, add in your setup.py fill the parameter data_files in the setup() method. This way, you will be able to specify where to install those additional f...
[ 3 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0007414295_installation_python.txt
Q: Jinja 2 - Django Form : rendering encodes HTML I was testing Jinja2 in a Django project and have a strange output. When I render the form, some characters are HTML encoded (&lt; &gt; etc.) In the template : {{ form.as_p() }} It renders to the browser : <p><label for="id_username">Utilisateur:</label> <input autoc...
Jinja 2 - Django Form : rendering encodes HTML
I was testing Jinja2 in a Django project and have a strange output. When I render the form, some characters are HTML encoded (&lt; &gt; etc.) In the template : {{ form.as_p() }} It renders to the browser : <p><label for="id_username">Utilisateur:</label> <input autocomplete="off" id="id_username" type="text" name="use...
[ "Jinja2 tries to be safe by HTML-escaping the data. So you have to use |safe filter.\nThough I haven't used Django with Jinja2, I believe this should work:\n{{ form.as_p()|safe }}\n\n" ]
[ 27 ]
[]
[]
[ "django", "jinja2", "python" ]
stackoverflow_0007414637_django_jinja2_python.txt
Q: Is there any GPS library for use in Python? I am looking for Python library, which can work with GPS coordinates. Let's say, I have a list of coordinates: >>> gps = [ ... (53.25012925, −6.24479338, 349.9, '2011-08-20T09:35:00Z'), ... (53.25028285, -6.24441800, 359.9, '2011-08-20T09:35:30Z'), ... (53.25049500, -...
Is there any GPS library for use in Python?
I am looking for Python library, which can work with GPS coordinates. Let's say, I have a list of coordinates: >>> gps = [ ... (53.25012925, −6.24479338, 349.9, '2011-08-20T09:35:00Z'), ... (53.25028285, -6.24441800, 359.9, '2011-08-20T09:35:30Z'), ... (53.25049500, -6.24266032, 395.9, '2011-08-20T09:36:00Z'), ... ...
[ "I have found an interesting library named geopy. It can calculate distances between two GPS points (it uses great-circle distance and Vincenty distance methods). On top of that, geopy can do geocoding (it can get GPS coordinates from an address).\nThe other features (average speed, higest point, etc.) I can hack b...
[ 4, 3 ]
[]
[]
[ "gps", "python" ]
stackoverflow_0007346453_gps_python.txt
Q: How to convert global to local coordinates in blender 2.5? I want to move a bone in Blender 2.5 with the following script bpy.context.object.pose.bones['hand_ik.L'].location=(X1,Y1,Z1) but i have the global (X2,Y2,Z2). How can i convert X2,Y2,Z2 (with matrix manipulations) to the corresponding X1,Y1,Z1 I want t...
How to convert global to local coordinates in blender 2.5?
I want to move a bone in Blender 2.5 with the following script bpy.context.object.pose.bones['hand_ik.L'].location=(X1,Y1,Z1) but i have the global (X2,Y2,Z2). How can i convert X2,Y2,Z2 (with matrix manipulations) to the corresponding X1,Y1,Z1 I want to achieve the same movement as bpy.ops.transform.translate(valu...
[ "A few weeks ago, write access to PoseBose.matrix (The Armature-Space matrix of the bone) was granted to the python API. If you're using 2.59 or the latest trunk, you could use something like this code:\nfrom mathutils import Matrix\n\nob = bpy.context.object \nglobalVector = Vector((1.0, 0.0, 0.0)) \nmw = bpy.dat...
[ 1 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0007132018_blender_python.txt
Q: Dynamically loading instance method during object instantiation I want to be able to dynamically load instance methods during object instantiation. According to my design, the default behaviour is coded in the base class. However, if certain conditions are met during object instatination, I dynamically change this...
Dynamically loading instance method during object instantiation
I want to be able to dynamically load instance methods during object instantiation. According to my design, the default behaviour is coded in the base class. However, if certain conditions are met during object instatination, I dynamically change this behaviour with another piece of code. This is how I do it: The defau...
[ "If you change your code as follows then it should work:\nclass First(object):\n def __init__(self, p):\n p = str(p)\n #The decision whether or not to perform default action is done\n #in the following try/except block. In reality this block \n #is more complicated\n #and more ...
[ 1 ]
[]
[]
[ "code_injection", "dynamic", "python" ]
stackoverflow_0007413740_code_injection_dynamic_python.txt
Q: Django db.connection.cursor.fetchone() returns emty result, when raw SQL doesn't I have method in a cusom QuerySet that performs raw SQL query to database. class QuerySet(models.query.QuerySet): def get_short(self, language_code='en'): """Returns shortest name for given language""" cursor = con...
Django db.connection.cursor.fetchone() returns emty result, when raw SQL doesn't
I have method in a cusom QuerySet that performs raw SQL query to database. class QuerySet(models.query.QuerySet): def get_short(self, language_code='en'): """Returns shortest name for given language""" cursor = connection.cursor() cursor.execute('''SELECT t.name FROM translation t, name n ...
[ "Try without the \", \".join to format your first parameter.\ncursor.execute('''SELECT t.name FROM translation t, name n\n WHERE n.id IN %s\n AND t.link_id = n.id\n AND t.lang_id = %s\n ORDER BY CHAR_LENGTH(t...
[ 3 ]
[]
[]
[ "django", "mysql_python", "python", "sql" ]
stackoverflow_0007415029_django_mysql_python_python_sql.txt
Q: Returning a custom model instance from a manager I have a model that looks like this and stores data as key-value pairs. class Setting(models.Model): company = models.ForeignKey( Company ) name = models.CharField( null=False, max_length=255 ) value= models.CharField( nu...
Returning a custom model instance from a manager
I have a model that looks like this and stores data as key-value pairs. class Setting(models.Model): company = models.ForeignKey( Company ) name = models.CharField( null=False, max_length=255 ) value= models.CharField( null=False, max_length=255 ) I have a custom Manage...
[ "Here's how I did it.\nI needed to do this because I had a Model that stored information as key value pairs and I needed to build a ModelForm on that Model but the ModelForm should display the key-value pairs as fields i.e. pivot the rows to columns. By default, the get() method of the Model always returns a Model ...
[ 1 ]
[]
[]
[ "django", "django_managers", "django_models", "django_queryset", "python" ]
stackoverflow_0007362315_django_django_managers_django_models_django_queryset_python.txt
Q: Store form fields as key-values / individual rows I have a simple form in Django that looks like this: class SettingForm(forms.Form): theme = forms.CharField(rrequired=True, initial='multgi' ) defaultinputmessage = forms.CharField(required=True, initial='Type here to begin..' ) ......
Store form fields as key-values / individual rows
I have a simple form in Django that looks like this: class SettingForm(forms.Form): theme = forms.CharField(rrequired=True, initial='multgi' ) defaultinputmessage = forms.CharField(required=True, initial='Type here to begin..' ) ...and the model to store it looks like: class Setting(mod...
[ "I'm assuming you want to store 'theme' as the name and the value as the value, same for defaultinputmessage. If that's the case, this should work:\nform = SettingForm({'theme': 'sometheme', 'defaultinputmessage': 'hello'})\nif form.is_valid():\n for key in form.fields.keys():\n setting = Setting.objects....
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "key_value_store", "python" ]
stackoverflow_0007338865_django_django_forms_django_models_key_value_store_python.txt
Q: Python, Tkinter,How to change GUI based on buttonclick I am using Tkinter in a programming assignment and have the following problem. I want the user to enter the value in a textbox, and I want to add additional fields on the GUI based on the number entered in the textbox when he/she clicks the submit-button. I tr...
Python, Tkinter,How to change GUI based on buttonclick
I am using Tkinter in a programming assignment and have the following problem. I want the user to enter the value in a textbox, and I want to add additional fields on the GUI based on the number entered in the textbox when he/she clicks the submit-button. I tried to place code inside of the function 'displayText()', wh...
[ "The problem is in this line of code:\nbutton = tkinter.Button(root, text=\"Submit\", command=displayText())\n\nThe command option takes a reference to a command. What you are doing instead is calling a command (displayText()) and giving the results of that command to the option. You need to remove the () so that t...
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007415264_python_tkinter.txt
Q: optimizing simple server with multiple clients I've successfully implemented simple server with multiple clients: class ProcessingServer: def __init__(self, bindaddress="127.0.0.1", portname=50001, maxqueue=5): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((bi...
optimizing simple server with multiple clients
I've successfully implemented simple server with multiple clients: class ProcessingServer: def __init__(self, bindaddress="127.0.0.1", portname=50001, maxqueue=5): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((bindaddress, portname)) self.socket.listen(max...
[ "I’d suggest that select returns that there is some writeable socket. And well, if there is no readable socket and outstring stays '', then you immediately run the loop again and again, causing high cpu load. So its probably better, to only add the wsocks if you actually need to write data. Then the select call wil...
[ 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0007403465_python_sockets.txt
Q: pydoc generated help-text with file handle parameters I have a function with the following parameter list: def print(*line, sep=' ', end='\n', file=sys.stdout, default = 'full'): Unfortunately the pydoc help text for the module shows it like this: FUNCTIONS print(*line, sep=' ', end='\n', file=<_io.TextIOWrapper ...
pydoc generated help-text with file handle parameters
I have a function with the following parameter list: def print(*line, sep=' ', end='\n', file=sys.stdout, default = 'full'): Unfortunately the pydoc help text for the module shows it like this: FUNCTIONS print(*line, sep=' ', end='\n', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp850'>, default='full')...
[ "Easy solution:\ndef print(*line, sep=' ', end='\\n', file=None, default = 'full'):\n '''If file is None, defaults to sys.stdout.'''\n\n if file is None:\n file = sys.stdout\n\n(But please consider not using print and file as identifiers. print esp. will break Python 2-compatibility forever.)\n" ]
[ 1 ]
[]
[]
[ "pydoc", "python" ]
stackoverflow_0007415386_pydoc_python.txt
Q: rdiff python module Is there a python module that has the functionality for computing rdiff signatures and delta differencing? I need to perform these operations on a cross-platform application so I'll need something that will bundle into py2exe, py2app etc. I've done a bunch of searching but I can't seem to get a...
rdiff python module
Is there a python module that has the functionality for computing rdiff signatures and delta differencing? I need to perform these operations on a cross-platform application so I'll need something that will bundle into py2exe, py2app etc. I've done a bunch of searching but I can't seem to get anything working. Pysync, ...
[ "rdiff-backup is written in Python. It appears to be using librsync under the covers and has a Python wrapper for it (look for _librsyncmodule.c in the source tree).\nThe following page may help to figure out how to build librsync on OS X and Windows: link.\n" ]
[ 1 ]
[]
[]
[ "backup_strategies", "delta", "diff", "librsync", "python" ]
stackoverflow_0007415680_backup_strategies_delta_diff_librsync_python.txt
Q: How to upload photos to a image hosting server programmatically? Hi guys I was wondering how does one upload pics to a image hosting site programmatically through python or java (python preferred). The site gives no ftp access just through a upload button on the site i.e only http access. Now I don't want any code...
How to upload photos to a image hosting server programmatically?
Hi guys I was wondering how does one upload pics to a image hosting site programmatically through python or java (python preferred). The site gives no ftp access just through a upload button on the site i.e only http access. Now I don't want any code here..I just cant figure out how to start out if u can guide me in th...
[ "*******************************\nATTENTION: This answer is outdated since the time it was written. Use requests library.\nhttp://docs.python-requests.org/en/latest/\n*******************************\n\n\nThis is a code sample that \"just works\" for me. It uses MultipartPostHandler for uploading files.\nimport urll...
[ 2 ]
[]
[]
[ "http", "image", "java", "python" ]
stackoverflow_0007414419_http_image_java_python.txt
Q: Better way to access super class method in multiple inheritance class Animal(object): def eat(self): print("I eat all") class C(object): def eat(self): print("I too eat") class Wolf(C, Animal): def eat(self): print("I am Non Veg") super(Wolf, self).eat() Animal...
Better way to access super class method in multiple inheritance
class Animal(object): def eat(self): print("I eat all") class C(object): def eat(self): print("I too eat") class Wolf(C, Animal): def eat(self): print("I am Non Veg") super(Wolf, self).eat() Animal.eat(self) w = Wolf() w.eat() I am learning multiple inheritance in...
[ "If you want to do sane multiple inheritance, you need everyone to be calling super except exactly one base class, which has as its duty not to call super. Having two completely-independent base classes with the same method isn't something that makes sense using OOP theory and is not something that Python has the t...
[ 7, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007415974_python.txt
Q: assigning a string with a combination of two and separate them in a list This is a simple example of what I am trying to do. Say, I have a random list which is the following: aa = 1 b = 2 c = 3 ao = 4 uw = 5 d = 6 ih = 7 I give the input to the program as: b d aa aw ay c In the input there are strings which don...
assigning a string with a combination of two and separate them in a list
This is a simple example of what I am trying to do. Say, I have a random list which is the following: aa = 1 b = 2 c = 3 ao = 4 uw = 5 d = 6 ih = 7 I give the input to the program as: b d aa aw ay c In the input there are strings which don't have values and are not present in the list like 'aw' and 'ay'. So, I have ...
[ "Step 1. Assign the phoneme values. You've done some of that. You need to finish all 37. It shouldn't be too hard.\naa = 1\nb = 2\nc = 3\nao = 4\nuw = 5\nd = 6 \nih = 7\n\nStep 2. Assign dipthong variables which are lists. This isn't too hard, either.\naw= [ ao, uw ]\nay= [ ao, ih ]\n\nStep 3. Create a neste...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007414160_python.txt
Q: Efficient way to format string i am writing the following sql query: "select someTableName.somefield, count(*) from someTableName WHERE someTableName.TimeStamp > %s and someTableName.EndTimeStamp < %s group by someTableName.ProviderUsername;", [from_date, to_data] this query can be used on three tables, so i do n...
Efficient way to format string
i am writing the following sql query: "select someTableName.somefield, count(*) from someTableName WHERE someTableName.TimeStamp > %s and someTableName.EndTimeStamp < %s group by someTableName.ProviderUsername;", [from_date, to_data] this query can be used on three tables, so i do not want to fix the table name so wha...
[ "You can use named variables in string formatting, like this:\n\"select %(tableName)s.somefield, count(*) from %(tableName)s WHERE %(tableName)s.TimeStamp > %(fromDate)s and %(tableName)s.EndTimeStamp < %(to_data)s group by %(tableName)s.ProviderUsername;\" %{'tableName':tableName, 'fromDate':fromDate, 'to_data':to...
[ 5, 3, 2, 0 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0007416167_formatting_python_string.txt
Q: Why is there a space in sys.argv[]? argc = len(sys.argv) if (argc < 3 or argc > 5): printusage() sys.exit() insensitive = 1 if ("-i" in sys.argv) else 0 boundaries = 1 if ("-b" in sys.argv) else 0 filename = sys.argv[argc-2] str = sys.argv[argc-1] print "Looking for '", str , "' in '" , filename , "'" ...
Why is there a space in sys.argv[]?
argc = len(sys.argv) if (argc < 3 or argc > 5): printusage() sys.exit() insensitive = 1 if ("-i" in sys.argv) else 0 boundaries = 1 if ("-b" in sys.argv) else 0 filename = sys.argv[argc-2] str = sys.argv[argc-1] print "Looking for '", str , "' in '" , filename , "'" The output is python count_words.py -b ...
[ "The space is not in sys.argv, it is caused by the use of commas when printing. Try\nprint \"Looking for '%s' in '%s'\" % (str, filename)\n\nAnd try to avoid shadowing the builtin str.\n", "It's because you're passing separate strings to the print statement, rather than concatenating them into one string and prin...
[ 7, 4, 3, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007416230_python.txt
Q: For loop - Sorting each character alphabetically within a list of words I have a list of words that I would like to sort by character in a list: ['alumni', 'orphan', 'binge', 'peanut', 'necktie'] I wanted to sort these alphabetically so they would end up being a list of: ['ailmnu', 'ahnopr', 'begin', 'aenptu', 'c...
For loop - Sorting each character alphabetically within a list of words
I have a list of words that I would like to sort by character in a list: ['alumni', 'orphan', 'binge', 'peanut', 'necktie'] I wanted to sort these alphabetically so they would end up being a list of: ['ailmnu', 'ahnopr', 'begin', 'aenptu', 'ceeiknt'] So far my code has been embarrassing: for i in range(len(splitfoo))...
[ "To do your whole thing nicely: \nitems = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']\nsorted_items = [\"\".join(sorted(item)) for item in items]\n\nHere I am using a list comprehension, which is a nice way of making small snippets like this. You can, if you want, expand it out to:\nitems = ['alumni', 'orpha...
[ 7, 4, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0007416370_for_loop_python.txt
Q: Use Python to parse html data which contains "&" I'm using the python library SGMLParser to parse some html. I encounter an html tag of the form <td class="school">Texas A&amp;M</td> I'd like to read out "Texas A&M". But when handle_data gets called, it gets called with "Texas A", and then, separately, "M" (quot...
Use Python to parse html data which contains "&"
I'm using the python library SGMLParser to parse some html. I encounter an html tag of the form <td class="school">Texas A&amp;M</td> I'd like to read out "Texas A&M". But when handle_data gets called, it gets called with "Texas A", and then, separately, "M" (quotes for clarity). How do I replace the &amp; string ...
[ "If you switch from the deprecated SGMLParser to a modern alternative such as LXML (which also handles HTML), this becomes trivial:\n>>> etree.fromstring('''<td class=\"school\">Texas A&amp;M</td>''').text\n'Texas A&M'\n\n", "SGMLParser has convert_entityref() method, but instead of deprecated SGMLParser I would ...
[ 4, 2, 1 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0007416587_html_parsing_python.txt
Q: Alpha-beta pruning with checkers I would like to implement an artificial intelligence for the checkers game. I must not understand the principle of alpha beta pruning because nothing works!! I would like that the algorithm stops at a certain time (5 or 10 secs). But, I think with my algorithm, it never stops. In a...
Alpha-beta pruning with checkers
I would like to implement an artificial intelligence for the checkers game. I must not understand the principle of alpha beta pruning because nothing works!! I would like that the algorithm stops at a certain time (5 or 10 secs). But, I think with my algorithm, it never stops. In addition the algorithm never cuts branc...
[ "File \"player.py\", line 61, in min_value and TypeError: unorderable types: NoneType() < float() are important hints. You should consider that actual error messages are more important than almost anything else you said about the problems you're having.\nSince you didn't read the error message, you left it to us ...
[ 3 ]
[]
[]
[ "artificial_intelligence", "python" ]
stackoverflow_0007414306_artificial_intelligence_python.txt
Q: Difference between 2 styles of closing file in Python Can somebody please explain the difference between the following? handler = open(printFile, "w") handler.close() and handler = open(printFile, "w") close(printFile) A: The difference is pretty simple: The latter does not exist. If it does in your ...
Difference between 2 styles of closing file in Python
Can somebody please explain the difference between the following? handler = open(printFile, "w") handler.close() and handler = open(printFile, "w") close(printFile)
[ "The difference is pretty simple: The latter does not exist.\nIf it does in your application, it's user-defined and might just call firstArgument.close() or do something else such as killing your dog.\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0007417128_python.txt
Q: from . import XXXX In one of my Python packages the __init__.py file contains the statement from . import XXXX What does the "." mean here? I got this technique by looking at another package, but I don't understand what it means. Thanks! A: Its a relative import. From: http://docs.python.org/py3k/reference/sim...
from . import XXXX
In one of my Python packages the __init__.py file contains the statement from . import XXXX What does the "." mean here? I got this technique by looking at another package, but I don't understand what it means. Thanks!
[ "Its a relative import.\nFrom: http://docs.python.org/py3k/reference/simple_stmts.html#the-import-statement\n\nWhen specifying what module to import you do not have to specify the\n absolute name of the module. When a module or package is contained\n within another package it is possible to make a relative import...
[ 12, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007417353_python.txt
Q: FileChooserDialog stuck on screen after destroy() I have a python script, requesting a file from user using FileChooserDialog. When done, it calls .destroy() on the dialog, but immediately after that begins to load the file. Since it is usually a large file, dialog "stays imprinted on screen" until parsing is done...
FileChooserDialog stuck on screen after destroy()
I have a python script, requesting a file from user using FileChooserDialog. When done, it calls .destroy() on the dialog, but immediately after that begins to load the file. Since it is usually a large file, dialog "stays imprinted on screen" until parsing is done, main window created and MainLoop run. Is it possible ...
[ "Try to force GTK to refresh the screen\n while gtk.events_pending(): # this forces the refresh of the screen\n gtk.main_iteration()\n\nbefore opening the file\n" ]
[ 4 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007417469_gtk_pygtk_python.txt
Q: How to use $gt and $lt on embedded list in mongodb I'm using pymongo and currently have a single collection. The collection holds documents representing matches in a football league. Each match has goals. Currently the goals are implemented as a list contained in the match object: {'matchID':1000, 'goals':[{'goa...
How to use $gt and $lt on embedded list in mongodb
I'm using pymongo and currently have a single collection. The collection holds documents representing matches in a football league. Each match has goals. Currently the goals are implemented as a list contained in the match object: {'matchID':1000, 'goals':[{'goalID':200,'scorer':'A'}, {'goalID':201,'scorer...
[ "You've got a couple of issues with that query:\n\nThe correct dotted field name for the goalID elements of the objects nested in the arrays should be \"goals.goalID\" -- that is, remove the preceding \"match.\"\nThe correct order for $gt (and friends: $gte, $lt, $lte) is field: {$operator: value}, like:\ndb.mycoll...
[ 2 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0007417436_mongodb_python.txt
Q: python - Values not being pulled from XML I have an XML file with the following structure: <root> <subroot id="someID"> <val1 value="a"/> <val2 value="b"/> <val3 value="c"/> <val4 value="1"/> <val5 value="2"/> <val6 value="3"/> <otherval value="xyz"/> </subroot> <subroot id="anoth...
python - Values not being pulled from XML
I have an XML file with the following structure: <root> <subroot id="someID"> <val1 value="a"/> <val2 value="b"/> <val3 value="c"/> <val4 value="1"/> <val5 value="2"/> <val6 value="3"/> <otherval value="xyz"/> </subroot> <subroot id="anotherID"> <val1 value="aa"/> <val2 value="...
[ "My suggestion is to structure your data as follows:\n<root>\n <subroot id=\"someID\">\n <value id=\"1\">a</value>\n <value id=\"2\">b</value>\n <value id=\"3\">c</value>\n <value id=\"4\">d</value>\n <value id=\"5\">2</value>\n <value id=\"6\">3</value>\n <value id=\"other\">xyz</value>\n </...
[ 4, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0007417378_python_xml.txt
Q: Importing a python module by path I have the following mis-fortunate situation: Three directories (A, B and C) contain a python module M with a function F. (Those directories are not packages and it is impossible to change anything about the situation.) I am looking for a way to import them separately to access th...
Importing a python module by path
I have the following mis-fortunate situation: Three directories (A, B and C) contain a python module M with a function F. (Those directories are not packages and it is impossible to change anything about the situation.) I am looking for a way to import them separately to access their functionalities. How do I need to i...
[ "This will work, but it seems a bit inelegant...\nimport sys\n\nsys.path.append(\"A\")\nimport M as A\n\nsys.path.pop()\ndel sys.modules['M']\n\nsys.path.append(\"B\")\nimport M as B\n\nand so on...\n\n", "You need to exec things into a new locals dictionary. You can only get to the files you mention as files, n...
[ 4, 4, 1 ]
[ "use import as like\nfrom A.M import F as A_F\n\n" ]
[ -2 ]
[ "import", "module", "path", "python" ]
stackoverflow_0007417599_import_module_path_python.txt
Q: How do Google App Engine Task Queues work? I'm confused about Task execution using queues. I've read the documentation and I thought I understood bucket_size and rate, but when I send 20 Tasks to a queue set to 5/h, size 5, all 20 Tasks execute one after the other as quickly as possible, finishing in less than 1 ...
How do Google App Engine Task Queues work?
I'm confused about Task execution using queues. I've read the documentation and I thought I understood bucket_size and rate, but when I send 20 Tasks to a queue set to 5/h, size 5, all 20 Tasks execute one after the other as quickly as possible, finishing in less than 1 minute. deferred.defer(spam.cookEggs, ...
[ "Execution rates are not honored by the app_devserver. This issue should not occur in production.\n[Answer discovered by Nick Johnson and/or question author; posting here as community wiki so we have something that can get marked accepted]\n" ]
[ 7 ]
[ "You want to set bucket_size to 1, or else you'll have \"bursts\" of queued activity like you saw there.\nFrom the documentation:\n\nbucket_size\nLimits the burstiness of the queue's\n processing, i.e. a higher bucket size\n allows bigger spikes in the queue's\n execution rate. For example, consider\n a queue w...
[ -1 ]
[ "google_app_engine", "python", "queue", "task" ]
stackoverflow_0004950872_google_app_engine_python_queue_task.txt
Q: how to create literal based query in sqlalchemy? I created one function for create expression def test(operator1, operation, operator2): return literal_column(operator1).op(operation)(operator2) Now when I call it with test(1, '=', 1) then it works But when I pass test('abc', '=', 'abc') Then it gives err...
how to create literal based query in sqlalchemy?
I created one function for create expression def test(operator1, operation, operator2): return literal_column(operator1).op(operation)(operator2) Now when I call it with test(1, '=', 1) then it works But when I pass test('abc', '=', 'abc') Then it gives error that abc is not a column. I tried to convert it de...
[ "any literal value can be converted to an expression construct:\nfrom sqlalchemy import literal_column, bindparam\n\n\n# ? = ?, 1 will be bound\nbindparam(1) == bindparam(1)\n\n# \" 1 = 1\", literals rendered inline (no quoting is applied !!)\nliteral_column(str(1)) == literal_column(str(1))\n\n" ]
[ 2 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0007411812_python_sql_sqlalchemy.txt
Q: Python find out contents of compiled module? So have this Python .pyd module (C++), so I can't just open it in a text editor to find out what it contains. So how can I? I just want to know the function names inside it. A: Python have full reflection. You can do the following (for a modulename.pyd) python >>> i...
Python find out contents of compiled module?
So have this Python .pyd module (C++), so I can't just open it in a text editor to find out what it contains. So how can I? I just want to know the function names inside it.
[ "Python have full reflection.\nYou can do the following (for a modulename.pyd)\n python\n >>> import modulename as mtmp\n >>> dir(mtmp)\n >>> help(mtmp)\n\nEDIT : Add help command as propose by Mike Graham\n" ]
[ 12 ]
[]
[]
[ "compiled", "module", "pyd", "python" ]
stackoverflow_0007418115_compiled_module_pyd_python.txt
Q: Mysterious and weird lines after using uni-form I'm using django-uni-form to display forms. I've included all the css and javascript (notably jquery) in the page. But now I get some weird looking lines. The image below show how it looks: http://i243.photobucket.com/albums/ff176/cwalkrox/uni-form1.jpg You can notic...
Mysterious and weird lines after using uni-form
I'm using django-uni-form to display forms. I've included all the css and javascript (notably jquery) in the page. But now I get some weird looking lines. The image below show how it looks: http://i243.photobucket.com/albums/ff176/cwalkrox/uni-form1.jpg You can notice that for username and email address, the lines are ...
[ "Those lines are due to the css files included in django-uniform: uni-form.css, uni-form-generic.css and uni-form.jquery.css. \nIt seems weird but at least in my case (a pinax project) the forms look better without the provided css.\nmy 2 cents\n" ]
[ 0 ]
[]
[]
[ "css", "django", "python", "uniform" ]
stackoverflow_0003884247_css_django_python_uniform.txt
Q: How do I get a set of grammar rules from Penn Treebank using python & NLTK? I'm fairly new to NLTK and Python. I've been creating sentence parses using the toy grammars given in the examples but I would like to know if it's possible to use a grammar learned from a portion of the Penn Treebank, say, as opposed to j...
How do I get a set of grammar rules from Penn Treebank using python & NLTK?
I'm fairly new to NLTK and Python. I've been creating sentence parses using the toy grammars given in the examples but I would like to know if it's possible to use a grammar learned from a portion of the Penn Treebank, say, as opposed to just writing my own or using the toy grammars? (I'm using Python 2.7 on Mac) Many ...
[ "If you want a grammar that precisely captures the Penn Treebank sample that comes with NLTK, you can do this, assuming you've downloaded the Treebank data for NLTK (see comment below):\nimport nltk\nfrom nltk.corpus import treebank\nfrom nltk.grammar import ContextFreeGrammar, Nonterminal\n\ntbank_productions = se...
[ 13, 3 ]
[]
[]
[ "grammar", "nltk", "parsing", "python", "tagged_corpus" ]
stackoverflow_0007056996_grammar_nltk_parsing_python_tagged_corpus.txt
Q: In python or coffeescript, why list.append not return the list itself ? recursion can be a lot simpler if so consider the following code if insert() return the list itself. def sieve(l): if not len(l): return [] return sieve(filter(lambda x: x%l[0] != 0, l)).insert(0, l[0]) For now, we have to rely on a h...
In python or coffeescript, why list.append not return the list itself ? recursion can be a lot simpler if so
consider the following code if insert() return the list itself. def sieve(l): if not len(l): return [] return sieve(filter(lambda x: x%l[0] != 0, l)).insert(0, l[0]) For now, we have to rely on a helper function to return the list after insertion. def cons(a, l): l.insert(0, a) return l def sieve(l): if...
[ "In Python, it is a big deal to get beginners to learn which objects are “immutable” and cannot be changed, and which are “mutable” and can be altered — in the latter case, every reference to the object sees the same change. This really seems to confuse newcomers. “I innocently called this function I wrote, and sud...
[ 14, 4, 0 ]
[]
[]
[ "coffeescript", "functional_programming", "python" ]
stackoverflow_0007410850_coffeescript_functional_programming_python.txt
Q: How do I return data from a related model in Django Tastypie? How do I bring in the information from another model? I have two models Article, and ArticleBody Article containing the main info and ArticleBody containing a loop of body and image information class Article(models.Model): author = models.ForeignKey...
How do I return data from a related model in Django Tastypie?
How do I bring in the information from another model? I have two models Article, and ArticleBody Article containing the main info and ArticleBody containing a loop of body and image information class Article(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=100) excerpt = m...
[ "class NewsBodyResource(ModelResource):\n class Meta:\n queryset = ArticleBody.objects.all()\n resource_name = 'article_body'\n\nclass NewsResource(ModelResource):\n newsbodies = fields.ToManyField('yourapp.api.resources.NewsBodyResource', 'articlebody_set', full=True)\n\n class Meta:\n ...
[ 5 ]
[]
[]
[ "api", "django", "django_models", "python", "tastypie" ]
stackoverflow_0007415138_api_django_django_models_python_tastypie.txt
Q: Django debugging with Emacs I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to pr...
Django debugging with Emacs
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?
[ "This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function:\nimport pdb; pdb.set_trace()\nNow when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the f...
[ 19, 13, 3, 1, 0, 0 ]
[]
[]
[ "debugging", "django", "emacs", "python" ]
stackoverflow_0000283294_debugging_django_emacs_python.txt
Q: How do I resolve namespace conflicts in my Python packages with standard library package names? I am developing a package with the following structure on disk: foo/ __init__.py xml.py bar.py moo.py The xml.py package provides a class that does some custom XML parsing and translation for the other pack...
How do I resolve namespace conflicts in my Python packages with standard library package names?
I am developing a package with the following structure on disk: foo/ __init__.py xml.py bar.py moo.py The xml.py package provides a class that does some custom XML parsing and translation for the other package components using a SAX stream parser. So it has in it: import xml.sax import xml.sax.handler But...
[ "As mentioned over here, use\nfrom __future__ import absolute_import\n\nand use relative imports if needed.\n" ]
[ 15 ]
[]
[]
[ "namespaces", "package", "python" ]
stackoverflow_0007418996_namespaces_package_python.txt
Q: printing the corresponding elements of dictionary Here is the solution to the question I had asked here assigning a string with a combination of two and separate them in a list. The earlier question was an example and below is the actual program. import sys param_values = { 'vowels':{ 'a...
printing the corresponding elements of dictionary
Here is the solution to the question I had asked here assigning a string with a combination of two and separate them in a list. The earlier question was an example and below is the actual program. import sys param_values = { 'vowels':{ 'aa' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1), (0.1,...
[ "Replace the section where the phonemes are added with the following:\nif next_phoneme is None :\n phonemeList.append((phoneme, param_values.get(phoneme)))\nelse : \n phonemeList.extend([(phoneme, param_values.get(phoneme)) for phoneme in next_phoneme])\n\nThis adds the full tuples, not just the names.\n", ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007418921_python.txt
Q: Why tuple assignment failed? I have tried to assign new data to existing tuple, and it does not work.and actually I want to add the a and b to get a sum, however only string can be iterated.. A=[('3', '4'), ('3', '11'), ('8', '10')] print A for a,b in A: a,b = int(a), int(b)+int(a) print A results: [('3',...
Why tuple assignment failed?
I have tried to assign new data to existing tuple, and it does not work.and actually I want to add the a and b to get a sum, however only string can be iterated.. A=[('3', '4'), ('3', '11'), ('8', '10')] print A for a,b in A: a,b = int(a), int(b)+int(a) print A results: [('3', '4'), ('3', '11'), ('8', '10')] [...
[ "When you set a, b = int(a), int(b)+int(a), you do not change the actual object a and b came from; you just bind new objects the variables a and b...\nYou can create a new list B, and populate it:\nA=[('3', '4'), ('3', '11'), ('8', '10')] \nprint A\nB = []\nfor a, b in A:\n B.append((int(a), int(b) + int(a)))\np...
[ 6, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007418090_python.txt
Q: Click on gtk.Expander custom label-widget doesn't work I'm triying to put dinamically several gtk.Expander inside a gtk.VBox and have a custom widget-label with a gtk.HBox with a gtk.Label and a gtk.Button/gtk.Image inside it to have a delete button, something similar to some list widgets found on MacOS X, for exa...
Click on gtk.Expander custom label-widget doesn't work
I'm triying to put dinamically several gtk.Expander inside a gtk.VBox and have a custom widget-label with a gtk.HBox with a gtk.Label and a gtk.Button/gtk.Image inside it to have a delete button, something similar to some list widgets found on MacOS X, for example at Automator (image). Look the close button at the righ...
[ "I would suggest creating your own custom widget, perhaps inheriting from Expander. Here is a tutorial on subclassing widgets in PyGTK.\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007415032_gtk_pygtk_python.txt
Q: error when running "Check for updates" I am running Aptana Studio 3, build: 3.0.4.201108101506. When I run "Check for updates" I get the following error "A Problem occurred" No repository found at file:/C:/Users/Keith/AppData/Local/Aptana%20Studio%203/plugins/com.python.pydev_2.2.1.2011073123/. Any help would be...
error when running "Check for updates"
I am running Aptana Studio 3, build: 3.0.4.201108101506. When I run "Check for updates" I get the following error "A Problem occurred" No repository found at file:/C:/Users/Keith/AppData/Local/Aptana%20Studio%203/plugins/com.python.pydev_2.2.1.2011073123/. Any help would be appreciated
[ "Looks like that filepath is set up as an update site in your preferences. I'd just remove it, since it looks invalid (maybe you installed a pydev zip from here?). Go to Preferences > Install/Update > Available Software Sites and then remove the entry for it.\n" ]
[ 0 ]
[]
[]
[ "aptana", "python" ]
stackoverflow_0007368288_aptana_python.txt
Q: Parsing Multiple Fields to Single Color Vector in Python Is there a good pattern in Python to use for parsing multiple lines of an input file into a single value? For example, I've got an input file that looks something like: BackgroundColor_R=0.0 BackgroundColor_G=0.0 BackgroundColor_B=0.0 BackgroundColor_A=0.0 D...
Parsing Multiple Fields to Single Color Vector in Python
Is there a good pattern in Python to use for parsing multiple lines of an input file into a single value? For example, I've got an input file that looks something like: BackgroundColor_R=0.0 BackgroundColor_G=0.0 BackgroundColor_B=0.0 BackgroundColor_A=0.0 DensityCorrection_Color_R=1.0 DensityCorrection_Color_G=1.0 Den...
[ "You can parse such file with ini file parser. http://docs.python.org/library/configparser.html. \nBut data structures is up to you. It depends on your needs.\n", "Something like this should work (but using configparser would be better for the first bit):\ndata = {}\n\nfor l in open('input').readlines():\n key...
[ 0, 0, 0 ]
[]
[]
[ "3d", "parsing", "python" ]
stackoverflow_0007418709_3d_parsing_python.txt
Q: Which haml-in-django implementation? I'd rather like to use something like HAML in django, but it seems there are a few alternatives, and I can't really tell the difference between them: hamlpy I'm leaning towards this one, and djaml makes it easy to use dmsl Also known as 'damsel', not sure how it differs from h...
Which haml-in-django implementation?
I'd rather like to use something like HAML in django, but it seems there are a few alternatives, and I can't really tell the difference between them: hamlpy I'm leaning towards this one, and djaml makes it easy to use dmsl Also known as 'damsel', not sure how it differs from hamlpy, Announced here, has a nice looking ...
[ "I think hamlpy is the best choice, simple, fast, does all one would expect from an abstraction language. http://www.reddit.com/r/django/comments/k9afb/html_the_easy_way/\n" ]
[ 1 ]
[]
[]
[ "django", "haml", "python" ]
stackoverflow_0007409602_django_haml_python.txt
Q: A Few Python questions I'm trying to learn Python from a background in javascript. I saw someone make a recursive function to find the least common denominator and wondered why they didn't just use a loop, so, both for the experience and to amuse myself, I wrote a simpler one: I came up with: def LCM(n,d): whi...
A Few Python questions
I'm trying to learn Python from a background in javascript. I saw someone make a recursive function to find the least common denominator and wondered why they didn't just use a loop, so, both for the experience and to amuse myself, I wrote a simpler one: I came up with: def LCM(n,d): while(n%d++ != 0 ): con...
[ "Python does not allow assignments (such as i+=1) in expressions since those can lead to confusing code, and Python is designed to make it hard to write confusing code, and make it simple to write obvious code.\nYou can simply write this:\ndef LCM(n,d):\n while n%d != 0:\n d += 1\n return d-1\nprint(L...
[ 8, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0007420019_javascript_python.txt
Q: How can I print a plot in matplotlib either from the plot window or with a command? is there a way to print a plot from matplotlib,either with a command or from the plot window itself ? I know i could save it and then print,but I am looking for something more automated.Thanks. A: You could save the figure as a p...
How can I print a plot in matplotlib either from the plot window or with a command?
is there a way to print a plot from matplotlib,either with a command or from the plot window itself ? I know i could save it and then print,but I am looking for something more automated.Thanks.
[ "You could save the figure as a pdf, then use subprocess to print the pdf. On *nix, lpr could be used:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport subprocess\nimport shlex\n\nn=20\nx=np.linspace(0,np.pi,n)\ny=np.sin(x)\nplt.plot(x,y)\nfname='/tmp/test.pdf'\nplt.savefig(fname)\nproc=subprocess.Popen...
[ 5, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007419787_matplotlib_python.txt
Q: How do I pull data from XML document from between XML tags in Django/Python? I have an external xml file that I am loading in my views.py file def test(request): url = urllib2.urlopen("http://someurl.com?xml") dom = minidom.parse(url) groups = dom.getElementsByTagName("group") deal_holder = [] ...
How do I pull data from XML document from between XML tags in Django/Python?
I have an external xml file that I am loading in my views.py file def test(request): url = urllib2.urlopen("http://someurl.com?xml") dom = minidom.parse(url) groups = dom.getElementsByTagName("group") deal_holder = [] # Iterate over each DOM group element: for group in groups: # I...
[ "Using minidom is quite similar to javascript.\nfrom xml.dom import minidom\nfrom StringIO import StringIO\na = \"\"\"<page>\n <site>\n <siteid>25550</siteid>\n <sitename>\n <![CDATA[ Some Text Here ]]>\n </sitename>\n <sitelink>\n http://somelinkehere.com\n ...
[ 2, 1 ]
[]
[]
[ "django", "django_views", "python", "web_scraping", "xml" ]
stackoverflow_0007420308_django_django_views_python_web_scraping_xml.txt
Q: Django - One view, multiple URLs? I am fairly new to both Python and Django and would like to follow best practices where possible. I would like to tidy up the following code to make it easier to work with. I am trying to set up a view which can be accessed through multiple URLs which provide different parameters...
Django - One view, multiple URLs?
I am fairly new to both Python and Django and would like to follow best practices where possible. I would like to tidy up the following code to make it easier to work with. I am trying to set up a view which can be accessed through multiple URLs which provide different parameters for which a queryset will be returned ...
[ "Sure. You can use a dictionary:\nmy_queryset_filters = {\n 'user': self.request.user,\n 'date__year': self.kwargs['year'],\n}\n\nRecord.objects.filter(**my_queryset_filters)\n\nThe ** expands the dictionary into keyword arguments. (There's also * which expands a list into positional arguments.)\n" ]
[ 5 ]
[]
[]
[ "django", "models", "python", "views" ]
stackoverflow_0007420430_django_models_python_views.txt
Q: Optimize non-abundant sums algorithm I am trying to solve this Project Euler question: A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect nu...
Optimize non-abundant sums algorithm
I am trying to solve this Project Euler question: A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if th...
[ "You're testing every number between 1 and the limit (let's say 30000) against every abundant number, so you're doing roughly 30000 * 7428 iterations; and you're checking if the result is in a list, which is a very slow operation -- it checks every item on the list until it finds a match!\nInstead, you should gener...
[ 11, 5, 4, 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004882428_python.txt
Q: How do I access the related ForeignKey object from a object in SQLAlchemy? For example, I have an object mapped to a table. IE: location = db.Column(db.Integer, db.ForeignKey('location.id')) When I do object.location, I get the actual foreignkey value. But I don't want that, how can I get the object instead (like...
How do I access the related ForeignKey object from a object in SQLAlchemy?
For example, I have an object mapped to a table. IE: location = db.Column(db.Integer, db.ForeignKey('location.id')) When I do object.location, I get the actual foreignkey value. But I don't want that, how can I get the object instead (like in Django ORM). Thanks!
[ "If you're using declarative base objects (which is recommended if you want it more like Django) then:\nclass Child(Base):\n __tablename__ = 'child'\n id = Column(Integer, primary_key=True)\n\nclass Parent(Base):\n __tablename__ = 'parent'\n id = Column(Integer, primary_key=True)\n child_id = Column(...
[ 8 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007420670_python_sqlalchemy.txt
Q: Randomly choose a number in a specific range with a specific multiple in python I have the following numbers: 100, 200, 300, 400 ... 20000 And I would like to pick a random number within that range. Again, that range is defined as 100:100:20000. Furthermore, by saying 'within that range', I don't mean randomly pic...
Randomly choose a number in a specific range with a specific multiple in python
I have the following numbers: 100, 200, 300, 400 ... 20000 And I would like to pick a random number within that range. Again, that range is defined as 100:100:20000. Furthermore, by saying 'within that range', I don't mean randomly picking a number from 100->20000, such as 105. I mean randomly choosing a number from th...
[ "Use random.randrange :\nrandom.randrange(100, 20001, 100)\n\n", "For Python 3:\nimport random\n\nrandom.choice(range(100, 20100, 100))\n\n", "from python manual:\n\nrandom.randrange([start], stop[, step])\nReturn a randomly selected element from range(start, stop, step). This\nis equivalent to choice(range(sta...
[ 21, 6, 2, 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0007420720_python_random.txt
Q: Python mechanize ignores form input in the HTML Got my little mechanize code: br.open('http://tumblr.com/customize'); print br.response().read() print br.form['edit_tumblelog[cname]'] # there definitely is edit_tumblelog # and br.form['edit_tumblelog[enable_cname]'] works f...
Python mechanize ignores form input in the HTML
Got my little mechanize code: br.open('http://tumblr.com/customize'); print br.response().read() print br.form['edit_tumblelog[cname]'] # there definitely is edit_tumblelog # and br.form['edit_tumblelog[enable_cname]'] works fine Output: ... <br/> ...
[ "Found the problem. It's a bug in Mechanize HTML parser that somehow ignores next tag after an occurence of <br/> note that <br /> works fine. My solution was to manually replace those:\nresponse = br.response()\nresponse.set_data(response.get_data().replace(\"<br/>\", \"<br />\")) #Python mechanize is broken, fixi...
[ 8, 6 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0002394420_mechanize_python.txt
Q: How to use cherrypy test harness for my own application? I can find the way to call the test harness, but I can't figure out how to write a simple test case. Thanks. A: Alright I got a simple test case working, but since we are using a non-standard routing method I discovered that I had to reinitialize the glob...
How to use cherrypy test harness for my own application?
I can find the way to call the test harness, but I can't figure out how to write a simple test case. Thanks.
[ "Alright I got a simple test case working, but since we are using a non-standard routing method I discovered that I had to reinitialize the global cherrypy configuration explicitly for each test case (after the testharness reinitializes it incorrectly). Here it is:\n\"\"\"\ntest that the test harness is working.\n...
[ 0 ]
[]
[]
[ "cherrypy", "python", "testing" ]
stackoverflow_0007417701_cherrypy_python_testing.txt
Q: Django Asynchronous Processing I have a bunch of Django requests which executes some mathematical computations ( written in C and executed via a Cython module ) which may take an indeterminate amount ( on the order of 1 second ) of time to execute. Also the requests don't need to access the database and are all in...
Django Asynchronous Processing
I have a bunch of Django requests which executes some mathematical computations ( written in C and executed via a Cython module ) which may take an indeterminate amount ( on the order of 1 second ) of time to execute. Also the requests don't need to access the database and are all independent of each other and Django. ...
[ "Celery would be perfect for this.\nSince what you're doing is relatively simple (read: you don't need complex rules about how tasks should be routed), you could probably get away with using the Redis backend, which means you don't need to setup/configure RabbitMQ (which, in my experience, is more difficult).\nI us...
[ 14, 0 ]
[]
[]
[ "asynchronous", "celery", "cython", "django", "python" ]
stackoverflow_0004535540_asynchronous_celery_cython_django_python.txt
Q: Nested regular expression replacement in python I'm migrating SQL from one platform to another. The SQL contains DECODE statements, which are not supported by my target platform. I'm using regular expressions to translate the decode statements to case statements but I'm failing at nested decodes: import re sql_fra...
Nested regular expression replacement in python
I'm migrating SQL from one platform to another. The SQL contains DECODE statements, which are not supported by my target platform. I'm using regular expressions to translate the decode statements to case statements but I'm failing at nested decodes: import re sql_frag = "select decode(dim1,'','-',dim1) as myfield1, dec...
[ "\nIs there a way to process the innermost decode before the others so that I can cleanly replace all of the decode statements with case statements?\n\nYes.\nUse ((?![^)]*decode).*?) in place of any (.*?) where a nested DECODE can legally occur. Run the regex in a loop.\nBe aware that this can fail if there are str...
[ 1 ]
[]
[]
[ "parsing", "python", "regex", "sql", "string" ]
stackoverflow_0007421068_parsing_python_regex_sql_string.txt
Q: Python C Extension passing arguments by reference I am trying to write a python C wrapper for a function (libFunc) whose prototype is libFunc(char**, int*, char*, int) How do I use PyArg_ParseTuple for setting up the arguments for function call. Here is what I currently have #include <Python.h> PyObject* lib...
Python C Extension passing arguments by reference
I am trying to write a python C wrapper for a function (libFunc) whose prototype is libFunc(char**, int*, char*, int) How do I use PyArg_ParseTuple for setting up the arguments for function call. Here is what I currently have #include <Python.h> PyObject* libFunc_py(PyObject* self, PyObject* args) { c...
[ "I ended up doing it this way\n#include <Python.h>\n\n PyObject* libFunc_py(PyObject* self, PyObject* args)\n {\n char* input;\n char* output;\n int inputlen;\n int outputlen;\n\n PyArg_ParseTuple(args, \"s#\" , &input, &inputlen);\n\n\n int ret = libFunc(&output, &ou...
[ 0 ]
[]
[]
[ "python", "python_c_extension" ]
stackoverflow_0007411151_python_python_c_extension.txt
Q: Performing session management in python I have created an application in python. And I am using extjs for the front-end. Once a valid user logs in, I want to use the username of the logged in user for further transactions. I wanted urgent help on how session management is to be done in python. Thanks in advance. ...
Performing session management in python
I have created an application in python. And I am using extjs for the front-end. Once a valid user logs in, I want to use the username of the logged in user for further transactions. I wanted urgent help on how session management is to be done in python. Thanks in advance.
[ "You don't do \"session management in Python\". You do \"session management in a framework, which may be implemented in Python\".\nA session can be implemented in many ways, but normally is implemented via Cookies. For example, Django (a Python framework), writes a cookie with a value called session containing a gi...
[ 2, 1 ]
[]
[]
[ "extjs", "python", "session" ]
stackoverflow_0007420907_extjs_python_session.txt
Q: BeautifulSoup python to parse html files I am using BeautifulSoup to replace all the commas in an html file with &sbquo;. Here is my code for that: f = open(sys.argv[1],"r") data = f.read() soup = BeautifulSoup(data) comma = re.compile(',') for t in soup.findAll(text=comma): t.replaceWith(t.replace(','...
BeautifulSoup python to parse html files
I am using BeautifulSoup to replace all the commas in an html file with &sbquo;. Here is my code for that: f = open(sys.argv[1],"r") data = f.read() soup = BeautifulSoup(data) comma = re.compile(',') for t in soup.findAll(text=comma): t.replaceWith(t.replace(',', '&sbquo;')) This code works except when th...
[ "soup.findall can take a callable:\ntags_to_skip = set([\"script\", \"style\"])\n# Add to this list as needed\n\ndef valid_tags(tag):\n \"\"\"Filter tags on the basis of their tag names\n\n If the tag name is found in ``tags_to_skip`` then\n the tag is dropped. Otherwise, it is kept.\n \"\"\"\n if t...
[ 5 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007421565_beautifulsoup_python.txt
Q: interact with special combobox using selenium webdriver I'm using selenium2 webdriver with firefox. Usually, when there is a combobox for e.g. months I set a distinct month by send_keys(monthname). I have a special listbox this time, where I can't simply send_keys() to it (not with webdriver nor manually). I'm not...
interact with special combobox using selenium webdriver
I'm using selenium2 webdriver with firefox. Usually, when there is a combobox for e.g. months I set a distinct month by send_keys(monthname). I have a special listbox this time, where I can't simply send_keys() to it (not with webdriver nor manually). I'm not a web developer, so I have no idea what the actual differenc...
[ "Do a click on the option element you want selected.\n" ]
[ 1 ]
[]
[]
[ "listbox", "python", "selenium" ]
stackoverflow_0007420395_listbox_python_selenium.txt
Q: Attempting to set a stringproperty to default of a md5 of another part of model What I am trying to do is on the fly when storing an image to the datastore, I would like to fill in a entry with the md5sum of the image for use later when outputting the image. I feel like it is a dummy error that I have over looked...
Attempting to set a stringproperty to default of a md5 of another part of model
What I am trying to do is on the fly when storing an image to the datastore, I would like to fill in a entry with the md5sum of the image for use later when outputting the image. I feel like it is a dummy error that I have over looked and just cant see right now. Code snippet: import hashlib from google.appengine.api...
[ "Defaults don't work that way. You need a DerivedProperty:\n@DerivedProperty\ndef etag(self):\n return hashlib.md5(self.img).hexdigest()\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007420225_google_app_engine_google_cloud_datastore_python.txt
Q: django extends + jquery some problem I have a problem with my .js scripts in the site which is a child of the base.html. The scripts which are located in the base.html work, there is no problem with them, but those which are located in the "child site" don't want to work at all:p Best regards, nykon PS, the chi...
django extends + jquery some problem
I have a problem with my .js scripts in the site which is a child of the base.html. The scripts which are located in the base.html work, there is no problem with them, but those which are located in the "child site" don't want to work at all:p Best regards, nykon PS, the child page: {% extends 'index.html' %} {% bl...
[ "The script's src is incorrect. It should be an absolute path, either src=\"/media…\" or, more likely, src=\"{{ MEDIA_URL }}js/test.js\".\n" ]
[ 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0007408380_django_jquery_python.txt
Q: Python read through file until match, read until next pattern Python 2.4.3 I need to read through some files (can be as large as 10GB). What I need it to do is go through the file until it matches a pattern. Then print that line and every line after it until it matches another pattern. At that point, resume rea...
Python read through file until match, read until next pattern
Python 2.4.3 I need to read through some files (can be as large as 10GB). What I need it to do is go through the file until it matches a pattern. Then print that line and every line after it until it matches another pattern. At that point, resume reading through the file until the next pattern match. For example. f...
[ "I don't see any need to use regex here. Not that they're that bad, but if you're looking for such a specific pattern, it's just overkill to use regex. Try something like this:\ndef record(filename, pattern):\n with open(filename) as file:\n recording = False\n for line in file:\n if lin...
[ 3, 2 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0007421621_pattern_matching_python_regex.txt
Q: Python: A more concise syntax for variable assignment when accessing a NoneType object Say, I have the following Python code if obj is None: identifier = None else: identifier = obj.id where obj is a Python object whose class definition is not included I barely remember there's a more concise syntax (like a o...
Python: A more concise syntax for variable assignment when accessing a NoneType object
Say, I have the following Python code if obj is None: identifier = None else: identifier = obj.id where obj is a Python object whose class definition is not included I barely remember there's a more concise syntax (like a one-line code?) that can achieve the same. If I wasn't dreaming, can someone please advise wh...
[ "identifier = None if obj is None else obj.id\n\n", "identifier = getattr(obj, \"id\", None)\n\n", "If you use an old python version without conditional expressions, you can resort on the evaluation semantics of boolean expressions: The value of a boolean expression is the value of that term in the expression w...
[ 8, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007421706_python.txt
Q: Automatically add constants for each of the choices in a Django model I'm constantly doing the following pattern in Django: class MyModel(models.Model): FOO = 1 BAR = 2 GOO = 3 BLAH_TYPES = ( (FOO, 'Foodally boogaly'), (BAR, 'Bar bar bar bar'), (GOO, 'Goo goo gaa gaa'), ...
Automatically add constants for each of the choices in a Django model
I'm constantly doing the following pattern in Django: class MyModel(models.Model): FOO = 1 BAR = 2 GOO = 3 BLAH_TYPES = ( (FOO, 'Foodally boogaly'), (BAR, 'Bar bar bar bar'), (GOO, 'Goo goo gaa gaa'), ) TYPE_FOR_ID = dict(BLAH_TYPES) ID_FOR_TYPE = dict(zip(TYPE_FO...
[ "Carl Meyer's django-model-utils library has an excellent solution for this - the Choices class, which allows you to declare a list of choices with access via human-readable attributes.\n", "This is about the most compact way to initialize your constants:\n# foobar choices constants\nFOO, BAR, BAZ = range(3) \n\n...
[ 5, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005085794_django_django_models_python.txt
Q: Creating a function from a member of an instance for another instance in python Imagine that i have f which is a function of a member of a class instance: class A: def b(self): print 'hey' a = A() f = a.b If I have another instance of the same class, let's say c = A() how can I reconstruct a new ff o...
Creating a function from a member of an instance for another instance in python
Imagine that i have f which is a function of a member of a class instance: class A: def b(self): print 'hey' a = A() f = a.b If I have another instance of the same class, let's say c = A() how can I reconstruct a new ff only using f and c, so calling ff() would result in c.b() instead of a.b()? c = A() ff...
[ "Can you use a method reference for the class instead of the instance reference?\nclass A:\n def whoami(self):\n print 'I am %s' % id(self)\n\na = A()\nc = A()\n\nfunc = A.whoami\n\nfunc(a)\nfunc(c)\n\n", "I'm not sure this would work in all cases, but:\ndef some_python_kungfu(meth, obj):\n \"\"\"Get...
[ 4, 3, 3 ]
[]
[]
[ "class", "copy", "function", "member", "python" ]
stackoverflow_0007421089_class_copy_function_member_python.txt
Q: Python 32-bit can't find MySQLdb module on OS X Lion I've been tearing my hair out and trying the solutions to getting Python and MySQL to play nicely with 64-bit architecture, and the solution seems to have all components installed/run as 32-bit. My issue is that for some reason, running Python in 32-bit mode via...
Python 32-bit can't find MySQLdb module on OS X Lion
I've been tearing my hair out and trying the solutions to getting Python and MySQL to play nicely with 64-bit architecture, and the solution seems to have all components installed/run as 32-bit. My issue is that for some reason, running Python in 32-bit mode via $ arch -i386 /System/Library/Frameworks/Python.framework...
[ "Not exactly an answer, but have you tried just to pip install MySQL-python? If you have some mysql_config in your path, it should compile just fine.\n– I am using a Python 2.7.2 via homebrew, a MAMP 2.0 installation, running on 10.6. with a 64bit kernel.\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "osx_lion", "python" ]
stackoverflow_0007422293_mysql_mysql_python_osx_lion_python.txt
Q: PyQt4 libraries and installation on Mac OS it has been a while now I'm surfing the net trying to find the way to sucessfully install PyQt4 on different Mac OS's and I can't figure it out. Does anybody know if there is out there a package I could easily install without having to go through the compiling? I'm develo...
PyQt4 libraries and installation on Mac OS
it has been a while now I'm surfing the net trying to find the way to sucessfully install PyQt4 on different Mac OS's and I can't figure it out. Does anybody know if there is out there a package I could easily install without having to go through the compiling? I'm developing sone Python tools with PyQt guis and the id...
[ "Take a look at py2app. It will bundle up a python script as a Mac OS .app bundle. Inside of there, if configured correctly, will be the copies of the PyQt and Python modules needed to run the program.\nFor packaging for running on Windows, there's py2exe. Likewise, if configured correctly, it will handle copyin...
[ 1, 0, 0 ]
[]
[]
[ "installation", "macos", "pyqt", "python" ]
stackoverflow_0003160596_installation_macos_pyqt_python.txt
Q: python if file does not exist fails so I have a loop that checks folder if it contains *.zip file for file in glob.glob( os.path.join(rootdir, '*.zip')): print "zip", file #Check if file does not exist if not os.path.exists(file): print "No files" #return els...
python if file does not exist fails
so I have a loop that checks folder if it contains *.zip file for file in glob.glob( os.path.join(rootdir, '*.zip')): print "zip", file #Check if file does not exist if not os.path.exists(file): print "No files" #return else: some code Now if file exi...
[ "If there is no zip file in that folder, the for loop never executes.\nJust like \nfor i in []:\n print \"Hello\"\n\ndoesn't print anything because there are no elements to iterate over.\nIf you need that error message, you can do this:\nfilelist = glob.glob(os.path.join(rootdir, '*.zip'))\nif filelist:\n for...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007422353_python.txt
Q: Detecting when a new attribute is added to a object in Python? I would like to have a special obj that does the following: obj.newly_created_attribute = some_value Obviously, all objects will allow this. But I would like the previous code to automatically call a method when newly_created_attribute is not yet a at...
Detecting when a new attribute is added to a object in Python?
I would like to have a special obj that does the following: obj.newly_created_attribute = some_value Obviously, all objects will allow this. But I would like the previous code to automatically call a method when newly_created_attribute is not yet a attribute of obj. In my particular case, I wish to set up a custom get...
[ "You can accomplish this by overriding __setattr__:\nclass SomeClass(object):\n def __setattr__(self, name, value):\n if not hasattr(self, name):\n print \"new attribute\", name\n # do stuff here\n return object.__setattr__(self, name, value)\n\n", "__setattr__ will help you...
[ 6, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007422416_python.txt
Q: Parsing ODF in Python with lxml I'm trying to parse the content.xml inside a ODF-file. I've read the file into a string and i've got a tree object with lxml.etree: tree = etree.XML(string) But now I need to find every subelement that is text:a OR text:h. I've been told in previous question that I could use XPath. ...
Parsing ODF in Python with lxml
I'm trying to parse the content.xml inside a ODF-file. I've read the file into a string and i've got a tree object with lxml.etree: tree = etree.XML(string) But now I need to find every subelement that is text:a OR text:h. I've been told in previous question that I could use XPath. I've tried but got stuck every single...
[ "That's because text is a namespace abbreviation, defined in the ODF schema. Try\ntree.xpath('//text:a | //text:h',\n namespaces={'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'})\n\n| is the set union operator. See also LXML docs.\n" ]
[ 1 ]
[]
[]
[ "lxml", "odf", "python", "xml", "xpath" ]
stackoverflow_0007422603_lxml_odf_python_xml_xpath.txt
Q: python (on Windows OS) - Facebook app with Google app engine I have a problem and so confused about it. I created an application and uploaded it to Google app engine and works fine. Then i wanted to connect it to a Facebook application, so i created the Facebook application and added the Google app engine URL in t...
python (on Windows OS) - Facebook app with Google app engine
I have a problem and so confused about it. I created an application and uploaded it to Google app engine and works fine. Then i wanted to connect it to a Facebook application, so i created the Facebook application and added the Google app engine URL in the Facebook Canvas and it also works quiet well. The problem is th...
[ "The official python facebook app I know is https://github.com/facebook/runwithfriends\nIf you look through it most if not all about facebook python app is there. \n" ]
[ 0 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0007417272_facebook_google_app_engine_python.txt
Q: How do I create a project without the project folder? I'm new to pyramid and paster, just reading the docs for now. I use virtualenv and inside the virtualenv dir I want to start a pyramid project. The problem is that I would like for paster to not create a dir with the project name, and instead put all the scaffo...
How do I create a project without the project folder?
I'm new to pyramid and paster, just reading the docs for now. I use virtualenv and inside the virtualenv dir I want to start a pyramid project. The problem is that I would like for paster to not create a dir with the project name, and instead put all the scaffold files on the current dir (the venv root). I thought abou...
[ "It is confusing at first but your code really doesn't need to be in your virtual environment directory at all. Actually it's better not to put your code inside your environment, as you might want to use different environments with the same code, for example to test your code with different versions of Python or di...
[ 3, 1 ]
[]
[]
[ "paster", "pyramid", "python" ]
stackoverflow_0007421082_paster_pyramid_python.txt
Q: How can I display text over columns in a bar chart in matplotlib? I have a bar chart and I want over each column to display some text,how can I do that ? A: I believe this will point you in the right direction: http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html. The part that you are mo...
How can I display text over columns in a bar chart in matplotlib?
I have a bar chart and I want over each column to display some text,how can I do that ?
[ "I believe this will point you in the right direction:\nhttp://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html.\nThe part that you are most interested in is:\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n plt.text(rect.get_x()+rect.get_width()/2., 1...
[ 39 ]
[]
[]
[ "bar_chart", "matplotlib", "python" ]
stackoverflow_0007423445_bar_chart_matplotlib_python.txt
Q: Running separate code while a socket server is running? How can I have a socket server running that accepts incoming connections and deals with that part of the code, while not having code waiting for new connections stuck in that same loop? I am just starting trying to learn. Would a TCP Handler be useful? I jus...
Running separate code while a socket server is running?
How can I have a socket server running that accepts incoming connections and deals with that part of the code, while not having code waiting for new connections stuck in that same loop? I am just starting trying to learn. Would a TCP Handler be useful? I just need some simple examples on this topic. I'm wanting someth...
[ "You can run your socket server in a thread.\nimport threading\nimport SocketServer\n\nserver = SocketServer.TCPServer(('localhost', 0), SocketServer.BaseRequestHandler)\nth = threading.Thread(target=server.serve_forever)\nth.daemon = True\nth.start()\n\n", "I'm not exactly sure what you are asking, but normally ...
[ 2, 0, 0 ]
[]
[]
[ "python", "sockets", "tcp", "udp" ]
stackoverflow_0007421339_python_sockets_tcp_udp.txt
Q: Which regex is more efficient? s/(?P<head>\[\[foo[^\[]*)abc/\g<head>def s/(?=\[\[foo[^\[]*)abc/def Which is more efficient? Are there any other ways to make it more efficient? Please note that although I used Perl-style syntax for illustration purposes, I'm actually using Python's re library, which doesn't allow...
Which regex is more efficient?
s/(?P<head>\[\[foo[^\[]*)abc/\g<head>def s/(?=\[\[foo[^\[]*)abc/def Which is more efficient? Are there any other ways to make it more efficient? Please note that although I used Perl-style syntax for illustration purposes, I'm actually using Python's re library, which doesn't allow the \K (keep) keyword.
[ "(?P<head>\\[\\[foo[^\\[]*)abc in python using the re module is way faster:\nimport time\nimport re\n\nrec1 = re.compile('(?P<head>\\[\\[foo[^\\[]*)abc')\nrec2 = re.compile('(?=\\[\\[foo[^\\[]*)abc')\n\ntotal1, total2 = 0.0, 0.0\n\ndef timeRE(ver):\n x = (\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_12...
[ 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007423525_python_regex.txt
Q: Python List & for-each access (Find/Replace in built-in list) I originally thought Python was a pure pass-by-reference language. Coming from C/C++ I can't help but think about memory management, and it's hard to put it out of my head. So I'm trying to think of it from a Java perspective and think of everything bu...
Python List & for-each access (Find/Replace in built-in list)
I originally thought Python was a pure pass-by-reference language. Coming from C/C++ I can't help but think about memory management, and it's hard to put it out of my head. So I'm trying to think of it from a Java perspective and think of everything but primitives as a pass by reference. Problem: I have a list, contai...
[ "Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.\nAs noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable wit...
[ 49, 16, 6 ]
[]
[]
[ "foreach", "list", "python", "reference", "replace" ]
stackoverflow_0007423118_foreach_list_python_reference_replace.txt
Q: lxml.etree._ElementTree.find() can't be called on objectify.parse result >>> from lxml import objectify >>> from StringIO import StringIO >>> f = StringIO("<root>data</root>") >>> tree = objectify.parse(f) >>> type(tree) <type 'lxml.etree._ElementTree'> >>> tree.find('root') Traceback (most recent call last): Fi...
lxml.etree._ElementTree.find() can't be called on objectify.parse result
>>> from lxml import objectify >>> from StringIO import StringIO >>> f = StringIO("<root>data</root>") >>> tree = objectify.parse(f) >>> type(tree) <type 'lxml.etree._ElementTree'> >>> tree.find('root') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "lxml.etree.pyx", line 1944, in lxml....
[ "We solve this mystery by looking at the corresponding source (long live OSS):\ndef find(self, path, namespaces=None):\n u\"\"\"find(self, path, namespaces=None)\n\n Finds the first toplevel element with given tag. Same as\n ``tree.getroot().find(path)``.\n\n The optional ``namespaces`` argument accept...
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0007351188_lxml_python.txt
Q: Python RPM I built won't install Because I have to install multiple versions of Python on multiple Oracle Linux servers which are built via a kickstart process, I wanted to build a python rpm for our yum repository. I was able to build Python manually using 'make altinstall' which doesn't install over your defaul...
Python RPM I built won't install
Because I have to install multiple versions of Python on multiple Oracle Linux servers which are built via a kickstart process, I wanted to build a python rpm for our yum repository. I was able to build Python manually using 'make altinstall' which doesn't install over your default system Python installation, so I tho...
[ "You should be able to fix this issue by adding the following line to your spec file:\n\nAutoReq: no\n\n\nHere is my understanding of why this is necessary. When rpmbuild runs across .py files with a #! (shebang) it will automatically add the binary that the shebang specifies as a requirement. Not only that, if t...
[ 24, 9 ]
[]
[]
[ "python", "rpm", "rpm_spec", "rpmbuild" ]
stackoverflow_0007423300_python_rpm_rpm_spec_rpmbuild.txt
Q: Python csv writer wrong separator? Disclaimer: I'm in Europe. According to this page Excel uses the semicolon ; as default separator in Europe to "prevent conflicts" with the decimal comma. Now, I have this Python code: import csv data = [["test", "data"], ["foo", "bar"]] writer = csv.writer(open("data.csv", "wb"...
Python csv writer wrong separator?
Disclaimer: I'm in Europe. According to this page Excel uses the semicolon ; as default separator in Europe to "prevent conflicts" with the decimal comma. Now, I have this Python code: import csv data = [["test", "data"], ["foo", "bar"]] writer = csv.writer(open("data.csv", "wb"), dialect="excel") writer.writerows(dat...
[ "This is because the csv.excel dialect is not locale aware. If you wish to explicitly use semicolons as the delimiter then you need to either explicitly pass the delimiter to csv.open as\nwriter = csv.writer(open(\"data.csv\", \"wb\"), delimiter=\";\")\n\nor create a new dialect and register it\nclass excel_semico...
[ 21, 7 ]
[]
[]
[ "csv", "excel", "localization", "python" ]
stackoverflow_0007423869_csv_excel_localization_python.txt
Q: Python for Flash Player Would it be technically possible to embed Python into a Flex/AIR application by compiling CPython code using Alchemy? (I'm guessing the project should be called Flython.) A: Yes. But don't expect all the standard modules to build. Some system calls won't translate. It would be a lot of w...
Python for Flash Player
Would it be technically possible to embed Python into a Flex/AIR application by compiling CPython code using Alchemy? (I'm guessing the project should be called Flython.)
[ "Yes.\nBut don't expect all the standard modules to build. Some system calls won't translate. It would be a lot of work to port. \n" ]
[ 2 ]
[]
[]
[ "air", "apache_flex", "cpython", "flash", "python" ]
stackoverflow_0007424128_air_apache_flex_cpython_flash_python.txt
Q: printing a tuple with a tab between the values I have a text file like the one below: this000is00a00test001251!! this000is00a00test001251!! this000is00a00test001251!! this000is00a00test001251!! I have the following code to parse through it: def file_open(): my_file = open(r'C:\Users\test\Desktop\parse_me.txt'...
printing a tuple with a tab between the values
I have a text file like the one below: this000is00a00test001251!! this000is00a00test001251!! this000is00a00test001251!! this000is00a00test001251!! I have the following code to parse through it: def file_open(): my_file = open(r'C:\Users\test\Desktop\parse_me.txt','r', encoding='cp1252') return my_file def par...
[ "If you want to join a list of strings, you can use join() like so:\nlist_of_strings = ['one', 'two', 'three']\nprint \"\\t\".join(list_of_strings) #\\t is the tab character\n\nOutput:\none two three\n\nFor commas, just replace \"\\t\".join with \",\".join. Join will also work with tuples as used in your exam...
[ 13 ]
[]
[]
[ "file", "formatting", "python", "text" ]
stackoverflow_0007424325_file_formatting_python_text.txt
Q: How to encrypt using public key? msg = "this is msg to encrypt" pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file. encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding) Now I am trying to give file containing radix64 format public key as a parameter in this method ...
How to encrypt using public key?
msg = "this is msg to encrypt" pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file. encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding) Now I am trying to give file containing radix64 format public key as a parameter in this method and unable to get expected result i.e ...
[ "In case someone searches for this question, I was getting the same error message: \nM2Crypto.RSA.RSAError: no start line\n\nIn my case, it turned out that my keys were of type unicode. This was solved by converting the key back to ascii:\nkey.encode('ascii')\n\n", "Did you ask this question before? See my answe...
[ 6, 1, 0 ]
[]
[]
[ "encoding", "encryption", "python" ]
stackoverflow_0001455782_encoding_encryption_python.txt
Q: Parsing responses of content-type chunked in python I'm trying to read and parse a request of content-type: chunked in python. Here is what I see when I load the url in a browser and look at the source: <!-- ---------------------------------------------------------------- http://github.com/Atmosphere -------------...
Parsing responses of content-type chunked in python
I'm trying to read and parse a request of content-type: chunked in python. Here is what I see when I load the url in a browser and look at the source: <!-- ---------------------------------------------------------------- http://github.com/Atmosphere ----------------------------------------------------------------------...
[ "\"chunked\" is not a valid content-type, although it is a valid transfer-encoding. Based on the sample you've posted, that doesn't really look like your problem. This looks like a header applied to a regular jsonp response. In many cases, the sgml comments would be ignored by a browser, but you'll have to extra...
[ 1 ]
[]
[]
[ "atmosphere", "chunked", "http_1.1", "python", "stream" ]
stackoverflow_0007424423_atmosphere_chunked_http_1.1_python_stream.txt
Q: Can't submit web form using urllib2 in python I am trying to submit the form at http://www.harshtechtalk.com/contact-us-harsh-tech-talk using the following code but no success. Please help! #!C:/Python27/python.exe import urllib import urllib2 def main(): proxy_info={ 'user' : 'ab...
Can't submit web form using urllib2 in python
I am trying to submit the form at http://www.harshtechtalk.com/contact-us-harsh-tech-talk using the following code but no success. Please help! #!C:/Python27/python.exe import urllib import urllib2 def main(): proxy_info={ 'user' : 'abc@abc.com', 'pass' : 'xyz',...
[ "Handling AJAX web forms generally requires using selenium so that Python is driving a real web browser with a JavaScript engine installed. Some people also talk about phantomjs but I am not aware of an official Python module for it at this point. See also:\nHeadless, scriptable Firefox/Webkit on linux?\n" ]
[ 0 ]
[]
[]
[ "forms", "python", "urllib2" ]
stackoverflow_0007424048_forms_python_urllib2.txt
Q: Best way in Python to combine 2 lists and return a min / max of a set I currently have two set lists that combine "steps" and "time": step = 1,1,1,1,2,2,2,2 time = 1,2,5,6,1,3,5,6 These values directly correlate, meaning a tuple looking like [(1,1),(1,2),(1,5),(1,6),(2,1),(2,3),(2,5),(2,11)] Basically I'm trying ...
Best way in Python to combine 2 lists and return a min / max of a set
I currently have two set lists that combine "steps" and "time": step = 1,1,1,1,2,2,2,2 time = 1,2,5,6,1,3,5,6 These values directly correlate, meaning a tuple looking like [(1,1),(1,2),(1,5),(1,6),(2,1),(2,3),(2,5),(2,11)] Basically I'm trying to find the max value for step 1, and the min value of step one, as well as...
[ "You're looking for itertools.groupby. Here is some example code for your question:\nstep = 1,1,1,1,2,2,2,2\ntime = 1,2,5,6,1,3,5,6\n\nfrom itertools import groupby, izip\nfrom operator import itemgetter\n\nfor key, group in groupby(izip(step, time), itemgetter(0)):\n group = [item[1] for item in group]\n pri...
[ 2, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0007424537_list_python_tuples.txt
Q: setSelected in QTreeWidget I have a project where I need to change the selection of a tree widget in code. This needs to be done after I clear out the tree and populate it again. I'm trying to mark the appropriate item as "selected" while I'm adding them. This works for root level nodes. But for child nodes, it do...
setSelected in QTreeWidget
I have a project where I need to change the selection of a tree widget in code. This needs to be done after I clear out the tree and populate it again. I'm trying to mark the appropriate item as "selected" while I'm adding them. This works for root level nodes. But for child nodes, it doesn't. I need to store the QTree...
[ "It is not specified in the documentation, but setSelected does nothing if the item hasn't been added to a view yet:\ninline void QTreeWidgetItem::setSelected(bool aselect)\n{ if (view) view->setItemSelected(this, aselect); }\n\nSo, you should either \n\npass treeObj or temp in the constructor of your QTreeWidgetIt...
[ 2 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0007420103_pyqt4_python_qt.txt
Q: How to test server behavior under network loss at every possible packet I'm working with mobile, so I expect network loss to be common. I'm doing payments, so each request matters. I would like to be able to test my server to see precisely how it will behave with client network loss at different points in the requ...
How to test server behavior under network loss at every possible packet
I'm working with mobile, so I expect network loss to be common. I'm doing payments, so each request matters. I would like to be able to test my server to see precisely how it will behave with client network loss at different points in the request cycle -- specifically between any given packet send/receive during the en...
[ "Unless your application is actually responding to and generating its own IP packets (which would be incredibly silly), you probably don't need to do testing at that layer. Simply testing at the TCP layer (e.g, connect(), send(), recv(), shutdown()) will probably be sufficient, as those events are the only ones whi...
[ 2 ]
[]
[]
[ "http", "network_programming", "python", "scapy", "tcp" ]
stackoverflow_0007424349_http_network_programming_python_scapy_tcp.txt
Q: Can pydev refactor a function call so that named arguments are used? For example: def f(foo, bar): return foo + bar answer = f(3,4) What I'm looking for is some way to highlight the function call in pydev and have it automatically refactored so that it reads: answer = f(foo=3, bar=4) A: That's not currently p...
Can pydev refactor a function call so that named arguments are used?
For example: def f(foo, bar): return foo + bar answer = f(3,4) What I'm looking for is some way to highlight the function call in pydev and have it automatically refactored so that it reads: answer = f(foo=3, bar=4)
[ "That's not currently possible. Please enter that as a feature request in the PyDev sf tracker. See: http://pydev.org/about.html for links.\n" ]
[ 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0004174729_eclipse_pydev_python.txt
Q: Controlling socket timeouts in external libraries I'm in the process of re-working my personal site and I've run into a bit of a snag that I'm hoping there's a clean workaround for: I'm using a variety of OS packages to communicate with StackExchange (multiple sites) and Twitter (just for my feed). To speed things...
Controlling socket timeouts in external libraries
I'm in the process of re-working my personal site and I've run into a bit of a snag that I'm hoping there's a clean workaround for: I'm using a variety of OS packages to communicate with StackExchange (multiple sites) and Twitter (just for my feed). To speed things up when refreshing my beaker-driven cache, I've multi-...
[ "Are you looking for \nsocket.setdefaulttimeout\n\n" ]
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0007424666_python_urllib2.txt
Q: Web2Py - Upload a file and read the content as Zip file I am trying to upload a zip file from Web2Py form and then read the contents: form = FORM(TABLE( TR(TD('Upload File:', INPUT(_type='file', _name='myfile', id='myfile'...
Web2Py - Upload a file and read the content as Zip file
I am trying to upload a zip file from Web2Py form and then read the contents: form = FORM(TABLE( TR(TD('Upload File:', INPUT(_type='file', _name='myfile', id='myfile', requires=IS_NOT_EMP...
[ "web2py form field uploads already are cgi.FieldStorage, you can get the raw uploaded bytes using:\ndata = request.vars.myfile.value\n\nFor a file-like object StringIO is not needed, use:\nfilelike = request.vars.myfile.file\nzip = zipfile.Zipfile(filelike)\n\n", "HTTP uploads aren't just raw binary, it's mixed-m...
[ 6, 3 ]
[]
[]
[ "python", "web2py", "zip" ]
stackoverflow_0006407558_python_web2py_zip.txt
Q: Can't find file with os.walk() I've created a file called program1.py in my /home/n00b directory. I then opened python and I wanted to see if I could write a script to find it's location. I did this: for f in os.walk('/home/n00b'): print 'searching', f if 'program1.py' in f: print 'found' ...
Can't find file with os.walk()
I've created a file called program1.py in my /home/n00b directory. I then opened python and I wanted to see if I could write a script to find it's location. I did this: for f in os.walk('/home/n00b'): print 'searching', f if 'program1.py' in f: print 'found' break Why isn't this working? ...
[ "It isn't working because os.walk returns a 3-tuple: current directory, list of directory names here, and list of filenames here:\nfor curdir, dirs, files in os.walk('/home/n00b'):\n print 'searching', files\n if 'program1.py' in files:\n print 'found'\n break\n\nYour print statement shoul...
[ 5, 0, 0 ]
[]
[]
[ "file", "os.walk", "python", "search" ]
stackoverflow_0007424948_file_os.walk_python_search.txt
Q: Can someone please recommend me a good PyQt/PySide tutorial/book/video series? ... or is Rapid GUI Development with PyQT everything that I'll ever need? I went through some online and most of them are really outdated, most of the code does not work, or they are written terribly in general. A: I liked the tutoria...
Can someone please recommend me a good PyQt/PySide tutorial/book/video series?
... or is Rapid GUI Development with PyQT everything that I'll ever need? I went through some online and most of them are really outdated, most of the code does not work, or they are written terribly in general.
[ "I liked the tutorial, \"PyQt by example,\" available at this address: http://lateral.netmanagers.com.ar/stories/BBS47.html. However, it may well be dated now. It does the somewhat overplayed \"todo list\" app, but nonetheless, it was clear and illustrated things well. It also provided a reasonable introduction ...
[ 8 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007424957_pyqt_python.txt
Q: Linux/Unix Server: Access SQL database that is in different directory than executing script I have a python script that executes a SQL query & gets information from a SQLite3 database file. The SQLite3 database file resides in a different directory than that of the executing script. All this occurs on my webhost(U...
Linux/Unix Server: Access SQL database that is in different directory than executing script
I have a python script that executes a SQL query & gets information from a SQLite3 database file. The SQLite3 database file resides in a different directory than that of the executing script. All this occurs on my webhost(Unix server cpanel) from within the cgi-bin directory. My Question/Problem: Is it possible to have...
[ "With the database I use (firebird) you have to specify the full path to the database from the root on the server\nSo \"/var/folder/wwww/db/dbfile.db\" for example, with /var being in the root folder of coarse\nJust saying where it is FROM the website \"db/dbfile.db\" wont work (for firebird at least)\nThis also al...
[ 0 ]
[]
[]
[ "python", "sql", "webserver" ]
stackoverflow_0007424771_python_sql_webserver.txt
Q: I can't get PyDev - PYTHONPATH to recognize my Java src directory in Eclipse In the Project Properties > PyDev - PYTHONPATH > Source Folders tab I have my Java source directory listed. However, when I try to run my Python file using right-click > Run As > Jython Run, I get "ImportError: cannot import name Person"....
I can't get PyDev - PYTHONPATH to recognize my Java src directory in Eclipse
In the Project Properties > PyDev - PYTHONPATH > Source Folders tab I have my Java source directory listed. However, when I try to run my Python file using right-click > Run As > Jython Run, I get "ImportError: cannot import name Person". This is a very simple Python script: from com.entities import Person person = Pe...
[ "Actually, it depends on how you structure your java code... you have to add as a source folder the folder that has your .class files (as that's the folder that's added to your pythonpath -- so, depending on how you structure your project, that may be your 'bin' folder).\nReference: read the last lines in: http://p...
[ 1 ]
[]
[]
[ "eclipse", "java", "jython", "python" ]
stackoverflow_0007422665_eclipse_java_jython_python.txt
Q: What is the maximum length of a character function argument in jython? What is the maximum length of a character function argument in python/jython? I've reviewed the documentation on python.org and no luck A: Python passes function arguments by reference, so the maximum length of a string passed to a function i...
What is the maximum length of a character function argument in jython?
What is the maximum length of a character function argument in python/jython? I've reviewed the documentation on python.org and no luck
[ "Python passes function arguments by reference, so the maximum length of a string passed to a function is purely dependent on the maximum length of a string.\nIt so happens that the maximum length of a string is platform dependent (Address space and/or RAM, generally) - see the question What is the max length of a ...
[ 3 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0007424761_jython_python.txt
Q: Add property to one of the form fields in django I am trying to add a special template property to one of the form fields which I will than use to render the form in template tag. Here is the code: form = ProfileForm() for field in form: if field.name == 'email': field.template = 'email_field.html' ...
Add property to one of the form fields in django
I am trying to add a special template property to one of the form fields which I will than use to render the form in template tag. Here is the code: form = ProfileForm() for field in form: if field.name == 'email': field.template = 'email_field.html' This way, original form variable is not modified. Is ...
[ "I'm going to assume you might want to build a html5 email field:\nfrom django import forms\nfrom django.forms.widgets import Widget\nfrom django.utils.safestring import mark_safe\n\n\nclass Html5Email(Widget):\n\n def render(self, name, value, attrs=None):\n return mark_safe(u'<input name=\"custom-email\...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007422389_django_python.txt
Q: Python recursion to print items from a list backwards Using Python, I'm trying to read a list or strings backwards. When finding the item of interest, I want to print all of those items from that point to the end of the list. I can do this without recursion and it works fine, but I feel like there's a nicer way ...
Python recursion to print items from a list backwards
Using Python, I'm trying to read a list or strings backwards. When finding the item of interest, I want to print all of those items from that point to the end of the list. I can do this without recursion and it works fine, but I feel like there's a nicer way to do this with recursion. :) Example without recursion: i...
[ "Recursion wouldn't make this simpler, it would make it more complicated.\nfor i, item in enumerate(reversed(items), 1):\n if item == 'item3':\n items_of_interest = items[-i:]\n break\nelse:\n # 'item3' wasn't found\n\nseems to be the simplest efficient way to do this to me. You only have to ite...
[ 5, 1 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0007425297_list_python_recursion.txt
Q: How to get sat and sun dates from given date ranges in python How to get saturday and sunday dates from given date range. for example : start_date = 2011-09-01 end_date = 2011-09-15 Now it should give the out put 2011-09-03 2011-09-04 2011-09-10 2011-09-11 Any help really appreciate. A: >>> import dateti...
How to get sat and sun dates from given date ranges in python
How to get saturday and sunday dates from given date range. for example : start_date = 2011-09-01 end_date = 2011-09-15 Now it should give the out put 2011-09-03 2011-09-04 2011-09-10 2011-09-11 Any help really appreciate.
[ ">>> import datetime\n>>> start = datetime.datetime.strptime(\"2011-09-01\", \"%Y-%m-%d\")\n>>> end = datetime.datetime.strptime(\"2011-09-15\", \"%Y-%m-%d\")\n>>> while start <= end:\n... if start.weekday() in (5, 6):\n... print start.strftime(\"%Y-%m-%d\")\n... start += datetime.timedelta(days=1)\...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007425552_python.txt
Q: alternative to oauth2 (Python module) on GAE? From my app running on GAE, I want to be able to post tweets periodically. I've a code with which I am able to post tweets from localhost. import urllib import urllib2 import simplejson as json import oauth2 as oauth consumer_key = "" consumer_key_secret = "" oauth_t...
alternative to oauth2 (Python module) on GAE?
From my app running on GAE, I want to be able to post tweets periodically. I've a code with which I am able to post tweets from localhost. import urllib import urllib2 import simplejson as json import oauth2 as oauth consumer_key = "" consumer_key_secret = "" oauth_token = "" oauth_token_secret = "" consumer = oauth...
[ "oauth2 is a pure-python module; it should run fine on App Engine - just bundle it with your app.\n", "You can check for this exmpale. Need to upload oauth2 folder along with your source.\n" ]
[ 1, 0 ]
[]
[]
[ "google_app_engine", "oauth_2.0", "python", "twitter", "twitter_oauth" ]
stackoverflow_0007418790_google_app_engine_oauth_2.0_python_twitter_twitter_oauth.txt
Q: QLabel.setText() not working? I have been trying to get QLabel.setText in PySide working for several days, but no succes. I have following code(simplified): def GUI(self): self.data1=QtGui.QLabel() self.data2=QtGui.QLCDNumber() self.lcdTimer=QtGui.QLCDNumber() def tick(time, self): self.lcdTimer.d...
QLabel.setText() not working?
I have been trying to get QLabel.setText in PySide working for several days, but no succes. I have following code(simplified): def GUI(self): self.data1=QtGui.QLabel() self.data2=QtGui.QLCDNumber() self.lcdTimer=QtGui.QLCDNumber() def tick(time, self): self.lcdTimer.display(timetodisplay) ## this one ...
[ "Get it working. Problem was that I had also other objects(ImageQt) a few hundreds lines later with names self.data1 and self.data2. def tick(time, self): was actually def tick(self, time):in my code.\n" ]
[ 0 ]
[]
[]
[ "pyqt", "pyqt4", "pyside", "python" ]
stackoverflow_0007416598_pyqt_pyqt4_pyside_python.txt
Q: Write a Python method to generate typos based on a string I could just add in something that creates typos based on Levenshtein distance of two, or something like that, or reverse-engineer Norvig's article on spellchecking. However, what are the most common ways to typos? Has somebody written a method? A: Th...
Write a Python method to generate typos based on a string
I could just add in something that creates typos based on Levenshtein distance of two, or something like that, or reverse-engineer Norvig's article on spellchecking. However, what are the most common ways to typos? Has somebody written a method?
[ "There's no such thing as general typo generation algorithm because this kind of algorithm depends on the target language and application - ie to generate spam domains you basically need to apply following strategies (using meta.stackoverflow.com as an example):\n\nmissing dots: met*as*tackoverflow.com (should be e...
[ 2 ]
[]
[]
[ "levenshtein_distance", "python" ]
stackoverflow_0007425025_levenshtein_distance_python.txt
Q: Forcing Django to use 32-bit Python I finally resolved the ubiquitous MySQL-python/OSX (10.7 64-bit) debacle and have Python and MySQL working fine by using 32-bit MySQL and calling python with 'arch -i386'. Py scripts outside of Django are correctly querying MySQL etc. However, when I try to fire up Django and ...
Forcing Django to use 32-bit Python
I finally resolved the ubiquitous MySQL-python/OSX (10.7 64-bit) debacle and have Python and MySQL working fine by using 32-bit MySQL and calling python with 'arch -i386'. Py scripts outside of Django are correctly querying MySQL etc. However, when I try to fire up Django and invoke the development server, I'm gettin...
[ "The VERSIONER_PYTHON_PREFER_32_BIT environment variable is an Apple-supplied feature. It only applies to the Apple-supplied system Pythons in Mac OS X 10.6 and 10.7. From the path shown, you are using a non-system Python (installed in /Library/Frameworks, possibly from a python.org installer). VERSIONER_PYTHON...
[ 1, 0 ]
[]
[]
[ "django", "macos", "mysql", "osx_lion", "python" ]
stackoverflow_0007423846_django_macos_mysql_osx_lion_python.txt