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: Parse a map of int -> list from a string This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right. Let's say I have a string: "1:a,b,c::2:e,f,g::3:h,i,j" and I want to convert this to a map like so: {'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']} ...
Parse a map of int -> list from a string
This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right. Let's say I have a string: "1:a,b,c::2:e,f,g::3:h,i,j" and I want to convert this to a map like so: {'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']} How would this be done? I can figure out how ...
[ "Here's one approach:\ndict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0003918797_python.txt
Q: How to make sure a file exists or can be created before writing to it in Python? I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that? A: Just open the file for writing and it will be created if it doesn't exist ...
How to make sure a file exists or can be created before writing to it in Python?
I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
[ "Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).\nf = open('some_file_that_might_not_exist.txt', 'w')\nf.write(data)\n\nYou will get an IOError if you can't open the file for writing.\n", "Per the docs, os.utime() will func...
[ 12, 7, 0 ]
[]
[]
[ "file_io", "filesystems", "python" ]
stackoverflow_0003918433_file_io_filesystems_python.txt
Q: How can I put only value after decimal I have got output and I want to use only three values after decimal. How can i do that in Python? A: Use the following: "%.3f" % x it converts your number to a string with three decimal places. A: In Python 2.6 or newer you should use the str.format method: >>> x = 15.23...
How can I put only value after decimal
I have got output and I want to use only three values after decimal. How can i do that in Python?
[ "Use the following:\n\"%.3f\" % x\n\nit converts your number to a string with three decimal places.\n", "In Python 2.6 or newer you should use the str.format method:\n>>> x = 15.23432\n>>> '{0:.3f}'.format(x)\n'15.234'\n\n", "round(number, 3)\nhttp://docs.python.org/tutorial/floatingpoint.html\n" ]
[ 4, 4, 3 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0003918878_floating_point_python.txt
Q: Object vs. class variable This is a completely theoretical question. Suppose the following code: >>> class C: ... a = 10 ... def f(self): self.a = 999 ... >>> >>> C.a 10 >>> c = C() >>> c.a 10 >>> c.f() >>> c.a 999 At this point, is class variable C.a still accessible through the object c? A: Yes, thoug...
Object vs. class variable
This is a completely theoretical question. Suppose the following code: >>> class C: ... a = 10 ... def f(self): self.a = 999 ... >>> >>> C.a 10 >>> c = C() >>> c.a 10 >>> c.f() >>> c.a 999 At this point, is class variable C.a still accessible through the object c?
[ "Yes, though c.__class__.a or type(c).a. The two differ slightly in that old-style classes (hopefully, those are all dead by now - but you never know...) have a type() of <type 'instance'> (and __class__ works as expected) while for new-style classes, type() is identical to __class__ except when the object override...
[ 4, 1, 1, 1 ]
[]
[]
[ "python", "syntax", "theory" ]
stackoverflow_0003918761_python_syntax_theory.txt
Q: Writing empty string to textfile in Python Quite embarassing issue, though i come from web development and rarely have to deal with files i/o. I wrote a simple config updater for use on my shared hosting. It scans the directory for subdirectories, and then writes config lines to a file - one line for each subdirec...
Writing empty string to textfile in Python
Quite embarassing issue, though i come from web development and rarely have to deal with files i/o. I wrote a simple config updater for use on my shared hosting. It scans the directory for subdirectories, and then writes config lines to a file - one line for each subdirectory. The problem is, when it detects there are ...
[ "You're using the r+ read-write mode. All reads and all writes update the file's position.\nTry:\nfile = open('path', 'r+')\nconfig = file.read()\n## all the code inbetween works fine\n## config is .split()-ed, hence the list\nif config == ['']:\n config = ''\nfile.seek(0) # rewind the file\nfile.write(config...
[ 3, 2, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003919382_file_io_python.txt
Q: How do I plot multiple X or Y axes in matplotlib? I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left im...
How do I plot multiple X or Y axes in matplotlib?
I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data...
[ "First off, cool question! It's definitely possible with matplotlib >= 1.0.0. (The new spines functionality allows it) \nIt requires a fair bit of voodoo, though... My example is far from perfect, but hopefully it makes some sense:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\...
[ 21, 10 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003918028_matplotlib_python.txt
Q: how to add python to system dependency on win7? i've got a problem when i'm doing dev I managed to use python manage.py runserver in a CMD shell but the system cant find python How could I add python to the system dependency to make the commandline work? A: There are two basic ways you can do this in Windows. S...
how to add python to system dependency on win7?
i've got a problem when i'm doing dev I managed to use python manage.py runserver in a CMD shell but the system cant find python How could I add python to the system dependency to make the commandline work?
[ "There are two basic ways you can do this in Windows. \nSetting the PATH in the cmd shell\nThe first way is only local to the CMD shell you are currently in, and will have to be done again if you opened a new shell.\nYou can set your PATH to include the directory where python.exe is located.\nIn your CMD shell you ...
[ 2 ]
[]
[]
[ "django", "installation", "python" ]
stackoverflow_0003920151_django_installation_python.txt
Q: python number guessing question import sys print 'Content-Type: text/html' print '' print '<pre>' # Read the form input which is a single line guess = -1 data = sys.stdin.read() # print data if data == []: print "Welcome to Josh's number game" try: guess = int(data[data.find('=')+1:]) except: gue...
python number guessing question
import sys print 'Content-Type: text/html' print '' print '<pre>' # Read the form input which is a single line guess = -1 data = sys.stdin.read() # print data if data == []: print "Welcome to Josh's number game" try: guess = int(data[data.find('=')+1:]) except: guess = -1 print 'Your guess is', guess...
[ "data is a string and will never equal [], which is a list. Try data.strip() == \"\".\nEDIT: It just occurred to me that you probably meant to use sys.stdin.readlines(), which does return a list. But instead of \"fixing\" this, I strongly recommend you follow @Zack's advice regarding CGI.\n", "sys.stdin.read() wi...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003920155_python.txt
Q: will yum break if I use rpms from the ius community project? I followed this tutorial: http://blog.boxedice.com/2010/01/19/updating-python-on-rhelcentos/ because I wanted to install python2.6 on a CentOS 5.5 machine without breaking yum. And i was successfully able install python2.6. My question is that after comp...
will yum break if I use rpms from the ius community project?
I followed this tutorial: http://blog.boxedice.com/2010/01/19/updating-python-on-rhelcentos/ because I wanted to install python2.6 on a CentOS 5.5 machine without breaking yum. And i was successfully able install python2.6. My question is that after completing the above commands the next time I try installing packages ...
[ "I am the primary maintainer of the IUS Community Project. This question would be better asked via the 'answers' section of our project page on http://launchpad.net/ius. \nRegardless, I am more than happy to clarify for you. IUS provides packages that strictly conflict with packages in RHEL... meaning if the ori...
[ 4, 1 ]
[]
[]
[ "centos5", "linux", "python", "rhel", "rpm" ]
stackoverflow_0003916603_centos5_linux_python_rhel_rpm.txt
Q: Python: How to loop through blocks of lines How to go through blocks of lines separated by an empty line? The file looks like the following: ID: 1 Name: X FamilyN: Y Age: 20 ID: 2 Name: H FamilyN: F Age: 23 ID: 3 Name: S FamilyN: Y Age: 13 ID: 4 Name: M FamilyN: Z Age: 25 I want to loop through the blocks and ...
Python: How to loop through blocks of lines
How to go through blocks of lines separated by an empty line? The file looks like the following: ID: 1 Name: X FamilyN: Y Age: 20 ID: 2 Name: H FamilyN: F Age: 23 ID: 3 Name: S FamilyN: Y Age: 13 ID: 4 Name: M FamilyN: Z Age: 25 I want to loop through the blocks and grab the fields Name, Family name and Age in a li...
[ "Here's another way, using itertools.groupby.\nThe function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False ...
[ 12, 5, 4, 2, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0003914454_python_text_processing.txt
Q: Picking out symbols from a code base with Python Given a code base (say for example a large C or Objective-C project) I would like to analyze the sourcecode files and pick out symbols of interest. They might be class declarations, variable names or types, or method names. Is there a Python module that could help...
Picking out symbols from a code base with Python
Given a code base (say for example a large C or Objective-C project) I would like to analyze the sourcecode files and pick out symbols of interest. They might be class declarations, variable names or types, or method names. Is there a Python module that could help me with this? The only approach I can see going forwa...
[ "Regex is definitely not a good way to examine programming language code. I would suggest choosing a parsing module from the links provided below.\nThere are a few tools out there that you could use. They all provide parsing facility. You can always build your stuff on top of that:\n\nhttp://code.google.com/p/pycpa...
[ 5, 1, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003919922_parsing_python.txt
Q: Running mysqldump through Python's subprocess module is slow and verbose @cost_time def dbdump_all(): "导出数据库所有数据至当前目录下以年月日命名的sql文件" filename=datetime.datetime.now().strftime("%Y-%m-%d") cmd="""mysqldump -u root -pzhoubt --opt --quick --database search > ./%s.sql"""%filename args=shlex.split(cmd) ...
Running mysqldump through Python's subprocess module is slow and verbose
@cost_time def dbdump_all(): "导出数据库所有数据至当前目录下以年月日命名的sql文件" filename=datetime.datetime.now().strftime("%Y-%m-%d") cmd="""mysqldump -u root -pzhoubt --opt --quick --database search > ./%s.sql"""%filename args=shlex.split(cmd) p=subprocess.Popen(args) #stdout, stderr = p.communicate() #print st...
[ "@cost_time\ndef dbdump_all():\n \"导出数据库所有数据至当前目录下以年月日命名的sql文件\"\n filename=datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".sql\"\n cmd=\"\"\"mysqldump -u root -pzhoubt --opt --quick --database search >./%s\"\"\"%filename\n print cmd\n p=subprocess.Popen(cmd,shell=True,cwd=os.getcwd())\n sts = o...
[ 2 ]
[]
[]
[ "import", "mysql", "python", "subprocess" ]
stackoverflow_0003920473_import_mysql_python_subprocess.txt
Q: Now to convert this strings to date time object in Python or django? Now to convert this strings to date time object in Python or django? 2010-08-17T19:00:00Z 2010-08-17T18:30:00Z 2010-08-17T17:05:00Z 2010-08-17T14:30:00Z 2010-08-10T22:20:00Z 2010-08-10T21:20:00Z 2010-08-10T20:25:00Z 2010-08-10T19:30:00Z 2010-08-1...
Now to convert this strings to date time object in Python or django?
Now to convert this strings to date time object in Python or django? 2010-08-17T19:00:00Z 2010-08-17T18:30:00Z 2010-08-17T17:05:00Z 2010-08-17T14:30:00Z 2010-08-10T22:20:00Z 2010-08-10T21:20:00Z 2010-08-10T20:25:00Z 2010-08-10T19:30:00Z 2010-08-10T19:00:00Z 2010-08-10T18:30:00Z 2010-08-10T17:30:00Z 2010-08-10T17:05:00Z...
[ "You can parse the strings as-is without the need to slice if you don't mind using the handy dateutil module. For e.g.\n>>> from dateutil.parser import parse\n>>> s = \"2010-08-17T19:00:00Z\"\n>>> parse(s)\ndatetime.datetime(2010, 8, 17, 19, 0, tzinfo=tzutc())\n>>> \n\n", "Use slicing to remove \"Z\" before suppl...
[ 11, 7, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003918735_django_python.txt
Q: Basic Python Function and Constant Help I'm not sure where to even start this assignment: In shopping for a new house, you must consider several factors. In this problem the initial cost of the house, the estimated annual fuel costs, and the annual tax rate are available. Write a program that determines and displa...
Basic Python Function and Constant Help
I'm not sure where to even start this assignment: In shopping for a new house, you must consider several factors. In this problem the initial cost of the house, the estimated annual fuel costs, and the annual tax rate are available. Write a program that determines and displays the total cost of a house after a five-yea...
[ "To calculate the house cost, add the initial cost \ninitial_cost\n\nto the fuel cost for five years, \nYEARS = 5\ninitial_cost + YEARS * annual_fuel_cost\n\nthen add the taxes for five years. Taxes for one year are computed by multiplying the tax rate by the initial cost.\ninitial_cost + YEARS * annual_fuel_cost +...
[ 2, 0 ]
[]
[]
[ "constants", "function", "python" ]
stackoverflow_0003920856_constants_function_python.txt
Q: using python module in java with jython I have a couple of python modules in an existing Python project that I wish to make use of in my Java app. I found an article and followed the steps mentioned there. In particular, I need to import the java interface: package jyinterface.interfaces; public interface Employe...
using python module in java with jython
I have a couple of python modules in an existing Python project that I wish to make use of in my Java app. I found an article and followed the steps mentioned there. In particular, I need to import the java interface: package jyinterface.interfaces; public interface EmployeeType { . . } into the module: from ...
[ "You can use it with Jython but not with CPython, the standard implementation.\nHow ever, there is an effort to provide full access to java class libraries when you use CPython. \n\nhttp://jpype.sourceforge.net/\n\n" ]
[ 1 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0003921000_java_jython_python.txt
Q: how to format variables before db to avoid errors I am recieving errors like this one: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't Stop.mp3' LIMIT 1' at line 1") Because I am tr...
how to format variables before db to avoid errors
I am recieving errors like this one: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't Stop.mp3' LIMIT 1' at line 1") Because I am trying to compare a URL that exists in my DB to one in a ...
[ "Let the MySQLdb module do the interpolation:\ncursor.execute(\"\"\"SELECT * FROM LINKS WHERE link = %s LIMIT 1\"\"\",\n (item['link'].encode(\"utf-8\"),)\n)\n\nThe execute() function can be passed items to be substituted into the query (see the documentation for execute()). It will automatically escape things a...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003921075_mysql_python.txt
Q: Serializing decimal points in Django, getting error: 'ValuesListQuerySet' object has no attribute '_meta' Is there a way I can serialize a FloatField model instance in django? I have the following in a management command: def chart_data(request): i = 1 chart = open_flash_chart() chart.title = t ...
Serializing decimal points in Django, getting error: 'ValuesListQuerySet' object has no attribute '_meta'
Is there a way I can serialize a FloatField model instance in django? I have the following in a management command: def chart_data(request): i = 1 chart = open_flash_chart() chart.title = t for manager in FusionManagers.objects.all(): net_data = manager.netio_set.values_list('Net', flat=True) ...
[ "\nThe Django serialization module only works on lists/querysets of full Django objects; ValuesListQuerySet contains tuples, not Django objects.\n\nI am quoting from a comment attached to Django ticket #8090. You'll need to get a QuerySet if you want to use Django's built in serialization. If not, you'll have to us...
[ 1 ]
[]
[]
[ "django", "django_models", "json", "python" ]
stackoverflow_0003921124_django_django_models_json_python.txt
Q: python - need help inserting text files with open() into mysql Can someone help me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)? For example: cursor.execute("insert into mytable (file_contents) values ('"+open(filename,"r").read()+"')") Obviously that'...
python - need help inserting text files with open() into mysql
Can someone help me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)? For example: cursor.execute("insert into mytable (file_contents) values ('"+open(filename,"r").read()+"')") Obviously that's not very practical, can someone post a better way to do this?
[ "It is dangerous to append content of a file directly into an SQL query, because of special characters (quotes!) or malicious SQL commands.\nTry this:\nwith open(filename,\"r\") as infile:\n cursor.execute(\"insert into mytable (file_contents) values (%s)\", (infile.read(), ))\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003920889_python.txt
Q: Multiple-instance Django forum software Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django? A: I once created a feature matrix of all Django forum apps I coul...
Multiple-instance Django forum software
Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?
[ "I once created a feature matrix of all Django forum apps I could find. It might be a bit outdated now, though (contributions welcome).\nAt least django-threadedcomments uses generic foreign keys, so you can attach a message thread to any database object, including users. \n", "Look at DjangoBB.\n", "Yep, the f...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "django", "forum", "python" ]
stackoverflow_0000546753_django_forum_python.txt
Q: Linear Regression with Python numpy I'm trying to make a simple linear regression function but continue to encounter a numpy.linalg.linalg.LinAlgError: Singular matrix error Existing function (with debug prints): def makeLLS(inputData, targetData): print "In makeLLS:" print " Shape inputData:",inputD...
Linear Regression with Python numpy
I'm trying to make a simple linear regression function but continue to encounter a numpy.linalg.linalg.LinAlgError: Singular matrix error Existing function (with debug prints): def makeLLS(inputData, targetData): print "In makeLLS:" print " Shape inputData:",inputData.shape print " Shape targetData...
[ "As explained in the other answer linalg.solve expects a full rank matrix. This is because it tries to solve a matrix equation rather than do linear regression which should work for all ranks.\nThere are a few methods for linear regression. The simplest one I would suggest is the standard least squares method. Just...
[ 19, 8 ]
[]
[]
[ "linear_regression", "numpy", "python" ]
stackoverflow_0003920571_linear_regression_numpy_python.txt
Q: Reverting the 'global ' statement I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity. I have a function: def f(): x = 12 #this is a local variable global x #this is a global I declared before x = 14 #chan...
Reverting the 'global ' statement
I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity. I have a function: def f(): x = 12 #this is a local variable global x #this is a global I declared before x = 14 #changes global x <How can I return the...
[ "Your code isn't doing what you think it is and there's no way to change it do what you describe. You can't \"revert\" what globals does since it has no effect at run time.\nThe global keyword is interpreted at compile time so in the first line of f() where you set x = 12 this is modifying the global x since the c...
[ 7, 4, 1 ]
[]
[]
[ "global", "local", "python", "scope" ]
stackoverflow_0003921822_global_local_python_scope.txt
Q: wxPython and py2app, CreateActCtx error 0x00000008 (Not enough disk space available) I've been developing an application that uses wxPython as the GUI librar, and py2exe so that I can easily distribute it, however I have just now tested py2exe and the following error appears when the executable is launched. 12:13:...
wxPython and py2app, CreateActCtx error 0x00000008 (Not enough disk space available)
I've been developing an application that uses wxPython as the GUI librar, and py2exe so that I can easily distribute it, however I have just now tested py2exe and the following error appears when the executable is launched. 12:13:08: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x00000008 (Not enough d...
[ "That means common controls stuff does not load. The second error could be a result of the first error which is non fatal and program continues to run.\ntry first : \n(Don't bundle option) and check if the issue still appears. This should typically work.\nbundle_files = 3 \n\ntry next: \nSince, you are using bundle...
[ 2, 0 ]
[]
[]
[ "py2exe", "python", "twisted", "wxpython" ]
stackoverflow_0003590440_py2exe_python_twisted_wxpython.txt
Q: python beautifulsoup related problem i have some problem to extract some data from html source. following is sniffit of my html source code, and i want to extract string value in every following <td class="gamedate">10/12 00:59</b></td> <td class="gametype">오버언더</b></td> <td class="legue"><nobr style="width:10...
python beautifulsoup related problem
i have some problem to extract some data from html source. following is sniffit of my html source code, and i want to extract string value in every following <td class="gamedate">10/12 00:59</b></td> <td class="gametype">오버언더</b></td> <td class="legue"><nobr style="width:100%;overflow:hidden;letter-spacing:-1;font-...
[ "Why not just do a replace on the string\nhtml.replace(\"AAAAAA\", \"Put what you want for AAAAAA here\")\n\nand do this for all of the things you want to replace?\nIgnore, I miss read the question completely my brain must not be on today\n", "You may use HTMLParser \n", "Something like this works on a basic ta...
[ 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003911201_beautifulsoup_python.txt
Q: Python/Django: Adding custom model methods? Using for example class model(models.Model) .... def my_custom_method(self, *args, **kwargs): #do something When I try to call this method during pre_save, save, post_save etc, Python raises a TypeError; unbound method. How can one add custom model metho...
Python/Django: Adding custom model methods?
Using for example class model(models.Model) .... def my_custom_method(self, *args, **kwargs): #do something When I try to call this method during pre_save, save, post_save etc, Python raises a TypeError; unbound method. How can one add custom model methods which can be executed in the same way like mod...
[ "How are you calling this method? You have defined an instance method, which can only be called on an instance of the class, not the class itself. In other words, once you have an instance of model called mymodelinstance, you can do mymodelinstance.my_custom_method().\nIf you want to call it on the class, you need ...
[ 42, 0 ]
[]
[]
[ "django", "methods", "model", "python" ]
stackoverflow_0003921619_django_methods_model_python.txt
Q: Matching Popen.communicate() output with regular expressions doesn't work I have code that roughly looks like this (the entire code is a bit too long to copy here): import re from subprocess import Popen, PIPE goodOutput = re.compile(r'\S+: 0x[0-9a-fA-F]{8} \d \d\s+->\s+0x[0-9a-fA-F]{8}') p = Popen(['/tmp/myexe'...
Matching Popen.communicate() output with regular expressions doesn't work
I have code that roughly looks like this (the entire code is a bit too long to copy here): import re from subprocess import Popen, PIPE goodOutput = re.compile(r'\S+: 0x[0-9a-fA-F]{8} \d \d\s+->\s+0x[0-9a-fA-F]{8}') p = Popen(['/tmp/myexe', param], stdout=PIPE, stderr=PIPE, cwd='/tmp') stdout, stderr = p.communicate...
[ "There still seem to be either typos in your regex or errors that lead to it not matching (extraneous }, too much whitespace).\nTry \ngoodOutput = re.compile(r\"\\s*[^:]:s*0x[0-9a-fA-F]{8}\\s+\\d\\s+\\d\\s+->\\s+0x[0-9a-fA-F]{8}\"`\n\nand see if that helps.\nAlso, try re.search() vs. re.match() and see if that make...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex", "stdout", "subprocess" ]
stackoverflow_0003921106_python_regex_stdout_subprocess.txt
Q: problem with running jpype with mod_python As Python's urllib module is too slow, I'm using Java code wrapped with JPype in my web site. When I tested my web site with Django web server, there was no problem. However when I switched the web server to apache2 + mod_python, following error occurs. I googled many tim...
problem with running jpype with mod_python
As Python's urllib module is too slow, I'm using Java code wrapped with JPype in my web site. When I tested my web site with Django web server, there was no problem. However when I switched the web server to apache2 + mod_python, following error occurs. I googled many times but couldn't find the answer. Is there any so...
[ "Another solution for your original problem: find other ways to get faster url retrieval. \nhttplib2 might already be a good solution: no problem to get it working as it's just a python library, but support for Keep-Alive connections can speed up things a lot, plus the caching support will help too (but only if you...
[ 0 ]
[]
[]
[ "java", "mod_python", "python" ]
stackoverflow_0003921583_java_mod_python_python.txt
Q: Reading data from memcache sometimes fails I've written a gevent-based program that allows its web clients to quickly exchange messages through it (so it works like a hub). Since I only support polling mechanism at this moment, I've written it to store messages that need to be delivered to a specific client in its...
Reading data from memcache sometimes fails
I've written a gevent-based program that allows its web clients to quickly exchange messages through it (so it works like a hub). Since I only support polling mechanism at this moment, I've written it to store messages that need to be delivered to a specific client in its 'inbox' at the server side. While the client li...
[ "I think I got it: it's a bug in the python-memcache module.\n" ]
[ 0 ]
[]
[]
[ "gevent", "memcached", "python" ]
stackoverflow_0003904547_gevent_memcached_python.txt
Q: TKinter: how to create a histogram? How can I create a histogram with TKinter and python ? A: this will help : http://effbot.org/tkinterbook/canvas.htm or http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas.html A: I don't know any out-of-the-box histogram widget. You may have to write your own. You may be in...
TKinter: how to create a histogram?
How can I create a histogram with TKinter and python ?
[ "this will help : http://effbot.org/tkinterbook/canvas.htm or http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas.html\n", "I don't know any out-of-the-box histogram widget. You may have to write your own. You may be interested by the Widget Construction Kit to help you in this task.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003921912_python_tkinter.txt
Q: app engine DeadlineExceededError for cron jobs and task queue for wikipedia crawler I am trying to build a wikipedia link crawler on google app engine. I wanted to store an index in the datastore. But I run into the DeadlineExceededError for both cron jobs and task queue. for the cron job I have this code: def b...
app engine DeadlineExceededError for cron jobs and task queue for wikipedia crawler
I am trying to build a wikipedia link crawler on google app engine. I wanted to store an index in the datastore. But I run into the DeadlineExceededError for both cron jobs and task queue. for the cron job I have this code: def buildTree(self): start=time.time() self.log.info(" Start Time: %f" % start) no...
[ "I have had great success with datetimes on GAE.\nfrom datetime import datetime, timedelta\ntime_start = datetime.now()\ntime_taken = datetime.now() - time_start\n\ntime_taken will be a timedelta. You can compare it against another timedelta that has the duration you are interested in.\nten_seconds = timedelta(seco...
[ 2, 1, 1, 1 ]
[]
[]
[ "cron", "google_app_engine", "python", "wikipedia" ]
stackoverflow_0003919337_cron_google_app_engine_python_wikipedia.txt
Q: How can I base64-encode unicode strings in JavaScript and Python? I need an encript arithmetic, which encript text to text. the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max) and it could be decrypt to unicode again. it should implement in javascript and python. If there is alr...
How can I base64-encode unicode strings in JavaScript and Python?
I need an encript arithmetic, which encript text to text. the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max) and it could be decrypt to unicode again. it should implement in javascript and python. If there is already some library could do this, great, if there is not, could you tell...
[ "You might want to look at the base64 module. In Python 2.x (starting with 2.4):\n>>> import base64\n>>> s=u\"Rückwärts\"\n>>> s\nu'R\\xfcckw\\xe4rts'\n>>> b=base64.b64encode(s.encode(\"utf-8\"))\n>>> b\n'UsO8Y2t3w6RydHM='\n>>> d=base64.b64decode(b)\n>>> d\n'R\\xc3\\xbcckw\\xc3\\xa4rts'\n>>> d.decode(\"utf-8\")\nu'...
[ 10, 4 ]
[]
[]
[ "base64", "encoding", "javascript", "python" ]
stackoverflow_0003922314_base64_encoding_javascript_python.txt
Q: GAE simple app question I am learning GAE with python. I am trying to build the simplest possible application: get name from user; write name to datastore; retrieve name and display page. I tried the tutorial but I still do not understand how to do this. I appreciate any answers. Thank you A: i´m going to post a...
GAE simple app question
I am learning GAE with python. I am trying to build the simplest possible application: get name from user; write name to datastore; retrieve name and display page. I tried the tutorial but I still do not understand how to do this. I appreciate any answers. Thank you
[ "i´m going to post a little snippet:\nCreate a file in your root directory, name it main.py\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\n# Pagina principal\nclass MainP...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003920371_google_app_engine_python.txt
Q: How to add Google Analytics to reStructuredText? I am using reStructured text to create some easy websites. So I have got a lot of *.rst files in which I want to add the Google Analytics code. But as far as I know it is not possible to add something like this?! I am using rst2html to convert the files to html. ...
How to add Google Analytics to reStructuredText?
I am using reStructured text to create some easy websites. So I have got a lot of *.rst files in which I want to add the Google Analytics code. But as far as I know it is not possible to add something like this?! I am using rst2html to convert the files to html.
[ "I've just discovered an easy way to add custom content to .rst files. All you need to do it to modify the template for html files. \nMake a new template template.txt and the following contents to it (based on the default template):\n%(head_prefix)s\n%(head)s\n<!--your tracking code-->\n%(stylesheet)s\n%(body_prefi...
[ 7, 2, 2, 1 ]
[]
[]
[ "docutils", "python", "restructuredtext" ]
stackoverflow_0003176258_docutils_python_restructuredtext.txt
Q: Getting a result from a modal window in pygtk I need to open a new window from my applications main window. This new window need to be modal, I need to be able to get a result from the modal window based on user interaction with it. I have figured out how to make the window modal. But I can't figure out how to ret...
Getting a result from a modal window in pygtk
I need to open a new window from my applications main window. This new window need to be modal, I need to be able to get a result from the modal window based on user interaction with it. I have figured out how to make the window modal. But I can't figure out how to return a result from the modal window and pass it back...
[ "You probably want to make your window a gtk.Dialog and launch it via the run() method. This is designed to do exactly what you are looking for. \nSee pygtk docs for gtk.Dialog.run\n" ]
[ 1 ]
[]
[]
[ "modal_dialog", "pygtk", "python" ]
stackoverflow_0003922829_modal_dialog_pygtk_python.txt
Q: Pythonic way to write create dictionary from dict comprehension, + something else I want to do something like this: parsetable = { # ... declarations: { token: 3 for token in [_id, _if, _while, _lbrace, _println] }.update({_vari...
Pythonic way to write create dictionary from dict comprehension, + something else
I want to do something like this: parsetable = { # ... declarations: { token: 3 for token in [_id, _if, _while, _lbrace, _println] }.update({_variable: 2}), #... } However this doesn't work because update...
[ "I think the approach you mentioned using dict() and a list of tuples is the way I would do it:\ndict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])\n\nIf you really want to use a dict comprehension you can do something like this:\n{ x : 2 if x == _variable else 3\n for x in [_id, _if,...
[ 4, 1, 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003918059_dictionary_python.txt
Q: How to interchange data between two python applications? I have two python applications. I need to send commands and data between them (between two processes). What is the best way to do that? One program is a daemon who should accept commands and parameters from another GUI application. How can I make daemon to m...
How to interchange data between two python applications?
I have two python applications. I need to send commands and data between them (between two processes). What is the best way to do that? One program is a daemon who should accept commands and parameters from another GUI application. How can I make daemon to monitor comands from GUI, while making it's job? I prefer solut...
[ "You can use the following methods for data interchange:\n\nSocket Programming : In Qt you can access QtNetwork module. See qt assistant for examples\nIPC : Use shared Memory implemented in QSharedMemory class.\nIf this application will run on unix os only, then you can try Posix based message queue etc. for data i...
[ 10, 2, 0 ]
[]
[]
[ "pid", "process", "pyqt4", "python" ]
stackoverflow_0003922135_pid_process_pyqt4_python.txt
Q: set key with new bulkloader I am converting a script to use the new bulkloader. (What was wrong with the original bulkloader? - I prefer writing Python to editing configuration files...) Anyway, I want to prevent duplicates by assigning a combination of properties to the key. The docs say: If you want to use or c...
set key with new bulkloader
I am converting a script to use the new bulkloader. (What was wrong with the original bulkloader? - I prefer writing Python to editing configuration files...) Anyway, I want to prevent duplicates by assigning a combination of properties to the key. The docs say: If you want to use or calculate a key from the import ...
[ "You can do this using the 'import_template' property (documented here) instead of 'import_transform':\n- property: __key__\n import_template: \"%(first_name)s %(last_name)s\"\n\n" ]
[ 1 ]
[]
[]
[ "backup", "bulkloader", "google_app_engine", "python" ]
stackoverflow_0003920171_backup_bulkloader_google_app_engine_python.txt
Q: Split a string in python a="aaaa#b:c:" >>> for i in a.split(":"): ... print i ... if ("#" in i): //i=aaaa#b ... print only b In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value? A: The following can repl...
Split a string in python
a="aaaa#b:c:" >>> for i in a.split(":"): ... print i ... if ("#" in i): //i=aaaa#b ... print only b In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?
[ "The following can replace your if statement.\nfor i in a.split(':'):\n print i.partition('#')[2]\n\n", "a = \"aaaa#b:c:\"\nprint(a.split(\":\")[0].split(\"#\")[1])\n\n", "I'd suggest from: Python Docs\n\nstr.rsplit([sep[, maxsplit]])\nReturn a list of the words in the string, using sep as the delimiter\n s...
[ 2, 1, 1, 1, 0 ]
[ "split would do the job nicely. Use rsplit only if you need to split from the last '#'.\na=\"aaaa#b:c:\"\n>>> for i in a.split(\":\"):\n... print i\n... b = i.split('#',1)\n... if len(b)==2:\n... print b[1]\n\n" ]
[ -1 ]
[ "python", "string" ]
stackoverflow_0003914659_python_string.txt
Q: Understanding what files in the TCL are required for distributing frozen Python Tkinter apps I'm trying to figure out which files in Python's (Python 2.6/Python 2.7) tcl folder are required in order to distribute frozen Python Tkinter apps using Py2exe or similar. The quick and dirty way to do this (using pyexe a...
Understanding what files in the TCL are required for distributing frozen Python Tkinter apps
I'm trying to figure out which files in Python's (Python 2.6/Python 2.7) tcl folder are required in order to distribute frozen Python Tkinter apps using Py2exe or similar. The quick and dirty way to do this (using pyexe as an example) is to follow the 2nd example on the following page and then xcopy your python's tcl ...
[ "You don't need the demos (I hope; if you do, that's gross!) but everything else is potentially required; the encodings are used to convert between the outside world's bytes and Tcl's characters, and the tzdata is used to make the time processing work. You can trim the encodings and tzdata if you are delivering the...
[ 5, 3 ]
[]
[]
[ "freeze", "py2exe", "python", "tcl", "tkinter" ]
stackoverflow_0003900375_freeze_py2exe_python_tcl_tkinter.txt
Q: How to validate an xml file against an XSD Schema using Amara library in Python? High bounty for the following Q: Hello, Here is what I tried on Ubuntu 9.10 using Python 2.6, Amara2 (by the way, test.xsd was created using xml2xsd tool): g@spot:~$ cat test.xml; echo =====o=====; cat test.xsd; echo ==== o=====; ...
How to validate an xml file against an XSD Schema using Amara library in Python?
High bounty for the following Q: Hello, Here is what I tried on Ubuntu 9.10 using Python 2.6, Amara2 (by the way, test.xsd was created using xml2xsd tool): g@spot:~$ cat test.xml; echo =====o=====; cat test.xsd; echo ==== o=====; cat test.py; echo =====o=====; ./test.py; echo =====o===== <?xml version="1.0" encodi...
[ "If you're open to using another library besides amara, try lxml. It supports what you're trying to do pretty easily:\nfrom lxml import etree\n\nsource_file = 'test.xml'\nschema_file = 'test.xsd'\n\nwith open(schema_file) as f_schema:\n\n schema_doc = etree.parse(f_schema)\n schema = etree.XMLSchema(schema_do...
[ 5, 1 ]
[]
[]
[ "amara", "python", "python_2.6", "xsd_validation" ]
stackoverflow_0003330366_amara_python_python_2.6_xsd_validation.txt
Q: How do I down-cast a c++ object from a python SWIG wrapper? The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when ...
How do I down-cast a c++ object from a python SWIG wrapper?
The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when I call it from python, I get a TypeError. Here are the details: ...
[ "As I commented above, this seems to work ok with swig 1.3.40.\nHere are my files:\nc.h:\n#include <iostream>\nclass Base {};\nclass Derived : public Base\n{\n public:\n void f() const { std::cout << \"In Derived::f()\" << std::endl; }\n};\nclass Container {\n public:\n const Base& GetBase() const {\n...
[ 3, 0, 0 ]
[]
[]
[ "c++", "downcast", "python", "swig", "typeerror" ]
stackoverflow_0003921294_c++_downcast_python_swig_typeerror.txt
Q: translating arrays from c to python ctypes I have the below arrays on C how can i interpert them to ctypes datatypes inside structre struct a { BYTE a[30]; CHAR b[256]; }; should i interpert a fixed array as the datatype * the size i want like the below and if yes how can i call this structure as a param...
translating arrays from c to python ctypes
I have the below arrays on C how can i interpert them to ctypes datatypes inside structre struct a { BYTE a[30]; CHAR b[256]; }; should i interpert a fixed array as the datatype * the size i want like the below and if yes how can i call this structure as a parameter to fun that takes instance from this struc...
[ "You're on the right track. You're probably just missing the byref() function. Assuming the function you want to call is named *print_struct*, do the following:\nfrom ctypes import *\n\nclass MyStruct(Structure):\n _fields_ = [('a',c_byte*30), ('b',c_char*256)]\n\ns = MyStruct() # Allocates a new instance of the...
[ 3, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003922290_ctypes_python.txt
Q: Py2Exe + FTDI driver Is it at all possible to somehow include the FTDI driver in a py2exe installer? If not, are there any ways to combine the two together in one easy installer? A: Include the FTDI driver folders in your distribution using py2exe's data_files option. You can run code like this to make the drive...
Py2Exe + FTDI driver
Is it at all possible to somehow include the FTDI driver in a py2exe installer? If not, are there any ways to combine the two together in one easy installer?
[ "Include the FTDI driver folders in your distribution using py2exe's data_files option.\nYou can run code like this to make the drivers visible to your application even if they aren't installed in system32:\nos.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/i386'))\nos.environ['PATH'] = ...
[ 0 ]
[]
[]
[ "driver", "ftdi", "installation", "py2exe", "python" ]
stackoverflow_0003923644_driver_ftdi_installation_py2exe_python.txt
Q: Python solution to allow photo uploading via email to my Django website I am learning Python/Django and my pet project is a photo sharing website. I would like to give users the ability to upload their photos using an email address like Posterous, Tumblr. Research has led me to believe I need to use the following...
Python solution to allow photo uploading via email to my Django website
I am learning Python/Django and my pet project is a photo sharing website. I would like to give users the ability to upload their photos using an email address like Posterous, Tumblr. Research has led me to believe I need to use the following: -- cron job -- python mail parser -- cURL or libcurl -- something that upda...
[ "Read messages from maildir. It's not optimized but show how You can parse emails. Of course you should store information about files and users to database. Import models into this code and make right inserts.\nimport mailbox\nimport sys\nimport email\nimport os\nimport errno\nimport mimetypes\n\n\nmdir = mailbox.M...
[ 3, 0 ]
[]
[]
[ "cron", "django", "email", "postfix_mta", "python" ]
stackoverflow_0003923915_cron_django_email_postfix_mta_python.txt
Q: Convert string to a tuple I have a string like this: '|Action and Adventure|Drama|Science-Fiction|Fantasy|' How can I convert it to a tuple or a list? Thanks. A: >>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|' >>> >>> [item for item in s.split('|') if item.strip()] ['Action and Adventure', 'Drama...
Convert string to a tuple
I have a string like this: '|Action and Adventure|Drama|Science-Fiction|Fantasy|' How can I convert it to a tuple or a list? Thanks.
[ ">>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'\n>>> \n>>> [item for item in s.split('|') if item.strip()]\n['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']\n>>> \n\nIf you'd rather have a tuple then:\n>>> tuple(item for item in s.split('|') if item.strip())\n('Action and Adventure', ...
[ 8, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003920751_python.txt
Q: Subprocess in Python Add Variables Subprocess in Python Add Variables import subprocess subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010') I want to be able to set the variables on the above command. the variables are the time '15:42' separated in 15 and 42 and the ...
Subprocess in Python Add Variables
Subprocess in Python Add Variables import subprocess subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010') I want to be able to set the variables on the above command. the variables are the time '15:42' separated in 15 and 42 and the date '13/10/2010' separated in day , mon...
[ "Use % formatting to build the command string.\n>>> hour,minute = '15','42'\n>>> day,month,year = '13','10','2010'\n>>> command = 'Schtasks /create /sc ONCE /tn Work /tr C:\\work.exe /st %s:%s /sd %s/%s/%s'\n>>> command % (hour,minute, day,month,year)\n'Schtasks /create /sc ONCE /tn Work /tr C:\\\\work.exe ...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003924122_python_string.txt
Q: Problem displaying xfbml with pyfacebook I'm using pyfacebook on my app but I'm having problems displaying xfbml For example I have to use iframes to display like buttons or like boxes. What's strange: 1) On the login page the appears correctly, I just have problems on other pages (once logged in) 2) The FB.init ...
Problem displaying xfbml with pyfacebook
I'm using pyfacebook on my app but I'm having problems displaying xfbml For example I have to use iframes to display like buttons or like boxes. What's strange: 1) On the login page the appears correctly, I just have problems on other pages (once logged in) 2) The FB.init part I use is <script src="http://static.ak.co...
[ "I think you are confusing Facebook's old javascript API with their new javascript API.\nAs mentioned on the new API page, use this to do the init:\n<div id=\"fb-root\"></div>\n<script>\n window.fbAsyncInit = function() {\n FB.init({appId: 'your app id', status: true, cookie: true,\n xfbml: true});\...
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "javascript", "pyfacebook", "python" ]
stackoverflow_0003924414_facebook_google_app_engine_javascript_pyfacebook_python.txt
Q: Python Queue - Threads bound to only one core I wrote a python script that: 1. submits search queries 2. waits for the results 3. parses the returned results(XML) I used the threading and Queue modules to perform this in parallel (5 workers). It works great for the querying portion because i can submit multip...
Python Queue - Threads bound to only one core
I wrote a python script that: 1. submits search queries 2. waits for the results 3. parses the returned results(XML) I used the threading and Queue modules to perform this in parallel (5 workers). It works great for the querying portion because i can submit multiple search jobs and deal with the results as they co...
[ "This is a byproduct of how CPython handles threads. There are endless discussions around the internet (search for GIL) but the solution is to use the multiprocessing module instead of threading. Multiprocessing is built with pretty much the same interface (and synchronization structures, so you can still use queue...
[ 4, 2 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0003924637_multithreading_python_queue.txt
Q: What is the easiest way to search through a list of dicts in Python? My database currently returns a list of dicts: id_list = ({'id': '0c871320cf5111df87da000c29196d3d'}, {'id': '2eeeb9f4cf5111df87da000c29196d3d'}, {'id': '3b982384cf5111df87da000c29196d3d'}, {'id': '3f6f3fcecf51...
What is the easiest way to search through a list of dicts in Python?
My database currently returns a list of dicts: id_list = ({'id': '0c871320cf5111df87da000c29196d3d'}, {'id': '2eeeb9f4cf5111df87da000c29196d3d'}, {'id': '3b982384cf5111df87da000c29196d3d'}, {'id': '3f6f3fcecf5111df87da000c29196d3d'}, {'id': '44762370cf5111df87da000c29196d...
[ "Here's a one-liner:\nif some_id in [d.get('id') for d in id_list]:\n pass\n\nNot very efficient though.\nedit -- A better approach might be:\nif some_id in (d.get('id') for d in id_list):\n pass\n\nThis way, the list isn't generated in full length beforehand.\n", "\nHow can I easily check if a given id is ...
[ 7, 7, 5, 3, 2 ]
[]
[]
[ "python", "python_datamodel" ]
stackoverflow_0003924397_python_python_datamodel.txt
Q: how to use paramiko to execute remote commands I wanted to compress a folder on a remote namchine.For that i am using paramiko. But i don't know how to do that using paramiko. Any suggestions?? This is my code: dpath = '/var/mysql/5.1/mysql.zip' port = 22 host = '10.88.36.7' transport = paramiko.Transp...
how to use paramiko to execute remote commands
I wanted to compress a folder on a remote namchine.For that i am using paramiko. But i don't know how to do that using paramiko. Any suggestions?? This is my code: dpath = '/var/mysql/5.1/mysql.zip' port = 22 host = '10.88.36.7' transport = paramiko.Transport((host, port)) transport.connect(username=sus...
[ "After \nchannel.exec_command(...)\n\nYou have to wait the termination of the command with:\nwhile not channel.exit_status_ready()\n ... wait ... ( you can read the output with channel.recv, or sleep a bit)\n\nFurthermore, you're zip command is weird... don't you want to say\nzip -r /var/db/mysql.zip /var/db/mys...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003924411_python.txt
Q: FormEncode validate: words divided by a comma How to validate words divided by a comma by FormEncode ? Something like this: "foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"] A: You'll probably need a custom validator. Here's a quick example: import formencode class CommaSepList(formencode.validators.FancyValidato...
FormEncode validate: words divided by a comma
How to validate words divided by a comma by FormEncode ? Something like this: "foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
[ "You'll probably need a custom validator. Here's a quick example:\nimport formencode\n\nclass CommaSepList(formencode.validators.FancyValidator):\n\n def _to_python(self, value, state):\n return value.split(\",\")\n\n def validate_python(self, value, state):\n for elem in value:\n if...
[ 1, 0 ]
[]
[]
[ "formencode", "pylons", "python" ]
stackoverflow_0003924355_formencode_pylons_python.txt
Q: Django and Haystack search issue I am running Python 2.6, the lastest haystack, django 1.2 beta and I have tried both Woosh and Xapian backends. The problem is that I cannot do a __lt or __gt filter on an integer field - when such is used,there are always none results found... My model: # -*- coding: utf-8 -*- fr...
Django and Haystack search issue
I am running Python 2.6, the lastest haystack, django 1.2 beta and I have tried both Woosh and Xapian backends. The problem is that I cannot do a __lt or __gt filter on an integer field - when such is used,there are always none results found... My model: # -*- coding: utf-8 -*- from django.db import models from django...
[ "I don't have a real answer, but here's how I would look for it:\nTry logging/printing the query you're actually building here (sqs just before the end of the search method). it might give you clues as to what is wrong.\nTry running the same kind of query (same set of filters) in the shell. what results do you get?...
[ 0, 0 ]
[]
[]
[ "django_haystack", "python" ]
stackoverflow_0002892466_django_haystack_python.txt
Q: Which is the most recommended Python Twitter library for programmatically updating my own Twitter stream? After Twitter discontinuing the Basic Auth, my program which updates my own Twitter stream (not others' Twitter streams.) has broken. I understand that OAuth is the way to go. I have set up a Twitter App for t...
Which is the most recommended Python Twitter library for programmatically updating my own Twitter stream?
After Twitter discontinuing the Basic Auth, my program which updates my own Twitter stream (not others' Twitter streams.) has broken. I understand that OAuth is the way to go. I have set up a Twitter App for the same and have acquired the consumer tokens. Now I don't want to implement the OAuth for Twitter all by mysel...
[ "you might want to try tweepy for that...\n", "I suggest tweepy as well, it's pretty simple, has oAuth/xAuth support, covers all features of Twitter API, actively under development and has a quick documentation to get you started. The author also claims python 3 support but it was discontinued a few months ago.\n...
[ 4, 1, 0 ]
[]
[]
[ "oauth", "python", "twitter" ]
stackoverflow_0003923292_oauth_python_twitter.txt
Q: Changing the encoding of a table with django+south migrations using --auto Django newbie here I know that I can change the encoding of a table by writing my own south migration. My question is, is there a way doing it by changing my model and using ./manage.py schemamigration my_app --auto ? A: AFAIK, there is ...
Changing the encoding of a table with django+south migrations using --auto
Django newbie here I know that I can change the encoding of a table by writing my own south migration. My question is, is there a way doing it by changing my model and using ./manage.py schemamigration my_app --auto ?
[ "AFAIK, there is no such thing as charset modification migration, as charset depends on deployment and thus is settings option.\nThus, You must crate the migration manually (so probably without --auto and using raw SQL). \n" ]
[ 1 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0003448806_django_django_south_python.txt
Q: How to understand this code of flask? Could anyone explain this line? g = LocalProxy(lambda: _request_ctx_stack.top.g) code from flask from werkzeug import LocalStack, LocalProxy # context locals _request_ctx_stack = LocalStack() current_app = LocalProxy(lambda: _request_ctx_stack.top.app) request = LocalProxy(...
How to understand this code of flask?
Could anyone explain this line? g = LocalProxy(lambda: _request_ctx_stack.top.g) code from flask from werkzeug import LocalStack, LocalProxy # context locals _request_ctx_stack = LocalStack() current_app = LocalProxy(lambda: _request_ctx_stack.top.app) request = LocalProxy(lambda: _request_ctx_stack.top.request) ses...
[ "The Werkzeug documentation for LocalStack and LocalProxy might help, as well as some basic understanding of WSGI.\nIt appears what is going on is that a global (but empty) stack _request_ctx_stack is created. This is available to all threads. Some WSGI-style objects (current_app, request, session, and g) are set...
[ 5 ]
[]
[]
[ "flask", "python", "werkzeug" ]
stackoverflow_0003800530_flask_python_werkzeug.txt
Q: Why it's needed to "source" some Vim plugins? From autotag.vim: install details Simply source the file autoTag.vim from your .vimrc file. This utility will (obviously) only work when using vim that's been compiled with python support. Is this needed because this is a Python plugin in vim, instead of a vimscript?...
Why it's needed to "source" some Vim plugins?
From autotag.vim: install details Simply source the file autoTag.vim from your .vimrc file. This utility will (obviously) only work when using vim that's been compiled with python support. Is this needed because this is a Python plugin in vim, instead of a vimscript? Aren't plugins in .vim/plugin loaded automatically...
[ "There is no difference: if you place it in .vim/plugin, you don't need to source it from somewhere else.\nAddendum\nAs Randy Morris explains in the comments, with pathogen.vim's magic, the equivalent plugin path to put the script in would actually be .vim/bundle/autotag/plugin.\n" ]
[ 1 ]
[]
[]
[ "ctags", "plugins", "python", "tags", "vim" ]
stackoverflow_0003925562_ctags_plugins_python_tags_vim.txt
Q: Compare strings with newlines in them? I'm trying to develop a script which compares a runtime generated string against one which is input by the user. Unfortunately, since user inputs his code using a textbox, I get ^M in the string input by user. Example, If I print these strings to file I get this: User Input: ...
Compare strings with newlines in them?
I'm trying to develop a script which compares a runtime generated string against one which is input by the user. Unfortunately, since user inputs his code using a textbox, I get ^M in the string input by user. Example, If I print these strings to file I get this: User Input: 1^M 2^M 3 Output of script: 1 2 3 Obvious...
[ "You should use str.splitlines() to split the text coming from the textbox, instead of whatever it is you're using now. That method handles \\r\\n properly.\n", "mystring.rstrip('\\r') will return a new string with any ^M removed from the end of the string.\n" ]
[ 10, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003925641_python_string.txt
Q: Markdown with custom syntax? I'm using python and using markdown. Is there a simple way to add a custom syntax? I want something like [ABC] expands to a certain tag or something. or do I use regex? A: It appears that you can write extensions for Python-Markdown, which is probably the best approach. If you are us...
Markdown with custom syntax?
I'm using python and using markdown. Is there a simple way to add a custom syntax? I want something like [ABC] expands to a certain tag or something. or do I use regex?
[ "It appears that you can write extensions for Python-Markdown, which is probably the best approach.\nIf you are using some other Markdown implementation (or, you know, just for the heck of it) you could pre-process the text to implement your own tags (converting them to HTML) before handing it off to Markdown. This...
[ 4 ]
[]
[]
[ "markdown", "python" ]
stackoverflow_0003925867_markdown_python.txt
Q: OSX Port Python Library Path? Cant find ctypes I am trying to use an application that has a dependency of ctypes, but am getting this error: $ python peach.py -t ~/Desktop/fuzz/wav/template.xml ] Peach 2.3.6 Runtime ] Copyright (c) Michael Eddington Traceback (most recent call last): File "peach.py", line 335...
OSX Port Python Library Path? Cant find ctypes
I am trying to use an application that has a dependency of ctypes, but am getting this error: $ python peach.py -t ~/Desktop/fuzz/wav/template.xml ] Peach 2.3.6 Runtime ] Copyright (c) Michael Eddington Traceback (most recent call last): File "peach.py", line 335, in <module> from Peach.Engine import * File ...
[ "A simple solution would be to use the native Python build that is included with Mac OS. This definitely works with the latest release of Mac OS X 10.6.4, which has Python 2.6.\nHere is an example showing that '_ctypes' is being imported successfully:\nmariah:~ joet3ch$ /usr/bin/python\nPython 2.6.1 (r261:67515, F...
[ 2, 1 ]
[]
[]
[ "macos", "path", "python" ]
stackoverflow_0003917391_macos_path_python.txt
Q: How to keep a python window on top of all others (python 3.1) I'm writing a little program that basically has a bunch of buttons that when you click one, it inputs a certain line of text into an online game I play. It would be a lot easier to use if the GUI would stay on top of the active game window so the user c...
How to keep a python window on top of all others (python 3.1)
I'm writing a little program that basically has a bunch of buttons that when you click one, it inputs a certain line of text into an online game I play. It would be a lot easier to use if the GUI would stay on top of the active game window so the user could be playing and then press a button on the panel without having...
[ "You will need to provide the information on which GUI framework you are using for detailed answer at SO.\nOn windows you could do something like this with the handle of your window.\nimport win32gui\nimport win32con\nwin32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0,0,0,0,\nwin32con.SWP_NOMOVE | win32con.SWP_NO...
[ 14 ]
[]
[]
[ "button", "python" ]
stackoverflow_0003926655_button_python.txt
Q: Can You Embed an TCL Script in Bash Script or Python Script That's Callable by External Programs? I'm writing a script to extract some useful data about a series of chemical simulations I've been running. To get this data I need (1) a C-program that calculates the density from a file type called *.pdb. I already ...
Can You Embed an TCL Script in Bash Script or Python Script That's Callable by External Programs?
I'm writing a script to extract some useful data about a series of chemical simulations I've been running. To get this data I need (1) a C-program that calculates the density from a file type called *.pdb. I already have (1). And (2) I need to use a program called vmd to get that pdb. In order to accomplish (2) from...
[ "There have been several Tcl-Python alloys. As Rafe Kettler's comment above sketches, the place to start is with a standard Python installation. This includes Tkinter, which builds in a full Tcl interpreter, accessible as described in the Wiki page mentioned. So, yes, it is feasible to \"do this in Python\".\nI ...
[ 5, 1 ]
[]
[]
[ "bash", "embedding", "python", "scripting", "tcl" ]
stackoverflow_0003926273_bash_embedding_python_scripting_tcl.txt
Q: compatibility between CPython and IronPython cPickle I was wondering whether objects serialized using CPython's cPickle are readable by using IronPython's cPickle; the objects in question do not require any modules outside of the built-ins that both Cpython and IronPython include. Thank you! A: If you use the d...
compatibility between CPython and IronPython cPickle
I was wondering whether objects serialized using CPython's cPickle are readable by using IronPython's cPickle; the objects in question do not require any modules outside of the built-ins that both Cpython and IronPython include. Thank you!
[ "If you use the default protocol (0) which is text based, then things should work. I'm not sure what will happen if you use a higher protocol. It's very easy to test this ...\n", "It will work because when you unpickle objects during load() it will use the current definitions of whatever classes you have defined ...
[ 2, 0 ]
[]
[]
[ "ironpython", "pickle", "python" ]
stackoverflow_0003882750_ironpython_pickle_python.txt
Q: print a string in an external application (python 3.1) Suppose I have a game and a python script running. In this game, to speak you just type whatever you want and hit enter. This python script has a button on it that I want to output a predefined string into the game, and hit enter automatically (essentially, th...
print a string in an external application (python 3.1)
Suppose I have a game and a python script running. In this game, to speak you just type whatever you want and hit enter. This python script has a button on it that I want to output a predefined string into the game, and hit enter automatically (essentially, the button causes the character to speak the string). What wou...
[ "Assuming your game is not running in the console (in that case you could use stdin), sendkeys might be an option on Windows. It allows you to send keystrokes to a certain window - in this case, the game window.\nIf the game is scriptable, you should of course use the game's own scripting options if available.\n", ...
[ 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003927368_python_string.txt
Q: Capturing Console output that is not written to stdout,stderr? I have an windows application called pregeocode (we lack source), this program basically writes geocoding to an input file. This program doesn't actually write anything to console unless there is an error. This program is generally called from a small ...
Capturing Console output that is not written to stdout,stderr?
I have an windows application called pregeocode (we lack source), this program basically writes geocoding to an input file. This program doesn't actually write anything to console unless there is an error. This program is generally called from a small Python program (it handles the arguments etc, and does all the fun p...
[ "Since the error message really isn't coming in on either stdout nor stderr, my best guess is that the program is using Windows' equivalent of opening /dev/tty, whatever that is. In Unix you could intercept that with careful use of pty.openpty but, as far as I know, there is no support for similar Windows-specific...
[ 5, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003926952_python_subprocess.txt
Q: How do you get the exact path to "My Documents"? In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see Get path to My Documents Is there a simple way to do this in Python? A: You could use the ctypes module to...
How do you get the exact path to "My Documents"?
In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see Get path to My Documents Is there a simple way to do this in Python?
[ "You could use the ctypes module to get the \"My Documents\" directory:\nimport ctypes\nfrom ctypes.wintypes import MAX_PATH\n\ndll = ctypes.windll.shell32\nbuf = ctypes.create_unicode_buffer(MAX_PATH + 1)\nif dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):\n print(buf.value)\nelse:\n print(\"Failure!\...
[ 15 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003927259_python_windows.txt
Q: Add unit to yaxis labels in MatPlotLib I am trying to add mi or km (miles, kilometers) after the value on the yaxis of a matplotlib bar chart. Right now I am just supplying matplotlib the values and it is making the yaxis labels automatically. I can't figure out how to append mi to the end of a value. 24 > 24...
Add unit to yaxis labels in MatPlotLib
I am trying to add mi or km (miles, kilometers) after the value on the yaxis of a matplotlib bar chart. Right now I am just supplying matplotlib the values and it is making the yaxis labels automatically. I can't figure out how to append mi to the end of a value. 24 > 24 mi There is an option for ax.set_7ticklabel...
[ "Are you wanting something like this?\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\n\nx = range(10)\nplt.plot(x)\n\nplt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d km'))\n\nplt.show()\n\n\n" ]
[ 23 ]
[]
[]
[ "charts", "django", "graph", "matplotlib", "python" ]
stackoverflow_0003927389_charts_django_graph_matplotlib_python.txt
Q: Need help with comparing two pictures in Python Hey guys, Im working on an assignment for my comp sci class, I dont know where Im going wrong here. The function is supposed to take two pictures, pic1 and pic2, and return how different they are. Heres what I have def smart_difference(pic1, pic2): '''Given two P...
Need help with comparing two pictures in Python
Hey guys, Im working on an assignment for my comp sci class, I dont know where Im going wrong here. The function is supposed to take two pictures, pic1 and pic2, and return how different they are. Heres what I have def smart_difference(pic1, pic2): '''Given two Pictures, pic1 and pic2 of any size and colour, return...
[ "Kay, the error is: \"AssertError: result after smart_difference should be between 0 and 1200, not 35000\"\nHeres what I did for simple difference:\ndef simple_difference(pic1, pic2):\n '''Given two Pictures of the same dimensions, pic1 and pic2, return the\n sum of the distances in color of the two pictures....
[ 0 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003927497_image_processing_python.txt
Q: Read static content from within the code of an application Is there a way to read the contents of a static data directory or interact with that data in any way from within the code of an application? Edit: Please excuse me if it wasn't clear at first, I mean getting a list of the files in that directory, not readi...
Read static content from within the code of an application
Is there a way to read the contents of a static data directory or interact with that data in any way from within the code of an application? Edit: Please excuse me if it wasn't clear at first, I mean getting a list of the files in that directory, not reading the data in them.
[ "No. Files marked as static in app.yaml are not available to your application; they're served from separate servers.\nIf you just need to list them, you could build a list as part of your deploy process. If you need to actually read them, you'll need to include a second copy in your application directory (althoug...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003926712_google_app_engine_python.txt
Q: Best way to submit data to a form using Python? I have not worked with web programming or web forms before so I am lost here. There is a simple perl/cgi <form method="post" action="/gestalt/cgi-pub/Kaviar.pl" enctype="multipart/form-data"> Now I tried looking at questions here, did a google search and read some ...
Best way to submit data to a form using Python?
I have not worked with web programming or web forms before so I am lost here. There is a simple perl/cgi <form method="post" action="/gestalt/cgi-pub/Kaviar.pl" enctype="multipart/form-data"> Now I tried looking at questions here, did a google search and read some about urllib2 etc. I guess I don't know enough about ...
[ "This should be a good start:\nimport urllib, urllib2\nurl = 'http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl'\nform_data = {'chr':'chr1', 'pos':'46743'} # the form takes 2 parameters: 'chr', and 'pos'\n # the values given in the dict are\n ...
[ 5 ]
[]
[]
[ "forms", "python" ]
stackoverflow_0003927599_forms_python.txt
Q: List Comprehension in Nested Lists I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]] and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it. I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] t...
List Comprehension in Nested Lists
I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]] and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it. I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the ite...
[ "This will give you the list you want:\n[lx for li in fieldlist for lx in li[1] if li[1]]\n\n", "List comprehension:\n>>> s = [[\"foo\", [\"a\", \"b\", \"c\"]], [\"bar\", [\"a\", \"b\", \"f\"]]]\n>>> [x for y, z in s for x in z]\n['a', 'b', 'c', 'a', 'b', 'f']\n>>>\n\nWhat is the purpose of your if li[1]? If li[1...
[ 5, 0, 0 ]
[]
[]
[ "list_comprehension", "nested_lists", "python" ]
stackoverflow_0003927553_list_comprehension_nested_lists_python.txt
Q: How do I properly format a StringIO object(python and django) to be inserted into an database? I have a requeriment to store images in the database using django, and for that I created a custom field : from django.db import models class BlobField(models.Field): __metaclass__ = models.SubfieldBase def db...
How do I properly format a StringIO object(python and django) to be inserted into an database?
I have a requeriment to store images in the database using django, and for that I created a custom field : from django.db import models class BlobField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self, connection): #TODO handle other db engines backend = connection.settings...
[ "There is no constraint requiring get_db_prep_value to return \"printable\" characters, or ASCII ones, or otherwise-constrained sets of characters: return any byte string that catches your fancy. You'll get a string in to_python and can make a file-like StringIO instance reading its data with the_instance = StringI...
[ 13 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003915888_django_django_models_python.txt
Q: Jython: subprocess.Popen runs out of file descriptors I'm using the Jython 2.51 implementation of Python to write a script that repeatedly invokes another process via subprocess.Popen and uses PIPE to pipe stdout and stderr to the parent process and stdin to the child process. After several hundred loop iteration...
Jython: subprocess.Popen runs out of file descriptors
I'm using the Jython 2.51 implementation of Python to write a script that repeatedly invokes another process via subprocess.Popen and uses PIPE to pipe stdout and stderr to the parent process and stdin to the child process. After several hundred loop iterations, I seem to run out of file descriptors. The Python subp...
[ "This only answers part of your question, but my understanding is that, when you spawn a new process, it normally inherits all the handles of the parent process. That includes such things as open files and sockets that you're listening on.\nOn UNIX, that's a side-effect of using 'fork', which duplicates the curren...
[ 3 ]
[]
[]
[ "file_io", "jython", "popen", "python", "resources" ]
stackoverflow_0003927595_file_io_jython_popen_python_resources.txt
Q: Is it possible to overload from/import in Python? Is it possible to overload the from/import statement in Python? For example, assuming jvm_object is an instance of class JVM, is it possible to write this code: class JVM(object): def import_func(self, cls): return something... jvm = JVM() # would invoke J...
Is it possible to overload from/import in Python?
Is it possible to overload the from/import statement in Python? For example, assuming jvm_object is an instance of class JVM, is it possible to write this code: class JVM(object): def import_func(self, cls): return something... jvm = JVM() # would invoke JVM.import_func from jvm import Foo
[ "This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;) \n", "It's hard to find something which isn't possible in a dynamic language like Python, but do we really need ...
[ 7, 3 ]
[]
[]
[ "import", "operator_overloading", "python" ]
stackoverflow_0003928023_import_operator_overloading_python.txt
Q: I'm trying to pick a framework for a product I'm about to build, and so far I'm leaning toward Nagare... Any thoughts? http://www.nagare.org/ As far as the type of product and framework usage, think something like Facebook (it's not exactly a social network, but close enough for evaluation in this context). Basica...
I'm trying to pick a framework for a product I'm about to build, and so far I'm leaning toward Nagare... Any thoughts?
http://www.nagare.org/ As far as the type of product and framework usage, think something like Facebook (it's not exactly a social network, but close enough for evaluation in this context). Basically, I'm just looking for something robust, scalable, easy to work with (small learning curve is a plus), compatible with ol...
[ "I would suggest Django + Pinax. Both are robust and have less learning curve (if you have familiarity with Python). \nThis should have you a social network up & running within a day or two.\nFor the front-end use the usual suspects. javascript, css, html. I believe there are some terrific libraries for javascript....
[ 5, 4 ]
[]
[]
[ "frameworks", "java", "javascript", "python" ]
stackoverflow_0003921312_frameworks_java_javascript_python.txt
Q: Send files from form directly to remote server In my application I'm dealing with upload of really big image files. They will be stored on a remote server, so from what I was able to learn I need to write some custom Storage system (probably with the use of python's poster module). Because of the size I would like...
Send files from form directly to remote server
In my application I'm dealing with upload of really big image files. They will be stored on a remote server, so from what I was able to learn I need to write some custom Storage system (probably with the use of python's poster module). Because of the size I would like to send the files directly to media server without ...
[ "According to the docs, the UploadedFile class should have a method chunks() which returns a generator. The chunk size is configurable (2.5 MB by default). So you can do something like that (copied from the docs):\ndestination = open('some/file/name.txt', 'wb+')\nfor chunk in f.chunks():\n destination.write(chun...
[ 0, 0 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0003928300_django_file_upload_python.txt
Q: Automatically expiring variable How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in t...
Automatically expiring variable
How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.
[ "I actually had to do this for dictionaries. Maybe you'll find the code useful:\n\"\"\"Cache which has data that expires after a given period of time.\"\"\"\nfrom datetime import datetime, timedelta\n\nclass KeyExpiredError(KeyError): pass \n\ndef __hax():\n class NoArg: pass\n return NoArg()\nNoArg = __hax()...
[ 9, 8, 3, 1, 1, 0 ]
[]
[]
[ "arrays", "python", "variables" ]
stackoverflow_0003927166_arrays_python_variables.txt
Q: How to setup springpython with Jython and Eclipse/PyDev? I'm having trouble setting up SpringPython with PyDev and Jython I've installed Spring python by: jython setup.py install and the setup installed the library to my jython installation successfully. See!: In my PyDev project i've selected the jython interp...
How to setup springpython with Jython and Eclipse/PyDev?
I'm having trouble setting up SpringPython with PyDev and Jython I've installed Spring python by: jython setup.py install and the setup installed the library to my jython installation successfully. See!: In my PyDev project i've selected the jython interpreter and have c:\jython2.5.1\Lib\site-packages in my Library ...
[ "The python interpreter that is used to compile your Python files is specified by PyDev on the project level. I suspect that while you do have Jython installed, your Eclipse project (katas) still uses CPython.\nPerform the following steps to fix this:\n\nOpen your project properties: right-click your project folder...
[ 1, 1 ]
[]
[]
[ "jython", "pydev", "python", "spring" ]
stackoverflow_0003921191_jython_pydev_python_spring.txt
Q: How to list an image sequence in an efficient way? Numercial sequence comparison in Python I have a directory of 9 images: image_0001, image_0002, image_0003 image_0010, image_0011 image_0011-1, image_0011-2, image_0011-3 image_9999 I would like to be able to list them in an efficient way, like this (4 entries f...
How to list an image sequence in an efficient way? Numercial sequence comparison in Python
I have a directory of 9 images: image_0001, image_0002, image_0003 image_0010, image_0011 image_0011-1, image_0011-2, image_0011-3 image_9999 I would like to be able to list them in an efficient way, like this (4 entries for 9 images): (image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999) Is there a way i...
[ "Here is a working implementation of what you want to achieve, using the code you added as a starting point:\n#!/usr/bin/env python\n\nimport itertools\nimport re\n\n# This algorithm only works if DATA is sorted.\nDATA = [\"image_0001\", \"image_0002\", \"image_0003\",\n \"image_0010\", \"image_0011\",\n ...
[ 6, 3, 2 ]
[]
[]
[ "glob", "python", "regex" ]
stackoverflow_0003926936_glob_python_regex.txt
Q: Compare Python Web Frameworks and their respective HTML5 APIs Implementations If you are familiar with a specific python web framework that has implementations for HTML5 API(s) ie.WebSockets, Forms, WebWorkers, WebStorage, Communication, Geolocation, Canvas, etc. Then please list the name of the framework and its ...
Compare Python Web Frameworks and their respective HTML5 APIs Implementations
If you are familiar with a specific python web framework that has implementations for HTML5 API(s) ie.WebSockets, Forms, WebWorkers, WebStorage, Communication, Geolocation, Canvas, etc. Then please list the name of the framework and its HTML5 capabilities.
[ "If you prefer writing your client code in Python, check out Pyjamas.\nI'm sorry, I haven't looked into its HTML5 capabilities.\n" ]
[ 0 ]
[]
[]
[ "django", "html", "python", "tornado", "web_applications" ]
stackoverflow_0003841983_django_html_python_tornado_web_applications.txt
Q: Documenting Python scripts for non-programmers We are currently looking for ways to help the non-programming members of the sysadmin group familiarize themselves with Python scripts used for day-to-day sysadmin tasks. Does anyone have any suggested documentation tools or best practices that we might find useful fo...
Documenting Python scripts for non-programmers
We are currently looking for ways to help the non-programming members of the sysadmin group familiarize themselves with Python scripts used for day-to-day sysadmin tasks. Does anyone have any suggested documentation tools or best practices that we might find useful for this purpose? Edit to address S.Lott's comment: Fi...
[ "There is a book on this subject - \"Python for Unix and Linux System Administration\".\n\nhttp://oreilly.com/catalog/9780596515829\n\nAnd an article on developer works which might provide you the flavor that you may want to follow.\n\nhttp://www.ibm.com/developerworks/aix/library/au-python/\n\nAnd almost any one, ...
[ 2, 2 ]
[]
[]
[ "documentation_generation", "python" ]
stackoverflow_0003928021_documentation_generation_python.txt
Q: lxml cleaner with a custom tag? I want to use lxml cleaner to get rid of all html, but then a regex to autolink something: [ABC] -> <a href="bah bah bah">ABC</a> what is the right way to handle this without xss and such? A: Maybe using markdown with inline HTML disabled would be suitable? The python markdown m...
lxml cleaner with a custom tag?
I want to use lxml cleaner to get rid of all html, but then a regex to autolink something: [ABC] -> <a href="bah bah bah">ABC</a> what is the right way to handle this without xss and such?
[ "Maybe using markdown with inline HTML disabled would be suitable? The python markdown module is quite mature.\nCheck out the \"safe mode\" section in the docs for more info on stripping out inline HTML.\nDepending on what you want, something like py-wikimarkup may be more appropriate.\nUsing a custom regexp is pr...
[ 1 ]
[]
[]
[ "lxml", "python", "xss" ]
stackoverflow_0003928060_lxml_python_xss.txt
Q: String Comparison with a Format - Python I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this %d/%m/%y %H:%M Is there any way i can compare string input with the above format in python? A: import time time.strptime("01/01/09 12:23"...
String Comparison with a Format - Python
I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this %d/%m/%y %H:%M Is there any way i can compare string input with the above format in python?
[ "import time\ntime.strptime(\"01/01/09 12:23\", \"%d/%m/%y %H:%M\")\n\nThis will raise ValueError if the string doesn't match:\ntime.strptime(\"01/01/09 12:234\", \"%d/%m/%y %H:%M\")\ntime.strptime(\"01-01-09 12:23\", \"%d/%m/%y %H:%M\")\n\nBy the way, please don't bring back two-digit years--use %Y if at all possi...
[ 8, 2 ]
[]
[]
[ "comparison", "python", "string" ]
stackoverflow_0003928999_comparison_python_string.txt
Q: AES encryption library compatible with Python 2.7 for Windows Any recommendations on an AES encryption library that's compatible with Python 2.7 for Windows? In the past we've used m2crypto with Python 2.6, but there's no version of m2crypto for Python 2.7 and our attempts to build a version from source have faile...
AES encryption library compatible with Python 2.7 for Windows
Any recommendations on an AES encryption library that's compatible with Python 2.7 for Windows? In the past we've used m2crypto with Python 2.6, but there's no version of m2crypto for Python 2.7 and our attempts to build a version from source have failed. Thank you, Malcolm
[ "Actually, the M2Crypto package supports Python 2.7 just fine — I have been using it in a cryptography-heavy application with no problem. I suppose the problem here is that Windows does not come with a compiler, so you cannot easily install the .tar.gz off of PyPI? Or are you getting an error when you try to compil...
[ 2, 1 ]
[]
[]
[ "cryptography", "m2crypto", "python", "python_2.7" ]
stackoverflow_0003859623_cryptography_m2crypto_python_python_2.7.txt
Q: rounding-up numbers within a tuple Is there anyway I could round-up numbers within a tuple to two decimal points, from this: ('string 1', 1234.55555, 5.66666, 'string2') to this: ('string 1', 1234.56, 5.67, 'string2') Many thanks in advance. A: If your tuple has a fixed size of 4 and the position of the floats...
rounding-up numbers within a tuple
Is there anyway I could round-up numbers within a tuple to two decimal points, from this: ('string 1', 1234.55555, 5.66666, 'string2') to this: ('string 1', 1234.56, 5.67, 'string2') Many thanks in advance.
[ "If your tuple has a fixed size of 4 and the position of the floats is always the same, you can do this:\n>>> t = ('string 1', 1234.55555, 5.66666, 'string2')\n>>> t2 = (t[0], round(t[1], 2), round(t[2], 2), t[3])\n>>> t2\n('string 1', 1234.56, 5.67, 'string2')\n\nThe general solution would be:\n>>> t2 = tuple(map(...
[ 14, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003928523_python.txt
Q: How to print the top 10 users by the number of processes? How could I print the top 10 users on a linux distribution by the number of processes they have running? I have managed to do this using a shell script, but now I'm interested at how I can do this using Python. A: Parsing the output of ps aux is not very ...
How to print the top 10 users by the number of processes?
How could I print the top 10 users on a linux distribution by the number of processes they have running? I have managed to do this using a shell script, but now I'm interested at how I can do this using Python.
[ "Parsing the output of ps aux is not very pleasant, and can be tricky because the format is not guaranteed to be the same on all Linux systems. \nInstalling a third-party tool like psutil or PSI should make things easy and portable. \nIf you are looking for a Linux-only solution without installing a third-party mo...
[ 2 ]
[]
[]
[ "linux", "process", "python" ]
stackoverflow_0003928959_linux_process_python.txt
Q: Importing nested modules in Python I'm trying to import a few libraries into my program (which is a google AppEngine application). Basically, I'm supposed to put all libraries in the root folder, but I've just created another folder called lib and placed them within that folder. (I've created the __init__.py) Im...
Importing nested modules in Python
I'm trying to import a few libraries into my program (which is a google AppEngine application). Basically, I'm supposed to put all libraries in the root folder, but I've just created another folder called lib and placed them within that folder. (I've created the __init__.py) Imports regularly work fine by using the i...
[ "I think that instead of from pack1.mod2 you actually want to say from lib.pack1.mod2.\nEdit: and, specifying what version of Python this is would help, since importation semantics have improved gradually over the years!\nEdit: Aha! Thank you for your comment; I now understand. You are trying to rename libraries wi...
[ 6 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003929228_import_module_python.txt
Q: Is it possible to use reflection to examine a function's decorators in Python 2.5? This is what i want to do: @MyDecorator def f(): pass for d in f.decorators: print d A: This is not generally possible without the cooperation of the decorators. For example, def my_decorator(f): def wrapper(*args, **k...
Is it possible to use reflection to examine a function's decorators in Python 2.5?
This is what i want to do: @MyDecorator def f(): pass for d in f.decorators: print d
[ "This is not generally possible without the cooperation of the decorators. For example,\ndef my_decorator(f):\n def wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n wrapper.decorators = [wrapper]\n if hasattr(f, 'decorators'):\n wrapper.decorators.extend[f.decorators]\n return...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003929317_python.txt
Q: Subprocess module errors with 'export' in python on linux? I'm setting up a program to connect my computer to our schools proxy and currently have something like this: import subprocess import sys username = 'fergus.barker' password = '*************' proxy = 'proxy.det.nsw.edu.au:8080' options = '%s:%s@%s' % (use...
Subprocess module errors with 'export' in python on linux?
I'm setting up a program to connect my computer to our schools proxy and currently have something like this: import subprocess import sys username = 'fergus.barker' password = '*************' proxy = 'proxy.det.nsw.edu.au:8080' options = '%s:%s@%s' % (username, password, proxy) subprocess.Popen('export http_proxy=' +...
[ "The problem is that export is not an actual command or file. It is a built-in command to shells like bash and sh, so when you attempt a subprocess.Popen you will get an exception because it can not find the export command. By default Popen does an os.execvp() to spawn a new process, which would not allow you to us...
[ 11, 5 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003929319_python_subprocess.txt
Q: UTF-8 compatible compression in python I'd like to include a large compressed string in a json packet, but am having some difficulty. import json,bz2 myString = "A very large string" zString = bz2.compress(myString) json.dumps({ 'compressedData' : zString }) which will result in a UnicodeDecodeError: 'utf8' c...
UTF-8 compatible compression in python
I'd like to include a large compressed string in a json packet, but am having some difficulty. import json,bz2 myString = "A very large string" zString = bz2.compress(myString) json.dumps({ 'compressedData' : zString }) which will result in a UnicodeDecodeError: 'utf8' codec can't decode bytes in position 10-13: i...
[ "Do you mean \"compress to UTF-8 strings\"? I'll assume that, since any generic compressor will compress UTF-8 strings. However, no real-world compressor is going to compress to a UTF-8 string.\nYou can't store 8-bit data like UTF-8 directly in JSON, because JSON strings are defined as Unicode. You'd have to bas...
[ 11 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0003929301_python_utf_8.txt
Q: python for loop, how to find next value(object)? HI, I'm trying to use for loop to find the difference between every two object by minus each other. So, how can I find the next value in a for loop? for entry in entries: first = entry # Present value last = ?????? # The last value how to say? ...
python for loop, how to find next value(object)?
HI, I'm trying to use for loop to find the difference between every two object by minus each other. So, how can I find the next value in a for loop? for entry in entries: first = entry # Present value last = ?????? # The last value how to say? diff = last = first
[ "It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.\nuse zip for small lists:\n for current, last in zip(entries[1:], entries):\n diff = current - last\n\nThis makes a copy of the list (and a list of tuples from both copies of the list) so it's go...
[ 12, 6, 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0003929039_for_loop_python.txt
Q: Subclassing file class in Python raises NameError I have to do a very simple project in python where I add error checking to the built in file class. So far, I've got: class RobustFile(file): def __init__(self,name,mode): file.__init__(self,name,mode) I'm just starting out, but to make sure I hadn't ...
Subclassing file class in Python raises NameError
I have to do a very simple project in python where I add error checking to the built in file class. So far, I've got: class RobustFile(file): def __init__(self,name,mode): file.__init__(self,name,mode) I'm just starting out, but to make sure I hadn't messed anything up, I ran it. Well, right off the bat,...
[ "You're probably using Python 3, which no longer has a file type.\nInstead, as noted in the Python 3 documentation's I/O Overview, it has a number of different stream types that are all derived from one of _io.TextIOBase, _io.BufferedIOBase, or _io.RawIOBase, which are themselves derived from _io.IOBase.\n", "Wor...
[ 7, 1 ]
[]
[]
[ "file", "python", "subclass" ]
stackoverflow_0003929646_file_python_subclass.txt
Q: Insert multiple tab-delimited text files into MySQL with Python? I am trying to create a program that takes a number of tab delaminated text files, and works through them one at a time entering the data they hold into a MySQL database. There are several text files, like movies.txt which looks like this: 1 Avatar...
Insert multiple tab-delimited text files into MySQL with Python?
I am trying to create a program that takes a number of tab delaminated text files, and works through them one at a time entering the data they hold into a MySQL database. There are several text files, like movies.txt which looks like this: 1 Avatar 3 Iron Man 3 Star Trek and actors.txt that looks the same etc. E...
[ "MySQL can read TSV files directly using the mysqlimport utility or by executing the LOAD DATA INFILE SQL command. This will be faster than processing the file in python and inserting it, but you may want to learn how to do both. Good luck!\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003929297_mysql_python.txt
Q: Python Unicode CSV export (using Django) I'm using a Django app to export a string to a CSV file. The string is a message that was submitted through a front end form. However, I've been getting this error when a unicode single quote is provided in the input. UnicodeEncodeError: 'ascii' codec can't encode chara...
Python Unicode CSV export (using Django)
I'm using a Django app to export a string to a CSV file. The string is a message that was submitted through a front end form. However, I've been getting this error when a unicode single quote is provided in the input. UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 200: ordinal not...
[ "You can't encode the Unicode character u'\\u2019' (U+2019 Right Single Quotation Mark) into ASCII, because ASCII doesn't have that character in it. ASCII is only the basic Latin alphabet, digits and punctuation; you don't get any accented letters or ‘smart quotes’ like this character.\nSo you will have to choose a...
[ 7, 2, 1 ]
[]
[]
[ "ascii", "csv", "python", "unicode", "utf_8" ]
stackoverflow_0003929327_ascii_csv_python_unicode_utf_8.txt
Q: password fetch using python import pwd import operator # Load all of the user data, sorted by username all_user_data = pwd.getpwall() interesting_users = sorted((u for u in all_user_data if not u.pw_name.startswith('_')), key=op...
password fetch using python
import pwd import operator # Load all of the user data, sorted by username all_user_data = pwd.getpwall() interesting_users = sorted((u for u in all_user_data if not u.pw_name.startswith('_')), key=operator.attrgetter('pw_name')) # ...
[ "Look at wtmp and utmp. There are APIs - check man wtmp\n" ]
[ 1 ]
[]
[]
[ "linux", "passwords", "python" ]
stackoverflow_0003873128_linux_passwords_python.txt
Q: Twitter Authentication Questions I have two questions (does that violate etiquette?) surrounding Twitter authentication. The first question is this. I'd like to store the access token that I receive but it is a dictionary object. Do I store the whole dictionary object or just some of the pertinent parts. Secondly ...
Twitter Authentication Questions
I have two questions (does that violate etiquette?) surrounding Twitter authentication. The first question is this. I'd like to store the access token that I receive but it is a dictionary object. Do I store the whole dictionary object or just some of the pertinent parts. Secondly I'd like to know how to log the user o...
[ "What you need to understand is that the OAuth protocol does not define \"login\" and \"logout\" concepts, those are inherent to your application. OAuth is a protocol to allow a consumer (your application) to access a resource owner's (one of your users) data stored by a resource provider (in this case, Twitter).\n...
[ 2, 1 ]
[]
[]
[ "oauth", "python", "twitter" ]
stackoverflow_0003929990_oauth_python_twitter.txt
Q: PyObjc vs RubyCocoa for Mac development: Which is more mature? I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming. So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objec...
PyObjc vs RubyCocoa for Mac development: Which is more mature?
I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming. So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa). I know that ideally to get the ...
[ "While you say you \"don't have time\" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time pickin...
[ 12, 7, 3, 1, 1 ]
[]
[]
[ "cocoa", "pyobjc", "python", "ruby", "ruby_cocoa" ]
stackoverflow_0000426607_cocoa_pyobjc_python_ruby_ruby_cocoa.txt
Q: 500 Error when sending file from python to django I've found a nice python module for sending data to remote servers via HTTP POST called poster. So I've wrote a simple view on my django app to receive and store data and then tried to send some file. Unfortunately even though I've set everything as it was shown in...
500 Error when sending file from python to django
I've found a nice python module for sending data to remote servers via HTTP POST called poster. So I've wrote a simple view on my django app to receive and store data and then tried to send some file. Unfortunately even though I've set everything as it was shown in the instruction I'm getting Internal Server Error. Can...
[ "This is a basic Python question. You need to import a module before you can use it. So just do import urllib at the top of the script and it should work.\n" ]
[ 3 ]
[]
[]
[ "django", "file_upload", "http", "python" ]
stackoverflow_0003928950_django_file_upload_http_python.txt
Q: Localization of Django application only applies to forms.py and not to models.py I have a problem when trying to localize my application. It is available in two languages: english and german. The problem appears when the browser has the language set english(United States) and in my settings file is set to 'de' and...
Localization of Django application only applies to forms.py and not to models.py
I have a problem when trying to localize my application. It is available in two languages: english and german. The problem appears when the browser has the language set english(United States) and in my settings file is set to 'de' and vice-versa. Some fields appear in english, others in german. My model contains CharFi...
[ "Changing the declaration \"from django.utils.translation import ugettext as _\" to \"from django.utils.translation import ugettext_lazy as _\" seems to solve the problem.\n", "Doublecheck your .po file: it shouldn't have any 'fuzzy' status.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "localization", "modelform", "models", "python" ]
stackoverflow_0003905690_django_localization_modelform_models_python.txt
Q: Monkey patching a Django form class? Given a form class (somewhere deep in your giant Django app).. class ContactForm(forms.Form): name = ... surname = ... And considering you want to add another field to this form without extending or modifying the form class itself, why does not the following approach ...
Monkey patching a Django form class?
Given a form class (somewhere deep in your giant Django app).. class ContactForm(forms.Form): name = ... surname = ... And considering you want to add another field to this form without extending or modifying the form class itself, why does not the following approach work? ContactForm.another_field = forms.Ch...
[ "Some pertinent definitions occur in django/forms/forms.py. They are:\n\nclass BaseForm\nclass Form\nclass DeclarativeFieldsMetaclass\ndef get_declared_fields\n\nget_declared_fields is called from DeclarativeFieldsMetaclass and constructs a list with the field instances sorted by their creation counter. It then pre...
[ 9 ]
[]
[]
[ "django", "django_forms", "monkeypatching", "python" ]
stackoverflow_0003930512_django_django_forms_monkeypatching_python.txt
Q: In python, any elegant way to refer to class method within the classes declaration scope? The below code works both under Python 2.6 and 3.1, but the third lambda of SomeObject.columns is a bit silly, serving no real purpose but to prevent the reference to SomeObject.helper_function from being looked at before the...
In python, any elegant way to refer to class method within the classes declaration scope?
The below code works both under Python 2.6 and 3.1, but the third lambda of SomeObject.columns is a bit silly, serving no real purpose but to prevent the reference to SomeObject.helper_function from being looked at before the class declaration finishes. It seems like a hack. If I remove the lambda, and replace it with ...
[ "There's no way to refer to the class that's currently being defined. There should really be keywords referring to the current scope, eg. __this_class__ for the innermost class being defined and __this_func__ for the innermost function, so classes and functions can cleanly refer to themselves without having to rep...
[ 4, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003929582_python.txt
Q: Python - Applying Two's Complement to a String I am trying to add the Two's Complement to a Binary number represented with a string. Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed? Example: 100010 is fl...
Python - Applying Two's Complement to a String
I am trying to add the Two's Complement to a Binary number represented with a string. Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed? Example: 100010 is flipped to 011101, and is represented as a string. How...
[ "I'd just do it as a number, then convert it back.\ndef tobin(x, count=8):\n # robbed from http://code.activestate.com/recipes/219300/\n return \"\".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))\n\ndef twoscomp(num_str):\n return tobin(-int(num_str,2),len(num_str))\n\nprint twoscomp('01001001')...
[ 2, 2, 1 ]
[]
[]
[ "python", "twos_complement" ]
stackoverflow_0003920873_python_twos_complement.txt