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: How to test interrupted POST handling I am trying to reproduce a bug that is introduced by interrupted multipart POST. Thus, I'd like to do something along the lines of curl -F 'item_count=8' -A 'Agent/4.0' http://tld/post/uri but interrupt the request when data are send. Arbitrary Ctrl+C is obviously not optimal...
How to test interrupted POST handling
I am trying to reproduce a bug that is introduced by interrupted multipart POST. Thus, I'd like to do something along the lines of curl -F 'item_count=8' -A 'Agent/4.0' http://tld/post/uri but interrupt the request when data are send. Arbitrary Ctrl+C is obviously not optimal. Any tools that support that (except manua...
[ "Spawn a thread and kill it almost immediately from the parent?\n" ]
[ 0 ]
[]
[]
[ "apache2", "integration_testing", "mod_wsgi", "python", "testing" ]
stackoverflow_0007497945_apache2_integration_testing_mod_wsgi_python_testing.txt
Q: How to get (childless) “tabs” in a pygtk application I am facing the problem to need tabs in a pygtk app. Pretty much just like gedit has, but without any per-child widget content. I’ve come across gtk.Notebook, but that requires me to put a widget for each tab, which I don't want. The reason is, that I have one w...
How to get (childless) “tabs” in a pygtk application
I am facing the problem to need tabs in a pygtk app. Pretty much just like gedit has, but without any per-child widget content. I’ve come across gtk.Notebook, but that requires me to put a widget for each tab, which I don't want. The reason is, that I have one widget, but would only like to updates its content based on...
[ "The invisble widget idea works. But not with gtk.Invisible (this just crashes), but with gtk.HBox() or any other thing that seems empty.\nself.notebook.append_page(gtk.HBox(), gtk.Label(\"title\"))\n\nNow if I want to display stuff inside the tab actually, I can use reparent to move the widget to the current tab l...
[ 2, 0 ]
[]
[]
[ "pygtk", "python", "tabs" ]
stackoverflow_0007498978_pygtk_python_tabs.txt
Q: Python: recurse through list of strings - how to tell the difference? I have the following code def printmylist( mylist ): """ print tree """ try: for f in mylist: printmylist( f ) except: print( " " + mylist ) hoping to get output like: root branch leaf ...
Python: recurse through list of strings - how to tell the difference?
I have the following code def printmylist( mylist ): """ print tree """ try: for f in mylist: printmylist( f ) except: print( " " + mylist ) hoping to get output like: root branch leaf leaf but since a string is enumerable, I get r o o t . . Checking for ty...
[ "The cleanest way that I know of is to use types.StringTypes (not to be confused with types.StringType):\nisinstance(var, types.StringTypes)\n\nAlternatively:\nisinstance(var, basestring)\n\nDocumentation for the types module indicates that the latter is the preferred way in recent versions of Python 2.x.\n", "I ...
[ 5, 1 ]
[ "The simplest one is if type(f) == str\nSometimes it's better to use if's than exceptions.\nEDIT:\nDue to larsmans comment, I don't recommend this option. It is useful in simple usage, but in professional coding it is better to use isinstance.\n" ]
[ -1 ]
[ "enumerable", "list", "python", "string", "types" ]
stackoverflow_0007499552_enumerable_list_python_string_types.txt
Q: Split text using Python Possible Duplicate: Python split string on regex How do I split some text using Python's re module into two parts: the text before a special word cut and the rest of the text following it. A: You can do it with re: >>> import re >>> re.split('cut', s, 1) # Split only once. But in this ...
Split text using Python
Possible Duplicate: Python split string on regex How do I split some text using Python's re module into two parts: the text before a special word cut and the rest of the text following it.
[ "You can do it with re:\n>>> import re\n>>> re.split('cut', s, 1) # Split only once.\n\nBut in this case you can just use str.split:\n>>> s.split('cut', 1) # Split only once.\n\n", "Check this, might help you\n>>> re.compile('[0-9]+').split(\"hel2l3o\")\n['hel', 'l', 'o']\n>>> \n\n>>> re.compile('cut').split(\"he...
[ 5, 1 ]
[]
[]
[ "python", "split" ]
stackoverflow_0007499929_python_split.txt
Q: module for pcap stream in python i am trying to filter some headers off my pcap stream using python. is there a particular module to do this. help with any or suggestion would be well appreciated A: I have been using python-libpcap http://sourceforge.net/projects/pylibpcap/ If I am not mistaken, it is just a wra...
module for pcap stream in python
i am trying to filter some headers off my pcap stream using python. is there a particular module to do this. help with any or suggestion would be well appreciated
[ "I have been using python-libpcap\nhttp://sourceforge.net/projects/pylibpcap/\nIf I am not mistaken, it is just a wrapper to the C libpcap. It doesn't feel very Pythonic, but it gets the job done.\nEdit:\nHowever, this will just let you separate the packets. There isn't much parsing of the headers. I failed to find...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003165879_python.txt
Q: How to determing if a file has finished downloading in python I have a folder called raw_files. Very large files (~100GB files) from several sources will be uploaded to this folder. I need to get file information from videos that have finished uploading to the folder. What is the best way to determine if a file i...
How to determing if a file has finished downloading in python
I have a folder called raw_files. Very large files (~100GB files) from several sources will be uploaded to this folder. I need to get file information from videos that have finished uploading to the folder. What is the best way to determine if a file is currently being downloaded to the folder (pass) or if the video h...
[ "The most reliable way is to modify the uploading software if you can.\nA typical scheme would be to first upload each file into a temporary directory on the same filesystem, and move to the final location when the upload is finished. Such a \"move\" operation is cheap and atomic.\nA variation on this theme is to u...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007500004_python.txt
Q: How do I interpret the return from posix_ipc::MessageQueue::receive()? I'm using Philip Semanchunk's posix_ipc python module to read from a posix message queue. A C++ program I've written populates the queue with a struct containing the data. My python program successfully reads the message off the queue but I'm...
How do I interpret the return from posix_ipc::MessageQueue::receive()?
I'm using Philip Semanchunk's posix_ipc python module to read from a posix message queue. A C++ program I've written populates the queue with a struct containing the data. My python program successfully reads the message off the queue but I'm not sure what to do with the resulting message. doing a print msg just prin...
[ "Use the Python struct module.\nstruct::unpack() will translate the hex string from MessageQueue::receive() into a tuple of strings\n" ]
[ 1 ]
[]
[]
[ "message_queue", "posix", "python" ]
stackoverflow_0007485830_message_queue_posix_python.txt
Q: transfer files from ssh server directly to client i have a ssh server which is use to store my files online. i need to make those file available for download easily so i am using paramiko library to connect to the ssh server (from my python script), it then lists files and displays on the webpage. the problem is t...
transfer files from ssh server directly to client
i have a ssh server which is use to store my files online. i need to make those file available for download easily so i am using paramiko library to connect to the ssh server (from my python script), it then lists files and displays on the webpage. the problem is that i dont want to download the files to the web server...
[ "Not a programmer's answer: instead of paramiko, mount the directory with documents with sshfs and serve the documents as if they were on the local file system\nhttp://fuse.sourceforge.net/sshfs.html\n", "A cgi script generates output on stdout which is delivered to the webserver. The output starts with header li...
[ 1, 0 ]
[]
[]
[ "http", "python", "scp", "ssh", "web" ]
stackoverflow_0007498336_http_python_scp_ssh_web.txt
Q: Autogenerate dummy documentation in the source code for Python in eclipse At the time I am documenting a lot of my code (Python) and I was wondering if there is a plugin to Eclipse that can automatically generate a doc string for my functions, like visual studio does it for C# when writing /// over a method. I hav...
Autogenerate dummy documentation in the source code for Python in eclipse
At the time I am documenting a lot of my code (Python) and I was wondering if there is a plugin to Eclipse that can automatically generate a doc string for my functions, like visual studio does it for C# when writing /// over a method. I have been searching around for a solution, but I had no luck - do any of you know ...
[ "Well, according to this doc, if you press Ctrl + 1 on a method name, you will get what you need.\nFor your example (EDIT : if you set the option PyDev>Editor>Code Style>Docstrings>Doctag generation to always to get the type of the param), you will get : \ndef myFunction(self, a, b):\n '''\n\n @param a:\n ...
[ 7 ]
[]
[]
[ "documentation", "eclipse", "plugins", "pydev", "python" ]
stackoverflow_0007500615_documentation_eclipse_plugins_pydev_python.txt
Q: Combining file permissions I want to set executable permissions for a file I have created in python. If I do os.chmod(file, stat.S_IXUSR), the existing permissions are overwritten. How do I combine the existing permissions for the file with executable permissions? A: stat it first. mode = os.stat(filename).st_m...
Combining file permissions
I want to set executable permissions for a file I have created in python. If I do os.chmod(file, stat.S_IXUSR), the existing permissions are overwritten. How do I combine the existing permissions for the file with executable permissions?
[ "stat it first.\nmode = os.stat(filename).st_mode\nos.chmod(filename, mode | stat.S_IXUSR)\n\n" ]
[ 6 ]
[ "Probably just with\n os.system('chmod %d \"%s\"' % (\"+x\", file))\n\nshould do the trick\n" ]
[ -1 ]
[ "file", "permissions", "python" ]
stackoverflow_0007500840_file_permissions_python.txt
Q: Can I stop an executable from requesting UAC elevation? I have an installer I'd like to run from a script. The installer requests UAC elevation but it doesn't need elevation because I'm installing to a user directory. Is there some way to run the installer so that it doesn't request UAC elevation? The script is ...
Can I stop an executable from requesting UAC elevation?
I have an installer I'd like to run from a script. The installer requests UAC elevation but it doesn't need elevation because I'm installing to a user directory. Is there some way to run the installer so that it doesn't request UAC elevation? The script is written in Python so I can access the Windows API through cty...
[ "You have to set the enviromnet variable __compat_layer for your process to RunAsInvoker. Then you can run the executable without any UAC prompt.\nYou can use the Windows API function SetEnvironmentVariable for this purpose.\n" ]
[ 4 ]
[]
[]
[ "python", "uac", "winapi", "windows" ]
stackoverflow_0007086978_python_uac_winapi_windows.txt
Q: How to set vim to unindent when meets a empty line in Python? It could be useful if vim could do a unindentation automatically when I type an empty line, but it seems it is not the default behavior. This would especially useful for Python, could Vim be configured to do so? A: I made some mods to my own indent/p...
How to set vim to unindent when meets a empty line in Python?
It could be useful if vim could do a unindentation automatically when I type an empty line, but it seems it is not the default behavior. This would especially useful for Python, could Vim be configured to do so?
[ "I made some mods to my own indent/python.vim to enable full dedent when the third empty line is entered. You may be able to adapt this to your needs.\ndiff --git a/python.vim b/python.vim\nindex 0c04e81..c60c30e 100644\n--- a/python.vim\n+++ b/python.vim\n@@ -142,8 +142,14 @@ function GetPythonIndent(lnum)\n ...
[ 2 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0007500645_python_vim.txt
Q: Python array of datetime objects from numpy ndarray I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another one is time, e.g. 19:00:00:081. How can I combine them into one array of datetime objects? Currently, they're strings in numpy array. A: If the date and time string in the ex...
Python array of datetime objects from numpy ndarray
I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another one is time, e.g. 19:00:00:081. How can I combine them into one array of datetime objects? Currently, they're strings in numpy array.
[ "If the date and time string in the example.txt data file were given as one column with no separating whitespace, then genfromtxt could convert it into a datetime object like this:\nimport numpy as np\nimport datetime as dt\ndef mkdate(text):\n return dt.datetime.strptime(text, '%Y-%m-%dT%H:%M:%S:%f') \ndata ...
[ 8, 2 ]
[]
[]
[ "datetime", "numpy", "python" ]
stackoverflow_0007500864_datetime_numpy_python.txt
Q: Question with scipy.optimize I am a newbie and I need your help!! I have installed scipy on my Ubuntu. When I ran the code from scipy import optimize, special I get the following in terminal: can't read /var/mail/scipy.optimize and if I type python, and get >>> then type in from scipy import optimize then I ran c...
Question with scipy.optimize
I am a newbie and I need your help!! I have installed scipy on my Ubuntu. When I ran the code from scipy import optimize, special I get the following in terminal: can't read /var/mail/scipy.optimize and if I type python, and get >>> then type in from scipy import optimize then I ran code including scipy, optimize, I g...
[ "from scipy import optimize, special on the shell prompt starts the from command, which is an email program.\nfrom scipy import optimize, special in Python will put the modules optimize and special in your namespace, but not scipy. Either use them unqualified or do import scipy instead.\n" ]
[ 3 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0007501785_python_scipy.txt
Q: Use python to crawl a website So I am looking for a dynamic way to crawl a website and grab links from each page. I decided to experiment with Beauitfulsoup. Two questions: How do I do this more dynamically then using nested while statements searching for links. I want to get all the links from this site. But I do...
Use python to crawl a website
So I am looking for a dynamic way to crawl a website and grab links from each page. I decided to experiment with Beauitfulsoup. Two questions: How do I do this more dynamically then using nested while statements searching for links. I want to get all the links from this site. But I don't want to continue to put nested ...
[ "The problem of spidering over a web site and getting all the links is a common problem. If you Google search for \"spider web site python\" you can find libraries that will do this for you. Here's one I found:\nhttp://pypi.python.org/pypi/spider.py/0.5\nEven better, Google found this question already asked and a...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "hyperlink", "nested", "python", "web_crawler", "while_loop" ]
stackoverflow_0006769387_hyperlink_nested_python_web_crawler_while_loop.txt
Q: MongoDB not that faster than MySQL? I discovered mongodb some months ago,and after reading this post, I thought mongodb was really faster than mysql, so I decided to build my own bench, the problem is that I do not have the same result than the above post's author, especially for quering the database : mongodb see...
MongoDB not that faster than MySQL?
I discovered mongodb some months ago,and after reading this post, I thought mongodb was really faster than mysql, so I decided to build my own bench, the problem is that I do not have the same result than the above post's author, especially for quering the database : mongodb seems to be slower than MyISAM tables. Could...
[ "Sigh. These kind of benchmarks, and I use the term loosely in this case, usually break down from the very start. MySQL isn't a \"slower\" database than MongoDB. One is a relational database, the other a NoSQL document store. They will/should be faster in the functional areas that they were designed to cover. In th...
[ 31, 7, 2 ]
[]
[]
[ "mongodb", "mysql", "python" ]
stackoverflow_0007501100_mongodb_mysql_python.txt
Q: cPickle - different results pickling the same object Is anyone able to explain the comment under testLookups() in this code snippet? I've run the code and indeed what the comment sais is true. However I'd like to understand why it's true, i.e. why is cPickle outputting different values for the same object dependin...
cPickle - different results pickling the same object
Is anyone able to explain the comment under testLookups() in this code snippet? I've run the code and indeed what the comment sais is true. However I'd like to understand why it's true, i.e. why is cPickle outputting different values for the same object depending on how it is referenced. Does it have anything to do wi...
[ "There is no guarantee that seemingly identical objects will produce identical pickle strings.\nThe pickle protocol is a virtual machine, and a pickle string is a program for that virtual machine. For a given object there exist multiple pickle strings (=programs) that will reconstruct that object exactly.\nTo take ...
[ 9, 6 ]
[]
[]
[ "pickle", "python", "serialization" ]
stackoverflow_0007501577_pickle_python_serialization.txt
Q: Python function calling I have the following classes: from forwind.lidarapi.api import MCLidarGUIPlugin class MCLidarActions( Handler ): tcp_send = Event def object__updated_changed( self, info ): print info; pass; def _tcp_send_changed( self ): print( "Click" ) and fro...
Python function calling
I have the following classes: from forwind.lidarapi.api import MCLidarGUIPlugin class MCLidarActions( Handler ): tcp_send = Event def object__updated_changed( self, info ): print info; pass; def _tcp_send_changed( self ): print( "Click" ) and from forwind.lidarapi.actions.a...
[ "Here is the example of calling super()\nBeware that you need to inherit object inorder to make super works.\nclass E(object):\n def __init__(self):\n print \"enter E\"\n print \"leave E\"\n\nclass F(E):\n def __init__(self):\n print \"enter F\"\n super(F, self).__init__()\n ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007482092_python.txt
Q: How do I deal with conflicting names when building python docs with doxygen I'm having a problem with Doxygen for Windows with Python where input files with the same failename cause a conflict wth the output files. This seems to be a bug in doxygen - is there a way to work-around this problem? Background We build...
How do I deal with conflicting names when building python docs with doxygen
I'm having a problem with Doxygen for Windows with Python where input files with the same failename cause a conflict wth the output files. This seems to be a bug in doxygen - is there a way to work-around this problem? Background We build docs for our API using Doxygen. Our project is overwhelmingly written in python ...
[ "You could try explicitly declaring a class w/ full namespace\nhttp://www.doxygen.nl/manual/commands.html#cmdclass\n" ]
[ 0 ]
[]
[]
[ "doxygen", "python", "windows" ]
stackoverflow_0005090261_doxygen_python_windows.txt
Q: Anything similar to a microcontroller interrupt handler? Is there some method where one could use a try statement to catch an error caused by a raise statement, execute code to handle the flag e.g. update some variables and then return to the line where the code had been operating when the flag was raised? I am th...
Anything similar to a microcontroller interrupt handler?
Is there some method where one could use a try statement to catch an error caused by a raise statement, execute code to handle the flag e.g. update some variables and then return to the line where the code had been operating when the flag was raised? I am thinking specifically of an interrupt handler for a micro-contro...
[ "One standard OS way to handle interrupts is to enqueue the interrupt so another kernel thread can process it.\nThis partially applies in Python.\n\nI am writing some code that has a thread checking a file to see if it updates and I want it to interrupt the main program so it is aware of the update, deals with it a...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007502483_python.txt
Q: How to use native Python logging or/and Twisted logger for multiple daemon/cron scripts? I use logging to one file with different scripts of one program - such as cron tasks, twisted daemons (HttpServers with some data) etc. If I use default Python logging in base class such as import logging impor...
How to use native Python logging or/and Twisted logger for multiple daemon/cron scripts?
I use logging to one file with different scripts of one program - such as cron tasks, twisted daemons (HttpServers with some data) etc. If I use default Python logging in base class such as import logging import logging.handlers .... self.__fname = open(logname, 'a') logging.bas...
[ "I think the point is that you should not use DailyLogFile but use PythonLOggingObserver to redirect the log to standard lib log\nfrom twisted.python import log\nobserver = log.PythonLoggingObserver()\nobserver.start()\nlog.msg('%s %s \\033[0m' % (self.__colors[colortype], msg))\n\nAlso you might want to see the ex...
[ 2 ]
[]
[]
[ "daemon", "linux", "logging", "python", "twisted" ]
stackoverflow_0007502295_daemon_linux_logging_python_twisted.txt
Q: Python, mutable object as default argument, is there any way to solve? class A: def __init__(self, n=[0]): self.data = n a = A() print a.data[0] #print 0 a.data[0] +=1 b = A() print a.data[0] #print 1, desired output is 0 In the case above, is there any way to provide a default argument with the mut...
Python, mutable object as default argument, is there any way to solve?
class A: def __init__(self, n=[0]): self.data = n a = A() print a.data[0] #print 0 a.data[0] +=1 b = A() print a.data[0] #print 1, desired output is 0 In the case above, is there any way to provide a default argument with the mutable object (such as list or class) in __init__() class A, but b is not affe...
[ "You could try this:\nclass A:\n def __init__(self, n=None):\n if n is None:\n n = [0]\n self.data = n\n\nWhich avoids the biggest problem you're facing here, that is, that's the same list for every single object of your type \"A.\"\n", "One possibility is:\nclass A:\n def __init__(self, ...
[ 7, 4, 0 ]
[]
[]
[ "class", "mutable", "object", "python" ]
stackoverflow_0007502238_class_mutable_object_python.txt
Q: Getting error: AttributeError: class has no attribute '' Here is the code: 1 #!/usr/bin/env python 2 3 import re, os, sys, jira, subprocess 4 5 class Check_jira: 6 7 def verify_commit_text(self, tags): 8 for line in tags: 9 if re.match('^NO-TIK',line): 10 ...
Getting error: AttributeError: class has no attribute ''
Here is the code: 1 #!/usr/bin/env python 2 3 import re, os, sys, jira, subprocess 4 5 class Check_jira: 6 7 def verify_commit_text(self, tags): 8 for line in tags: 9 if re.match('^NO-TIK',line): 10 return True 11 elif re.match('^NO-REVIEW', lin...
[ "class Check_jira ends on line 25 and has only one method. Then you have an if block, and CheckForJiraIssueRecord is just a function defined in this block (that is, the function is defined if __name__ == '__main__'.\nJust put the if block outside after the whole class definition.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007503149_python.txt
Q: Is there a way to specify the command line width in octave? I would like to use octave as a "calculator" in a python script. Currently I am running octave like so: octave -q --eval 'some code' and read the stdout to interpret the results. However, I am running into problems once matrices reach a certain width so ...
Is there a way to specify the command line width in octave?
I would like to use octave as a "calculator" in a python script. Currently I am running octave like so: octave -q --eval 'some code' and read the stdout to interpret the results. However, I am running into problems once matrices reach a certain width so that octave starts to output them with column numerations like so...
[ "The split_long_rows () command should be able to change this behavior. From the documentation,\n\nQuery or set the internal variable that controls whether rows of a matrix may be split when displayed to a terminal window\n\n" ]
[ 1 ]
[]
[]
[ "command_line", "octave", "python" ]
stackoverflow_0007501876_command_line_octave_python.txt
Q: Python re.split() vs split() In my quests of optimization, I discovered that that built-in split() method is about 40% faster that the re.split() equivalent. A dummy benchmark (easily copy-pasteable): import re, time, random def random_string(_len): letters = "ABC" return "".join([letters[random.randint(...
Python re.split() vs split()
In my quests of optimization, I discovered that that built-in split() method is about 40% faster that the re.split() equivalent. A dummy benchmark (easily copy-pasteable): import re, time, random def random_string(_len): letters = "ABC" return "".join([letters[random.randint(0,len(letters)-1)] for i in range(...
[ "re.split is expected to be slower, as the usage of regular expressions incurs some overhead.\nOf course if you are splitting on a constant string, there is no point in using re.split().\n", "When in doubt, check the source code. You can see that Python s.split() is optimized for whitespace and inlined. But s.spl...
[ 26, 10, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007501609_python_regex.txt
Q: Python OptParser I am trying to input a path using optparser in python. Unfortunately this piece of code keeps showing an error. import optparse,os parser = optparse.OptionParser() parser.add_option("-p","--path", help = "Prints path",dest = "Input_Path", metavar = "PATH") (opts,args) =parser.parse_args() print...
Python OptParser
I am trying to input a path using optparser in python. Unfortunately this piece of code keeps showing an error. import optparse,os parser = optparse.OptionParser() parser.add_option("-p","--path", help = "Prints path",dest = "Input_Path", metavar = "PATH") (opts,args) =parser.parse_args() print os.path.isdir(opts.In...
[ "That error is because opts.Input_Path is None, instead of being your path string/unicode. \nAre you sure you are calling the script correctly? You should probably put in some error checking code in any case to make sure that if a user doesnt put -p, the program won't just crash.\nOr, change it to a positional a...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007504213_python.txt
Q: Why does SciPy return negative p-values for extremely small p-values with the Fisher-exact test? I've noticed that the Fisher-exact test in SciPy returns a negative p-value if the p-value is extrememly small: >>> import scipy as sp >>> import scipy.stats >>> x = [[48,60],[3088,17134]] >>> sp.stats.fisher_exact(x) ...
Why does SciPy return negative p-values for extremely small p-values with the Fisher-exact test?
I've noticed that the Fisher-exact test in SciPy returns a negative p-value if the p-value is extrememly small: >>> import scipy as sp >>> import scipy.stats >>> x = [[48,60],[3088,17134]] >>> sp.stats.fisher_exact(x) (4.4388601036269426, -1.5673906617053035e-11) In R, using the same 2x2 contingency table: > a = matri...
[ "Fisher's exact test uses the hypergeometric distribution.\nThe version of scipy you are using uses an implementation of the hypergeometric distribution that is not very precise. This is a known problem and has been fixed in the scipy repository.\n" ]
[ 10 ]
[]
[]
[ "python", "r", "scipy", "statistics" ]
stackoverflow_0007504198_python_r_scipy_statistics.txt
Q: How do I increase the speed of plotting in python? I have a 256x256 numpy-array of data which is constantly being changed. on every iteration I take a snapshot to make a movie. snapshot is a 3d surface plot made using matplotlib. The problem is that plotting costs me >2 seconds on every iteration which is about 60...
How do I increase the speed of plotting in python?
I have a 256x256 numpy-array of data which is constantly being changed. on every iteration I take a snapshot to make a movie. snapshot is a 3d surface plot made using matplotlib. The problem is that plotting costs me >2 seconds on every iteration which is about 600 seconds for 250 iterations. I had the same program run...
[ "For 3D plotting in general, I would advise mayavi. It can be a bit daunting at first, but it is worth the effort.\nIt is certainly much faster than matplotlib for plotting one shot of 3D data. For plotting many times with a savefig call, I'm not sure...\n", "GNUplot (accessed through it's various python interfac...
[ 2, 0, 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0007503164_matplotlib_plot_python.txt
Q: Submodule importing primary module First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything. The situation is the following: In a folder mod, I have the files __init__.py and sub.py. They contain the following data: __init__.py: print "mod" sub...
Submodule importing primary module
First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything. The situation is the following: In a folder mod, I have the files __init__.py and sub.py. They contain the following data: __init__.py: print "mod" sub.py: import __init__ print "sub" Now le...
[ "You can actually inspect what is going on by using the dictionary sys.modules. Python decides to reload a module depending on the keys in that dictionary.\nWhen you run import mod, it creates one entry, mod in sys.modules.\nWhen you run import mod.sub, after the call to import __init__, Python checks whether the k...
[ 7, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0007503748_import_module_python.txt
Q: Sorting a python dictionary by name? I have a python dictionary that I want to sort according to name: location_map_india = { 101: {'name': 'Andaman & Nicobar Islands', 'lat': 11.96, 'long': 92.69, 'radius': 294200}, 108: {'name': 'Andhra Pradesh', 'lat': 17.04, 'long': 80.09, 'radius': 294200}, ... } It do...
Sorting a python dictionary by name?
I have a python dictionary that I want to sort according to name: location_map_india = { 101: {'name': 'Andaman & Nicobar Islands', 'lat': 11.96, 'long': 92.69, 'radius': 294200}, 108: {'name': 'Andhra Pradesh', 'lat': 17.04, 'long': 80.09, 'radius': 294200}, ... } It doesn't come out the way I expect it. I trie...
[ "You are close. Try:\nlocation_map_india = sorted(location_map_india.iteritems(), key=lambda x: x[1][\"name\"])\n\nbut the result would be a list not a dict. dict is orderless.\n", "If you're using python 2.7 or superior, take a look at OrderedDict. Using it may solve your problem.\n>>> OrderedDict(sorted(d.items...
[ 6, 3, 1, 1 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0007503685_dictionary_python_sorting.txt
Q: Tkinter: one or more mainloops? I have an already large Tkinter program, so that I have an init file, where the root = Tk() window is defined (containing basically a Text widget and a few other things), some more code, and last the call to mainloop() function. Everything works, until I needed to call a procedure b...
Tkinter: one or more mainloops?
I have an already large Tkinter program, so that I have an init file, where the root = Tk() window is defined (containing basically a Text widget and a few other things), some more code, and last the call to mainloop() function. Everything works, until I needed to call a procedure before the mainloop, and I wanted to r...
[ "You are correct that mainloop needs to be called once, after your program has initialized. This is necessary to start the event loop, which is necessary for windows to draw themselves, respond to events, and so on.\nWhat you can do is break your initialization into two parts. The first -- creating the wait window ...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007499923_python_tkinter.txt
Q: django when adding data from admin interface: TypeError at admin/... unicode object not callable I'm getting an error when trying to save to the following model using the admin interface: models.py class Answer(models.Model): a = models.TextField(primary_key=True) gloss = models.TextField(blank=True) clean = mod...
django when adding data from admin interface: TypeError at admin/... unicode object not callable
I'm getting an error when trying to save to the following model using the admin interface: models.py class Answer(models.Model): a = models.TextField(primary_key=True) gloss = models.TextField(blank=True) clean = models.TextField(blank=True) count = models.IntegerField(blank=True) p = models.IntegerField(blank=True...
[ "Okay, I think I figured it out... I'm using a variable/column called \"clean\". Django's admin interface has a method called \"clean()\" also, which does some kind of validation. It appears that there was some kind of naming conflict so I changed the variable to name to \"cleaned\" and then to make sure that it...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007479548_django_python.txt
Q: Need solution to Non Egg Install of Mechanize - Py2exe fails I have racked my brain on getting Mechanize to install without an egg in Win7. I have tried the easy_install --allways-unzip method. The easy_install -Z method. Added .pth file in the site-packages directory. Added combinations of the above. Py2exe d...
Need solution to Non Egg Install of Mechanize - Py2exe fails
I have racked my brain on getting Mechanize to install without an egg in Win7. I have tried the easy_install --allways-unzip method. The easy_install -Z method. Added .pth file in the site-packages directory. Added combinations of the above. Py2exe doesn't play nice with egg files. If you have got this working, pl...
[ "If you haven't already read it there is a section on py2exe website about dealing with eggs. I don't know how effective it is (I never install eggs), and py2exe can be tricky enough without dealing with an egg installed packages. I would do the one of the following:\n\nDownload the mechanize source package, unzip ...
[ 4, 0 ]
[]
[]
[ "mechanize", "py2exe", "python" ]
stackoverflow_0007417579_mechanize_py2exe_python.txt
Q: How to call one function from within another function in python this may seem like a very basic question, but i have difficulty grasping it, and would appreciate any help. I want to be able to call CheckForJiraIssueRecord from verify_commit_text. here is the code: when i run it i get error: jira ticket regex mat...
How to call one function from within another function in python
this may seem like a very basic question, but i have difficulty grasping it, and would appreciate any help. I want to be able to call CheckForJiraIssueRecord from verify_commit_text. here is the code: when i run it i get error: jira ticket regex matched! printing m.group(1) QA-65 my_args ... QA-65 transaction abort! ...
[ "The function is being called but it's throwing an exception due to the following lines:\n32 sys.stdout = os.devnull\n33 sys.stderr = os.devnull\n\nYou are assigning a string (os.devnull) to a what should be a file handle, so when anyone writes to stdout or stder it will throw an exception due to a type err...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007504797_python.txt
Q: Pylons and zombie processes I'm trying to write an application that will allow the user to start long-running calculation processes (a few hours, for example). To do so, I use Python Popen() function. As long as the main Pylons process works fine, everything is good, but when I restart the Pylons process, it doesn...
Pylons and zombie processes
I'm trying to write an application that will allow the user to start long-running calculation processes (a few hours, for example). To do so, I use Python Popen() function. As long as the main Pylons process works fine, everything is good, but when I restart the Pylons process, it doesn't respond to any requests if the...
[ "To avoid zombie processes, the child must do a double fork to detach itself from the controlling process. See http://en.wikipedia.org/wiki/Zombie_process\nSo all you need to do is make your child process fork again - while being careful to keep the relevant file handles open so that you can still communicate.\n" ]
[ 1 ]
[ "You need some kind of message passing. This maybe done by installing a signal handler. Python has the signal module for this and Popen has a send_signal method.\nMaybe http://www.doughellmann.com/PyMOTW/subprocess/#signaling-between-processes helps you too.\n" ]
[ -1 ]
[ "multiprocessing", "pylons", "python", "zombie_process" ]
stackoverflow_0007504459_multiprocessing_pylons_python_zombie_process.txt
Q: emacs windows run python program in current buffer and display the output on output window I use the Python-mode (not the default one comes with emacs 23). I could not execute the python program currently loaded in emacs. I am getting "Symbol's function definition is void: smart-operator-mode-on" error. Any clue ...
emacs windows run python program in current buffer and display the output on output window
I use the Python-mode (not the default one comes with emacs 23). I could not execute the python program currently loaded in emacs. I am getting "Symbol's function definition is void: smart-operator-mode-on" error. Any clue or any tips makes a python program and it can be run on emacs and show the result output window?...
[ "It works after turning it off (smart-operator-mode-on)\nI need to see how to solve smart-operator-mode-on\n(setq debug-on-error t) helps me to spot the error. Thanks Noufal.\n", "I got this error fixed by downloading the smart-operator.el file into a load-path and adding require 'smart-operator' before calling ...
[ 0, 0 ]
[]
[]
[ "emacs", "python", "python_mode" ]
stackoverflow_0002032476_emacs_python_python_mode.txt
Q: creating a nested list class within python I can't figure out what I'm doing wrong. I have to create a nested list(of possible solutions to a problem), so I created a class that appends a solution to a list of existing solutions(since each solution is being calculated one at a time) This function works fine: def a...
creating a nested list class within python
I can't figure out what I'm doing wrong. I have to create a nested list(of possible solutions to a problem), so I created a class that appends a solution to a list of existing solutions(since each solution is being calculated one at a time) This function works fine: def appendList(list): #print list list2.appen...
[ "When working with a class instance the special variable self is always passed as the first argument to the method calls. You need to modify your function declaration to accommodate this:\nclass SolutionList:\n def appendList(self, list):\n #rest of your function here.\n\n", "Since you're dealing with classe...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007505566_python.txt
Q: What is the difference between Python's httplib and urllib2? Possible Duplicate: Python urllib vs httplib? I am just curious when I would want to use httplib over urllib2 and vice versa. A: Basically - httplib is lower level, while urllib is high-level. Use urllib2 whenever you just need to do something basi...
What is the difference between Python's httplib and urllib2?
Possible Duplicate: Python urllib vs httplib? I am just curious when I would want to use httplib over urllib2 and vice versa.
[ "Basically - httplib is lower level, while urllib is high-level. Use urllib2 whenever you just need to do something basic, like read the contents of a web site. Use httplib when you need to do something more crazy (hopefully rarely).\n", "You may wanna give python-requests a look instead of urllib2 if you want...
[ 3, 1 ]
[]
[]
[ "httplib", "python", "urllib", "urllib2" ]
stackoverflow_0007505559_httplib_python_urllib_urllib2.txt
Q: sendLine Won't Send integers (Twisted Python) I'm writing a MUD in Python using the Twisted library. I'm currently trying to send a integer through the sendLine method via to the LineReceiver module. However, whenever I try sending a integer I get the below error message while running my program: Unhandled Error T...
sendLine Won't Send integers (Twisted Python)
I'm writing a MUD in Python using the Twisted library. I'm currently trying to send a integer through the sendLine method via to the LineReceiver module. However, whenever I try sending a integer I get the below error message while running my program: Unhandled Error Traceback (most recent call last): File "C:\Python...
[ "so... send a string: \nself.sendLine(str(SomeVarWhichIsANumber))\n\n" ]
[ 5 ]
[]
[]
[ "mud", "network_programming", "python", "twisted" ]
stackoverflow_0007505767_mud_network_programming_python_twisted.txt
Q: Python-Remove rows based on lack of character I would like to remove a row from my file if it contains a letter other than A, C, G, or T. So that ['TC', 'CY', 'GS', 'GA', 'CT'] will become ['TC', 'GA', 'CT']. The files will have an unknown number of rows and will contain patterns of 2 or more letters in any orde...
Python-Remove rows based on lack of character
I would like to remove a row from my file if it contains a letter other than A, C, G, or T. So that ['TC', 'CY', 'GS', 'GA', 'CT'] will become ['TC', 'GA', 'CT']. The files will have an unknown number of rows and will contain patterns of 2 or more letters in any order. In addition, I do not know the other letters th...
[ "How about this, as a one liner:\nvalid = [l.strip() for l in fh if all(c in 'ACGT' for c in l.strip())]\n\nwhere fh is your file handle.\n", "You can solve it with a simple regular expression and a list comprehension.\n>>> import re\n>>> data = ['TC', 'CY', 'GS', 'GA', 'CT']\n>>> [x for x in data if re.match(r'^...
[ 3, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007505775_python.txt
Q: Object not in the right state; which exception is appropriate? Say I have a class Rocket(object): def __init__(self): self.ready = False def prepare_for_takeoff(self): self.ready = True def takeoff(self): if not self.ready: raise NotReadyException("not ready!") ...
Object not in the right state; which exception is appropriate?
Say I have a class Rocket(object): def __init__(self): self.ready = False def prepare_for_takeoff(self): self.ready = True def takeoff(self): if not self.ready: raise NotReadyException("not ready!") print("Liftoff!") Now, which of the standard exceptions would ...
[ "\nNow, which of the standard exceptions would be most appropriate to derive NotReadyException from?\n\nException\nDon't mess with anything else. \nhttp://code.google.com/p/soc/wiki/PythonStyleGuide#Exceptions\nWhat are your use cases for exception handling? \nIf you derived your exception from, say ValueError, wo...
[ 7, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0007505941_exception_python.txt
Q: Query Python dictionary to get value from tuple Let's say that I have a Python dictionary, but the values are a tuple: E.g. dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)} and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ...
Query Python dictionary to get value from tuple
Let's say that I have a Python dictionary, but the values are a tuple: E.g. dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)} and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above. I could do so using .i...
[ "Just keep indexing:\n>>> D = {\"Key1\": (1,2,3), \"Key2\": (4,5,6)}\n>>> D[\"Key2\"][2]\n6\n\n", "Use tuple unpacking:\nfor key, (valX, valY, valZ) in dict.iteritems():\n ...\n\nOften people use\nfor key, (_, _, valZ) in dict.iteritems():\n ...\n\nif they are only interested in one item of the tuple....
[ 15, 6, 1 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0007504081_dictionary_python_tuples.txt
Q: Relations on composite keys using sqlalchemy I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas? from sqlalchemy import create_engine, ForeignKey, Column, String, Integer from sqlalchemy.orm import relationship, sessionma...
Relations on composite keys using sqlalchemy
I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas? from sqlalchemy import create_engine, ForeignKey, Column, String, Integer from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declara...
[ "The problem is that you have defined each of the dependent columns as foreign keys separately, when that's not really what you intend, you of course want a composite foreign key. Sqlalchemy is responding to this by saying (in a not very clear way), that it cannot guess which foreign key to use (firstName or lastN...
[ 100 ]
[]
[]
[ "composite", "database_relations", "key", "python", "sqlalchemy" ]
stackoverflow_0007504753_composite_database_relations_key_python_sqlalchemy.txt
Q: Checking for unique output in Python I came across a fun math problem yesterday and have it solved, but with the code I wrote, I had to do a keyboard interrupt or it would run forever, lol. So I changed it to have an end condition, but now it only prints 1 solution and stops. The problem goes like this: "You have...
Checking for unique output in Python
I came across a fun math problem yesterday and have it solved, but with the code I wrote, I had to do a keyboard interrupt or it would run forever, lol. So I changed it to have an end condition, but now it only prints 1 solution and stops. The problem goes like this: "You have the numbers 123456789, in that order. Bet...
[ "Don't use random, enumerate all possible operator combinations (well, you can cut the search space a bit, if the first couple of numbers the result is larger than 2002, there is no way the result is going to be smaller). itertools is your friend.\nIf you do that, your program will finish in no time.\nIf you know t...
[ 8, 5, 3, 3, 2 ]
[]
[]
[ "puzzle", "python" ]
stackoverflow_0007506264_puzzle_python.txt
Q: How can I capture this through a regex? I have some text like this: ABCPQR01 is not at all good EFHSTU39 is somewhat nicer and I want to capture the ABC... and EFH... type words. The first set of three letters can be ABC or EFH and the second set of three letters can be PQR or STU. Instead of writing two separate...
How can I capture this through a regex?
I have some text like this: ABCPQR01 is not at all good EFHSTU39 is somewhat nicer and I want to capture the ABC... and EFH... type words. The first set of three letters can be ABC or EFH and the second set of three letters can be PQR or STU. Instead of writing two separate regexes to capture these two text elements, ...
[ ">>> re.match('(ABC|EFH)(PQR|STU)', 'ABCPQR01 is not at all good').groups()\n('ABC', 'PQR')\n\n", "I think this would be a pattern which would work :)\n>>> re.compile(\"^(ABC|EFH)(PQR|STU)\\d\\d\\b\")\n\nalso you can test it at http://www.regextester.com/index2.html\n" ]
[ 6, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007506628_python_regex.txt
Q: Convert ASCII characters to hex escaped strings I was reading in a file from Python. I opened this file and used 'rb' to read the bytes. When I read them off, say: f.read(1) it would output something like this b'\x50' So my question is, when I tried a longer string like this f.read(24) I got this: b'R\x00S\x00S...
Convert ASCII characters to hex escaped strings
I was reading in a file from Python. I opened this file and used 'rb' to read the bytes. When I read them off, say: f.read(1) it would output something like this b'\x50' So my question is, when I tried a longer string like this f.read(24) I got this: b'R\x00S\x00S\x00Q\x00S\x00O\x00N\x00P\x00S\x00M\x00R\x00P\x00 Yo...
[ "print(''.join('\\\\x%02x' % c for c in B))\n\n" ]
[ 6 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0007506717_python_struct.txt
Q: Can I declare a class within a function in Python? How can I define class Options inside of my CheckForJiraIssueRecord function? def CheckForJiraIssueRecord(object): #sys.stdout = open(os.devnull) #sys.stderr = open(os.devnull) class Options: pass options = Options() options.user = 'u...
Can I declare a class within a function in Python?
How can I define class Options inside of my CheckForJiraIssueRecord function? def CheckForJiraIssueRecord(object): #sys.stdout = open(os.devnull) #sys.stderr = open(os.devnull) class Options: pass options = Options() options.user = 'user' options.password = 'password' try: ...
[ "Yes, just correct your indentation and that code should work. You'll be creating a new class each time the function is called.\ndef CheckForJiraIssueRecord(object):\n class Options:\n pass\n options = Options()\n\n options.user = 'user'\n options.password = 'password'\n\n", "Yes, you can. Alt...
[ 6, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007506523_python.txt
Q: Finding words from Wordnet separated by a fixed Edit Distance from a given word I am writing a spell checker using nltk and wordnet, I have a few wrongly spelt words say "belive". What I want to do is find all words from wordnet that are separated by a leveshtein's edit distance of 1 or 2 from this given word. Do...
Finding words from Wordnet separated by a fixed Edit Distance from a given word
I am writing a spell checker using nltk and wordnet, I have a few wrongly spelt words say "belive". What I want to do is find all words from wordnet that are separated by a leveshtein's edit distance of 1 or 2 from this given word. Does nltk provide any methods to accomplish this? How to do this? May be, I put it wro...
[ "It does in fact provide an edit_distance method. See the docs here\n", "Okay, finally came up with a solution:\nfrom nltk.corpus import wordnet\nf=open(\"wordnet_wordlist.txt\",\"w\")\nfor syn in list(wordnet.all_synsets()):\n f.write(syn.name[:-5])\n f.write(\"\\n\")\n\nf.close()\n\nf = open(\"wordnet_wo...
[ 1, 0 ]
[]
[]
[ "nlp", "nltk", "python", "wordnet" ]
stackoverflow_0007490028_nlp_nltk_python_wordnet.txt
Q: python3 - ttk treeview... extract values from specific column into a function I'm very new to programming and I just can't figure out how to make this work for me... I'm just trying to figure out how to extract the values from the treeview's col4 into a function that would allow me to provide a simple sum in the r...
python3 - ttk treeview... extract values from specific column into a function
I'm very new to programming and I just can't figure out how to make this work for me... I'm just trying to figure out how to extract the values from the treeview's col4 into a function that would allow me to provide a simple sum in the result_display label at the bottom. From what I've read, I need to use the item meth...
[ "I am new to treeview, but I think I have your solution. This code will just show you how the values are \"packaged\" so you can use them however you like.\ndef fullcalc():\n try:\n # get a list of children of the root node\n children = tv.get_children()\n for child in children:\n # For so...
[ 3 ]
[]
[]
[ "python", "treeview", "ttk" ]
stackoverflow_0007365098_python_treeview_ttk.txt
Q: How does random graph generator work in networkx? I used the source code of Networkx to generate a random graph with Poisson degree distribution. I change some parts of codes that I need as follows: import random import networkx import math from networkx.generators.classic import empty_graph def gnp_random_graph(...
How does random graph generator work in networkx?
I used the source code of Networkx to generate a random graph with Poisson degree distribution. I change some parts of codes that I need as follows: import random import networkx import math from networkx.generators.classic import empty_graph def gnp_random_graph(n, p, seed=None): """Return a random graph G_{n,p}....
[ "Unless the number of nodes/edges are large, this gives a bernoulli distribution. You can get networkx to give you a poisson degree distribution easily.\nimport numpy as np\nfrom scipy.stats import poisson\n\ndef poissongraph(n,mu):\n z= np.zeros(n) #n is number of nodes\n for i in range(n):\n z[i]=poi...
[ 3, 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0006703792_networkx_python.txt
Q: Add a method to a list instance in python I want to add a method to a single instance of the 'list' class. Example: a = [1,2] a.first = lambda self: return self[0] I know this don't work, but I want something like that works like that. I know its not a good practice, and I know I should do a whole new class, but ...
Add a method to a list instance in python
I want to add a method to a single instance of the 'list' class. Example: a = [1,2] a.first = lambda self: return self[0] I know this don't work, but I want something like that works like that. I know its not a good practice, and I know I should do a whole new class, but I think this is possible in Python and haven't ...
[ "Nothing will work with a native list, since you cannot add methods to a type defined in C. You will need to derive from list and add your method to that class.\n" ]
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0007507350_python.txt
Q: pygettext: Seen unexpected token "%" I am currently trying to implement internationalization in an application (Python 2.6) and have run into an error involving string formatting. A string marked translatable looks like this: foo = _("I would like to have %d pounds of cheese" % amount) Running pygettext on my sour...
pygettext: Seen unexpected token "%"
I am currently trying to implement internationalization in an application (Python 2.6) and have run into an error involving string formatting. A string marked translatable looks like this: foo = _("I would like to have %d pounds of cheese" % amount) Running pygettext on my source tree then complains when it hits this l...
[ "Translate the unreplaced string. Or replace on the translated string.\nfoo = _(\"I would like to have %d pounds of cheese\") % amount\n\n" ]
[ 1 ]
[]
[]
[ "gettext", "internationalization", "python" ]
stackoverflow_0007507588_gettext_internationalization_python.txt
Q: ForEach and NestedVariables in FormEncode to create array of form items in Pyramid I'm using Pyramid with FormEncode to try and create and validate a list of addresses. I'm using pyramid_simpleform and have been looking at this tutorial http://jimmyg.org/blog/2007/multiple-checkboxes-with-formencode.html and this ...
ForEach and NestedVariables in FormEncode to create array of form items in Pyramid
I'm using Pyramid with FormEncode to try and create and validate a list of addresses. I'm using pyramid_simpleform and have been looking at this tutorial http://jimmyg.org/blog/2007/multiple-checkboxes-with-formencode.html and this previous question Pylons FormEncode with an array of form elements but I'm still having ...
[ "I have written a blog post with similar usage back in 2009, it may come in handy:\nhttp://www.domenkozar.com/2009/07/22/advanced-formencode-usage/\n" ]
[ 0 ]
[]
[]
[ "formencode", "pyramid", "python" ]
stackoverflow_0007251488_formencode_pyramid_python.txt
Q: Python and Regex - extracting a number from a string I'm new to regex, and I'm starting to sort of get the hang of things. I have a string that looks like this: This is a generated number #123 which is an integer. The text that I've shown here around the 123 will always stay exactly the same, but it may have fu...
Python and Regex - extracting a number from a string
I'm new to regex, and I'm starting to sort of get the hang of things. I have a string that looks like this: This is a generated number #123 which is an integer. The text that I've shown here around the 123 will always stay exactly the same, but it may have further text on either side. But the number may be 123, 597...
[ "You don't really need a fancy regex. Just use a group on what you want.\nre.search(r'#(\\d+)', 'This is a generated number #123 which is an integer.').group(1)\n\nif you want to match a number in the middle of some known text, follow the same rule:\nr'some text you know (\\d+) other text you also know'\n\n", "re...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007507524_python_regex.txt
Q: App Engine problems using the command line I am developing an App Engine project on Windows using Eclipse and Python 2.5 and Django 0.96. Everything in my app, including Django, is working nicely. My problems arise when I try to use command line. For example, I'm told that if I want to clear the local datastore I ...
App Engine problems using the command line
I am developing an App Engine project on Windows using Eclipse and Python 2.5 and Django 0.96. Everything in my app, including Django, is working nicely. My problems arise when I try to use command line. For example, I'm told that if I want to clear the local datastore I can enter "python manage.py reset" but when I do...
[ "If you're using Django 0.96 templates within a 'normal' App Engine app, then manage.py isn't involved at all.\n/path/to/dev_appserver.py --clear_datastore .\nis what you want, assuming you're CD'd to the root of your app.\n" ]
[ 2 ]
[]
[]
[ "command_line", "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007506854_command_line_django_google_app_engine_google_cloud_datastore_python.txt
Q: python sort list short of renaming/fixing the logging module on the webservers... when i do a list.sort(), the list entries get placed in the following order: 2011-09-21 19:15:54,731 DEBUG __main__ 44: running www.site.com-110731.log.0.gz 2011-09-21 19:15:54,731 DEBUG __main__ 44: running www.site.com-110731.log...
python sort list
short of renaming/fixing the logging module on the webservers... when i do a list.sort(), the list entries get placed in the following order: 2011-09-21 19:15:54,731 DEBUG __main__ 44: running www.site.com-110731.log.0.gz 2011-09-21 19:15:54,731 DEBUG __main__ 44: running www.site.com-110731.log.1.gz 2011-09-21 19:15...
[ "You would probably want to write a custom comparator to pass to sort; in fact, you probably need to anyway, because you're likely getting a lexicographical sort order instead of the intended (I presume) numerical order.\nFor instance, if you know that the filenames will only differ in those digits, you'd write a c...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007507922_python.txt
Q: Combining 2 functions I am trying to combine two functions because A) I think I can and B) I think I should. When I use the functions separately the script works fine. When I combine them the "new" variable is an empty string vice what it should be. Any help would be appreciated. If you need the full script th...
Combining 2 functions
I am trying to combine two functions because A) I think I can and B) I think I should. When I use the functions separately the script works fine. When I combine them the "new" variable is an empty string vice what it should be. Any help would be appreciated. If you need the full script that could be arranged. Funct...
[ "I'd go easy with the globals:\ndef script(x, y, z):\n new = ''\n ns = x[:x.find('@')]\n\n for a in y:\n if a in z: \n new += z.get(a)\n\n" ]
[ 2 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007507967_function_python.txt
Q: Python graph visualization and editing with PyQt I want to expose some kind of graph explorer widget in Python using PyQt and some library. Does such a library exist? A: It looks like NodeBox could be a good solution for you. According to its web page it doesn't seem to depend on anything that would keep it fr...
Python graph visualization and editing with PyQt
I want to expose some kind of graph explorer widget in Python using PyQt and some library. Does such a library exist?
[ "It looks like NodeBox could be a good solution for you. According to its web page it doesn't seem to depend on anything that would keep it from working with PyQt.\nAnother possibility, though messier, would be to incorporate whatever Sage does to draw graphs.\n", "Try the nodebox-gl fork version of nodebox that...
[ 2, 0, 0, 0 ]
[]
[]
[ "graph", "graphviz", "pyqt", "python" ]
stackoverflow_0005768566_graph_graphviz_pyqt_python.txt
Q: Do we have something similar/equivalent to Jdbctemplate in Python? I'm looking for Jdbtemplate equivalent in Python. Any one saw something similar somewhere ? A: Found one, Spring Python DatabaseTemplate
Do we have something similar/equivalent to Jdbctemplate in Python?
I'm looking for Jdbtemplate equivalent in Python. Any one saw something similar somewhere ?
[ "Found one, Spring Python DatabaseTemplate\n" ]
[ 4 ]
[]
[]
[ "jdbctemplate", "python" ]
stackoverflow_0007494640_jdbctemplate_python.txt
Q: maintain state between custom tag calls? Is there a way to maintain state between tag calls? I need to store the last item passed to a tag that I have created. It appeared as if I could use context to do this, but it doesn't seem to work. Here is my code: @register.simple_tag(takes_context=True) def date_divide...
maintain state between custom tag calls?
Is there a way to maintain state between tag calls? I need to store the last item passed to a tag that I have created. It appeared as if I could use context to do this, but it doesn't seem to work. Here is my code: @register.simple_tag(takes_context=True) def date_divider(context, date): if 'last_date' not in co...
[ "It seems likely that the context into which you are entering last_date no longer exists the second time you reach this tag (for instance, perhaps that context has been popped already?). A (sort of hackish) solution is to be sure that you insert last_date into the \"highest\" context:\nif 'last_date' not in contex...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007507958_django_python.txt
Q: Trouble with Recursion in Python Working with python 2.7. The following code allows me to input the winning percentage of two teams (WP_1 and WP_2) a number of wins (k) and determine given the two team's winning percentages, the probability that team one will have more wins at the end of the season (Playoff_Probab...
Trouble with Recursion in Python
Working with python 2.7. The following code allows me to input the winning percentage of two teams (WP_1 and WP_2) a number of wins (k) and determine given the two team's winning percentages, the probability that team one will have more wins at the end of the season (Playoff_Probability): def PlayoffProb(WP_1, k, WP_2)...
[ " return Total_Playoff_Probability(WP_1, k+1, WP_2)\n\nI think you meant\n return PlayoffProb2(WP_1, k+1, WP_2)\n\nYou've got that error because you are trying to treat a floating point number as a function. Obviously, that doesn't compute.\nEDIT\nActually, it should be:\n return Total_Playoff_Probability + Pla...
[ 5, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0007508427_python_recursion.txt
Q: List in a Python class shares the same object over 2 different instances? I created a class: class A: aList = [] now I have function that instantiate this class and add items into the aList. note: there are 2 items for item in items: a = A(); a.aList.append(item); I find that the first A and the seco...
List in a Python class shares the same object over 2 different instances?
I created a class: class A: aList = [] now I have function that instantiate this class and add items into the aList. note: there are 2 items for item in items: a = A(); a.aList.append(item); I find that the first A and the second A object has the same number of items in their aList. I would expect that th...
[ "You have defined the list as a class attribute.\nClass attributes are shared by all instances of your class.\nWhen you define the list in __init__ as self.aList, then the list is an attribute of your instance (self) and then everything works as you expected.\n", "You are confusing class and object variables.\nIf...
[ 13, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002757116_python.txt
Q: Returning from a function while continuing to execute I am working on a Django application where I would like to populate several fields within my model when an object is first created. Currently I am able to do this in the save() routine of my model like so: def save(self, *args, **kwargs): file = fileinfo.ge...
Returning from a function while continuing to execute
I am working on a Django application where I would like to populate several fields within my model when an object is first created. Currently I am able to do this in the save() routine of my model like so: def save(self, *args, **kwargs): file = fileinfo.getfileinfo(self.file_path) if not self.file_size: ...
[ "Your best bet in this case is to use celery.\nThis enables you to create tasks that will occur in the background, without blocking the current request.\nIn your case, you can .save(), create the task that updates the fields, push it to your celery queue, and then return the desired response to the user.\n", "I d...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "nonblocking", "python" ]
stackoverflow_0007508009_django_nonblocking_python.txt
Q: Is "backporting" Python 3's `range` to Python 2 a bad idea? One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this: #!/bin/bash # Run some PyUnit tests python2 test.py python3 test.py One ...
Is "backporting" Python 3's `range` to Python 2 a bad idea?
One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this: #!/bin/bash # Run some PyUnit tests python2 test.py python3 test.py One thing I've been doing is making range work the same in both versi...
[ "You can use the six package which provides a Python 2 and 3 compatibility library and written by one of the Python core developers. Among its features is a set of standard definitions for renamed modules and functions, including xrange -> range. The use of six is one of many recommendations in the official Porti...
[ 9, 6 ]
[]
[]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0007507492_python_python_2.x_python_3.x.txt
Q: Ideal way to pass filtered relationship of a model to a template? This is more of what feels like a lot of work / hackish code... Say I have some models like this: class Semester(models.Model): year = models.IntegerField() month = models.IntegerField() # ... some fields class Course(models.Model): ...
Ideal way to pass filtered relationship of a model to a template?
This is more of what feels like a lot of work / hackish code... Say I have some models like this: class Semester(models.Model): year = models.IntegerField() month = models.IntegerField() # ... some fields class Course(models.Model): semesters = models.ManyToManyField(Semester) # ... some field...
[ "You're going to have data translation either way... but if you want to make it a little easier on the template you could return a generator instead of a list of courses and/or semesters.\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007507504_django_django_templates_python.txt
Q: Django-registration not recognizing urls.py accounts page? I am trying to setup django-registration and it is not recognizing the URLs. I get Error 404 when I visit http://localhost:8000/accounts/ Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/ Using the URLconf de...
Django-registration not recognizing urls.py accounts page?
I am trying to setup django-registration and it is not recognizing the URLs. I get Error 404 when I visit http://localhost:8000/accounts/ Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/ Using the URLconf defined in namekeepr.urls, Django tried these URL patterns, in thi...
[ "Try going to http://localhost:8000/accounts/ with a slash on the end. That is the 'regular' django url, usually it would redirect to this but it is not for some reason.... but before you try to solve that problem, should make sure it works this way.\n", "based on the server response, you have not defined a url ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007507508_django_python.txt
Q: How can I convert a string to a list in python? Let's say I have : my_args = ["QA-65"] as the desired result, but in my function, I have: m = re.search("([a-zA-Z]+-\d+)",line) print 'printing m.group(1)' print m.group(1) m_args = m.group(1) print 'my_a...
How can I convert a string to a list in python?
Let's say I have : my_args = ["QA-65"] as the desired result, but in my function, I have: m = re.search("([a-zA-Z]+-\d+)",line) print 'printing m.group(1)' print m.group(1) m_args = m.group(1) print 'my_args ' print m_args print type...
[ "Perhaps this:\nmy_args = [my_args]\n\n", "You do it this way:\nm_args = [m_args, ]\n\n" ]
[ 11, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007508715_python.txt
Q: I have a problem with pprint in python I have looked into the pprint function, which i tried below: from pprint import pprint a = [[1,2],[3,4]] pprint(a) But it didn't give me what i want, which is: 1 2 3 4 Is there a simple way to solve this ? A: That's... not what pprint does. for i in a: print ' '.join(i...
I have a problem with pprint in python
I have looked into the pprint function, which i tried below: from pprint import pprint a = [[1,2],[3,4]] pprint(a) But it didn't give me what i want, which is: 1 2 3 4 Is there a simple way to solve this ?
[ "That's... not what pprint does.\nfor i in a:\n print ' '.join(i)\n\n", "You can either do what Ignacio said or change the width of pprint:\n>>> pprint.pprint([[1,2],[3,4]], width=10)\n[[1, 2],\n [3, 4]]\n\nBut you would have to calculate the space that your list takes...\n" ]
[ 2, -1 ]
[]
[]
[ "format", "list", "nested", "pprint", "python" ]
stackoverflow_0007508783_format_list_nested_pprint_python.txt
Q: Extract assigned variable name See the update below I even don't know how to make a short title for my problem. In a class I have some class attributes of StringField class: class Authors(Table): # id field is already present first_name = StringField(maxLength=100) last_name = StringField(maxLength=10...
Extract assigned variable name
See the update below I even don't know how to make a short title for my problem. In a class I have some class attributes of StringField class: class Authors(Table): # id field is already present first_name = StringField(maxLength=100) last_name = StringField(maxLength=100) StringField constructor may rece...
[ "I don't know how Django does it. But you could do it this way:\nclass WantFixup(object):\n def new_instance(self, name, derived_name):\n cls = type(self)\n if name is None:\n name = derived_name.replace('_', ' ')\n return cls(name)\n\nclass Container(WantFixup):\n def __init_...
[ 2, 1 ]
[]
[]
[ "inspect", "python", "python_3.x" ]
stackoverflow_0007495105_inspect_python_python_3.x.txt
Q: I don't understand the width field in pprint in python I don't understand this concept clearly. Could somebody give me some examples to demonstrate the concept for width in pprint in python? A: Basically it tries to limit your output to a specific width. Here's an example: import pprint stuff = ['spam', 'eggs...
I don't understand the width field in pprint in python
I don't understand this concept clearly. Could somebody give me some examples to demonstrate the concept for width in pprint in python?
[ "Basically it tries to limit your output to a specific width. \nHere's an example:\nimport pprint\nstuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']\npp = pprint.PrettyPrinter(width=80)\npp.pprint(stuff)\n\nresult is:\n['spam', 'eggs', 'lumberjack', 'knights', 'ni']\n\nbut if you do the same thing but change...
[ 9 ]
[]
[]
[ "concept", "pprint", "python", "width" ]
stackoverflow_0007508899_concept_pprint_python_width.txt
Q: Beautiful Soup - how to fix broken tags I'd like to know how to fix broken html tags before parsing it with Beautiful Soup. In the following script the td> needs to be replaced with <td. How can I do the substitution so Beautiful Soup can see it? from BeautifulSoup import BeautifulSoup s = """ <tr> td>LABEL1</td>...
Beautiful Soup - how to fix broken tags
I'd like to know how to fix broken html tags before parsing it with Beautiful Soup. In the following script the td> needs to be replaced with <td. How can I do the substitution so Beautiful Soup can see it? from BeautifulSoup import BeautifulSoup s = """ <tr> td>LABEL1</td><td>INPUT1</td> </tr> <tr> <td>LABEL2</td><td...
[ "Edit (working):\nI grabbed a complete (at least it should be complete) list of all html tags from w3 to match against. Try it out:\nfixedString = re.sub(\">\\s*(\\!--|\\!DOCTYPE|\\\n a|abbr|acronym|address|applet|area|\\\n b|base|basefont|bdo|big|blockquote|body...
[ 2, 2 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0007508774_beautifulsoup_python_regex.txt
Q: Creating a rect grid in Pygame I need to create a clickable 8 by 8 grid in pygame. Right now I have something like this: #!/usr/bin/python2 #------------------------------------------------------------------------------- # Imports & Inits import pygame, sys from pygame.locals import * pygame.init() #--------------...
Creating a rect grid in Pygame
I need to create a clickable 8 by 8 grid in pygame. Right now I have something like this: #!/usr/bin/python2 #------------------------------------------------------------------------------- # Imports & Inits import pygame, sys from pygame.locals import * pygame.init() #--------------------------------------------------...
[ "Though your solution is indeed a little cumbersome, I'd first say\nrectangles = (rect1, rect2, ...)\n\nthen you can iterate over them as intended.\nTry sth like\npos = pygame.mouse.get_pos()\nfor rect in rectangles:\n if rect.collidepoint(pos):\n changecolor(rect)\n\nYou'd have to implement the changecol...
[ 4, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007415109_pygame_python.txt
Q: How to break out of the loop only if a certain case is met, but then continue the iteration? I realize that the title may be somewhat confusing, so I apologize. Basically, this is my code: while i < 5: do stuff if i == 3: print "i is 3" break Now all that sounds pretty simple, right? Except I do...
How to break out of the loop only if a certain case is met, but then continue the iteration?
I realize that the title may be somewhat confusing, so I apologize. Basically, this is my code: while i < 5: do stuff if i == 3: print "i is 3" break Now all that sounds pretty simple, right? Except I don't really want to BREAK from the loop as much as I'd want it to start over again. So in this case...
[ "while i < 5:\n do stuff\n if i == 3:\n print \"i is 3\"\n continue\n\n", "Instead of break use continue\nNow, I pretty much never use continue as I find it is usually clearer to rework the code to avoid it. Of course that's really easy in this example, if you have trouble with a more complex exampl...
[ 12, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007509211_python.txt
Q: Python Interpreter: Can't assign to literal I wrote a program with this code in it: ('<') = raw_input(v1), ('>') = raw_input(v2) and recieve the message syntax error: can't assign to literal. What am I doing wrong? A: What am I doing wrong? You're attempting to assign something the user enters to an instance of...
Python Interpreter: Can't assign to literal
I wrote a program with this code in it: ('<') = raw_input(v1), ('>') = raw_input(v2) and recieve the message syntax error: can't assign to literal. What am I doing wrong?
[ "\nWhat am I doing wrong?\n\nYou're attempting to assign something the user enters to an instance of a String. That doesn't work.\nTo grab your question in a comment on another answer and attempt to incorporate it, if you want to be able to type v1 and have it return '<', you need to do this:\nv1 = '<'\n\nIt sound...
[ 4, 2, 1 ]
[]
[]
[ "python", "syntax", "syntax_error", "variable_assignment" ]
stackoverflow_0007507027_python_syntax_syntax_error_variable_assignment.txt
Q: Why deadline doesn't work with GAE urlfetch? If I use the following code: result = urlfetch.fetch(url=url_get_devices, payload='', method=urlfetch.POST, headers=headers, deadline=10 ) ...
Why deadline doesn't work with GAE urlfetch?
If I use the following code: result = urlfetch.fetch(url=url_get_devices, payload='', method=urlfetch.POST, headers=headers, deadline=10 ) then I am getting error: File "D:\Work_GAE\test.p...
[ "It sounds like you're using a very old version of the App Engine SDK. You should update to the latest version.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0007506253_google_app_engine_python_urlfetch.txt
Q: Having issues with making Sprites transparent in pygame! (image included inside) Even though I've set the transparency of the image to 'True', I am still unable to clear the fuzz around it. I've tried various methods, playing around with it in Photoshop to no avail. Any help would be greatly appreciated. Thanks! ...
Having issues with making Sprites transparent in pygame! (image included inside)
Even though I've set the transparency of the image to 'True', I am still unable to clear the fuzz around it. I've tried various methods, playing around with it in Photoshop to no avail. Any help would be greatly appreciated. Thanks!
[ "It looks like on the image in photoshop, you'll need to clean up the file. Check the alpha on the parts of the image that are white.\n", "Note: save as png.\nJpeg will cause compression, probably why you are expecting a solid color of white, and it isn't.\nPng will be loss-less, and even has alpha-transparency (...
[ 2, 0 ]
[]
[]
[ "image", "pygame", "python", "transparency" ]
stackoverflow_0006638649_image_pygame_python_transparency.txt
Q: PyGame flickering issue I've made several small programs in PyGame and for my latest attempt I have added scrolling (push arrow keys) but when it happens the sprites flicker. I've tried to pinpoint the issue but cannot. The drawing section happens in engine.screen.py redraw() and update_window() Github repository ...
PyGame flickering issue
I've made several small programs in PyGame and for my latest attempt I have added scrolling (push arrow keys) but when it happens the sprites flicker. I've tried to pinpoint the issue but cannot. The drawing section happens in engine.screen.py redraw() and update_window() Github repository of code
[ "Have you considered swapping lines 48 and 49 in screen.py? :) Not sure, but maybe you ought to call display.flip() after rendering the sprites?\n", "Do you have vertical sync enabled? And set framerate to 60, for a nice look.\n" ]
[ 2, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0006556938_pygame_python.txt
Q: Hooking Python standard library modules Question I've written a replacement threading module for Python. What's the best method to go about hooking all uses of the usual threading module from the standard library with my own? The hooking should be opt-in, and on a per project, or per executable basis. When this st...
Hooking Python standard library modules
Question I've written a replacement threading module for Python. What's the best method to go about hooking all uses of the usual threading module from the standard library with my own? The hooking should be opt-in, and on a per project, or per executable basis. When this statement is executed: import threading I want...
[ "Can you not just put your replacement threading module in some directory, and make sure that directory is listed in PYTHONPATH when you want to use it? That should mean that directory is searched before the default places when importing threading, and Python will find your module and stop.\n", "You might try usi...
[ 3, 3 ]
[]
[]
[ "import", "multithreading", "python", "python_3.x" ]
stackoverflow_0007509016_import_multithreading_python_python_3.x.txt
Q: Pygame subclassing issues? So basically I just wanted to create an enemy class with pygames.sprite.Sprite as the parent. But then I wanted to move this sprite object I created as well as add it to the screen. But it says blit is not a attribute of class "Enemy". Sorry for the newb question but how do I go about do...
Pygame subclassing issues?
So basically I just wanted to create an enemy class with pygames.sprite.Sprite as the parent. But then I wanted to move this sprite object I created as well as add it to the screen. But it says blit is not a attribute of class "Enemy". Sorry for the newb question but how do I go about doing this? Class enemy: class Ene...
[ "Try this way : \npygame.init()\nscreen = pygame.display.set_mode([320, 240])\nenemy = Enemy()\nscreen.blit(enemy.image, enemy.rect)\npygame.display.update()\n\nyou have to blit the sprite image in the pygame screen to display it.\n", "Sprites can be placed in SpriteGroups, which have nice features, but also blit...
[ 2, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0006525168_pygame_python.txt
Q: Any pointers on using Ropevim? Is it a usable library? Rope is a refactoring library for Python and RopeVim is a Vim plugin which calls into Rope. The idea of using RopeVim seems great to me, is there any documentation on "getting started" with RopeVim? I've followed what documentation there is: https://bitbucket....
Any pointers on using Ropevim? Is it a usable library?
Rope is a refactoring library for Python and RopeVim is a Vim plugin which calls into Rope. The idea of using RopeVim seems great to me, is there any documentation on "getting started" with RopeVim? I've followed what documentation there is: https://bitbucket.org/agr/ropevim/src/tip/README.txt I suppose I'm looking for...
[ "For basic renaming, hover your vim cursor over the variable/method/etc that you wish to rename and then type:\n:RopeRename <enter>\n\nFrom there it should be self-explanatory. It asks for the root path to the project you wish to do the renaming in. Then it asks you for the new name. Then you can preview/confirm ch...
[ 13, 2, 2 ]
[ "If you can live without vim, use Eric, which has rope support.\n" ]
[ -3 ]
[ "python", "refactoring", "rope", "vim" ]
stackoverflow_0004843493_python_refactoring_rope_vim.txt
Q: Do/Undo using command pattern in Python I have read that using command pattern is one of the most popular ways to accomplish do/undo functionality. In fact, I have seen that it's possible to stack a bunch of actions and reverse them in order to reach a given state. However, I'm not quite sure how that can be done ...
Do/Undo using command pattern in Python
I have read that using command pattern is one of the most popular ways to accomplish do/undo functionality. In fact, I have seen that it's possible to stack a bunch of actions and reverse them in order to reach a given state. However, I'm not quite sure how that can be done in Python and most of the tutorials I have re...
[ "How I'd go about this\nclass Command(object):\n def execute(self, canvas):\n raise NotImplementedError\n\nclass DrawLineCommand(Command):\n def __init__(self, point1, point2):\n self._point1 = point1\n self._point2 = point2\n\n def execute(self, canvas):\n canvas.draw_line(sel...
[ 2, 2 ]
[]
[]
[ "command", "design_patterns", "python" ]
stackoverflow_0007509129_command_design_patterns_python.txt
Q: how to detect if the sprite has been clicked in pygame Im new in pygame, right now im working with sprites. My question is how do i detect if the sprite has been clicked? I want to do something when the sprite was clicked just like a button. thx :) [Edited] thx Stephen. In addition is there a way to know who is th...
how to detect if the sprite has been clicked in pygame
Im new in pygame, right now im working with sprites. My question is how do i detect if the sprite has been clicked? I want to do something when the sprite was clicked just like a button. thx :) [Edited] thx Stephen. In addition is there a way to know who is the sprite that was clicked? Here is sample code boxes = pyga...
[ "It's been a long time since I did anything in Pygame, but IIRC the basic idea is that your sprite should have a rect attribute that describes its position on the screen. When you receive a mouse click event, you get the position by calling pygame.mouse.get_pos(). You can then check for a collision between a rect...
[ 9, 5 ]
[]
[]
[ "pygame", "python", "sprite" ]
stackoverflow_0006356840_pygame_python_sprite.txt
Q: How can I insert a console in to a pyGame Window? I'm making a text adventure, and I want to have pyGame animations and illustrations and a HUD! How can I insert this console? Thanks! A: I'm pretty sure that's impossible. If you want a console within a Pygame screen then you'll have to write your own, or find o...
How can I insert a console in to a pyGame Window?
I'm making a text adventure, and I want to have pyGame animations and illustrations and a HUD! How can I insert this console? Thanks!
[ "I'm pretty sure that's impossible. If you want a console within a Pygame screen then you'll have to write your own, or find one written by someone else (e.g. http://pygame.org/project-pygame-console-287-.html)\n", "For your game, you can use subsurface, for the different screen 'sections'.\nUsing python 3x will ...
[ 2, 0 ]
[]
[]
[ "console", "frontend", "pygame", "python", "user_interface" ]
stackoverflow_0006044316_console_frontend_pygame_python_user_interface.txt
Q: pygame event handling Just a noob question about python and pygame event handling. I got the following code in a pygame tutorial: while 1: for event in pygame.event.get(): if event.type in (QUIT, KEYDOWN): sys.exit() ...but for some reason it returns this error: if event.type in (QUIT, KEYDO...
pygame event handling
Just a noob question about python and pygame event handling. I got the following code in a pygame tutorial: while 1: for event in pygame.event.get(): if event.type in (QUIT, KEYDOWN): sys.exit() ...but for some reason it returns this error: if event.type in (QUIT, KEYDOWN): NameError: name 'QUIT'...
[ "I think you meant this:\nif event.type in (pygame.QUIT, pygame.KEYDOWN)\n\nThe tutorial probably used from pygame import *, and this example perfectly shows why this is a bad habit.\n", "instead of from pygame import *, use:\nfrom pygame.locals import *\n" ]
[ 16, 0 ]
[]
[]
[ "event_handling", "pygame", "python" ]
stackoverflow_0005901779_event_handling_pygame_python.txt
Q: two or more dots in a django template after the variable In a django template, is it possible to have two (or more) dots after a variable? For example, say I have a list of objects that I first want to use a list-index lookup for and then once I have the object, I want to call its method for getting the absolute ...
two or more dots in a django template after the variable
In a django template, is it possible to have two (or more) dots after a variable? For example, say I have a list of objects that I first want to use a list-index lookup for and then once I have the object, I want to call its method for getting the absolute url, should that work? For example: {% for entry in myList...
[ "What you are doing is perfectly acceptable in Django templates. There is no better way to accomplish what you're trying to do.\n", "more than one dot absolutely works.\nbased on your comment, there is no entry.0 because entry IS the first item in the list cause you are already looping through `myList'\njust use...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007509025_django_django_templates_python.txt
Q: Utility To Count Number Of Lines Of Code In Python Or Bash Is there a quick and dirty way in either python or bash script, that can recursively descend a directory and count the total number of lines of code? We would like to be able to exclude certain directories though. For example: start at: /apps/projects/real...
Utility To Count Number Of Lines Of Code In Python Or Bash
Is there a quick and dirty way in either python or bash script, that can recursively descend a directory and count the total number of lines of code? We would like to be able to exclude certain directories though. For example: start at: /apps/projects/reallycoolapp exclude: lib/, frameworks/ The excluded directories s...
[ "Found an awesome utility CLOC. https://github.com/AlDanial/cloc\nHere is the command we ran:\nperl cloc.pl /apps/projects/reallycoolapp --exclude-dir=lib,frameworks\n\nAnd here is the output\n--------------------------------------------------------------------------------\nLanguage files ...
[ 41, 15, 4 ]
[]
[]
[ "bash", "lines_of_code", "python" ]
stackoverflow_0007507846_bash_lines_of_code_python.txt
Q: How do I get the arguments for any python method? Normally I would use inspect.getargspec, however how do I get the arguments of a method that has been bound? Eg, how do I get the argument names for the method 'foo' as follows: class Foo(object): @memoized def foo(self, arg1, arg2): pass Note tha...
How do I get the arguments for any python method?
Normally I would use inspect.getargspec, however how do I get the arguments of a method that has been bound? Eg, how do I get the argument names for the method 'foo' as follows: class Foo(object): @memoized def foo(self, arg1, arg2): pass Note that Foo().foo is a memoized object, http://wiki.python.or...
[ "You could add a _wrapped attribute to the partial, which may be what you did already:\ndef __get__(self, obj, objtype):\n \"\"\"Support instance methods.\"\"\"\n f = functools.partial(self.__call__, obj)\n f._wrapped = self.func\n return f\n\nOr you could return self.func instead of the partial if obj ...
[ 2 ]
[]
[]
[ "decorator", "introspection", "python" ]
stackoverflow_0007509400_decorator_introspection_python.txt
Q: How do I change the django-registration e-mail template "site" name? The current setup ends up substituting example.com into the below code from the template. I want it to point to localhost:8000 Without hard coding this, where and how can I change the template so that the site is linked to my localhost? Thank you...
How do I change the django-registration e-mail template "site" name?
The current setup ends up substituting example.com into the below code from the template. I want it to point to localhost:8000 Without hard coding this, where and how can I change the template so that the site is linked to my localhost? Thank you for registering an account at {{ site.domain }}. To activate your registr...
[ "The site object in the template comes from the Django Site model. When you do a syncdb, it defaults automatically to example.com\nIf you login to Django's admin interface, you will find \"Sites\". Inside it, you will be able to change example.com to whatever you like.\n\n" ]
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007509962_django_python.txt
Q: Python how to check if variable exist and its length, in one if statement? Here's my situation: if var: if len(var) == 5: do something... else: do the same thing... To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check i...
Python how to check if variable exist and its length, in one if statement?
Here's my situation: if var: if len(var) == 5: do something... else: do the same thing... To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check its length... Any idea? I would like something like this: if var and len(var) ==...
[ "Did you try that? It works:\nif var and len(var) == 5:\n ....\n\nThe and operator doesn't evaluate the RHS if the LHS is false. Try this:\n>>> False and 1/0\nFalse\n>>> True and 1/0\nZeroDivisionError: division by zero\n\n", "The code as you've written it in the question executes the statements in two cases...
[ 18, 3, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007510038_if_statement_python.txt
Q: Python: map widgets to database for reading and editing it I am relatively new to database GUI programming, and I want to make a simple app in Python, which allows user to access and edit database. I want to view/edit tables and specific records plus generate some specific reports about stored data. For example, ...
Python: map widgets to database for reading and editing it
I am relatively new to database GUI programming, and I want to make a simple app in Python, which allows user to access and edit database. I want to view/edit tables and specific records plus generate some specific reports about stored data. For example, if we have a table with employees name and position, it should a...
[ "You can use the Qt Database GUI Layer.\nIf you want to use SQLAlchemy too, you can take a look at Camelot.\nUPDATE\nA good introduction to the Qt Database GUI Layer is chapter 15 of the book\n\"Rapid GUI Programming with Python and Qt\".\n" ]
[ 1 ]
[]
[]
[ "data_mapping", "database", "pyqt", "python", "widget" ]
stackoverflow_0007510392_data_mapping_database_pyqt_python_widget.txt
Q: Handling ascii char in python string i have file having name "SSE-Künden, SSE-Händler.pdf" which having those two unicode char ( ü,ä) when i am printing this file name on python interpreter the unicode values are getting converted into respective ascii value i guess 'SSE-K\x81nden, SSE-H\x84ndler.pdf' but i want ...
Handling ascii char in python string
i have file having name "SSE-Künden, SSE-Händler.pdf" which having those two unicode char ( ü,ä) when i am printing this file name on python interpreter the unicode values are getting converted into respective ascii value i guess 'SSE-K\x81nden, SSE-H\x84ndler.pdf' but i want to test dir contains the pdf file of name...
[ "Assuming your terminal supports displaying the characters, iterate over the list of files and print them individually (or use Python 3, which displays Unicode in lists):\nPython 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for...
[ 3, 1, 0 ]
[]
[]
[ "ascii", "asciiencoding", "decode", "python" ]
stackoverflow_0007510350_ascii_asciiencoding_decode_python.txt
Q: Redirect the standard input and output of .net program I am writing a test script for a C/S system in python. And right now, we only have a test client written in C#. It is a command line based client. I want to control the input and get the output of the client in my python script. How could I make it? Thanks! ...
Redirect the standard input and output of .net program
I am writing a test script for a C/S system in python. And right now, we only have a test client written in C#. It is a command line based client. I want to control the input and get the output of the client in my python script. How could I make it? Thanks!
[ "Use the subprocess module as follows:\nimport subprocess\n\nproc = subprocess.Popen(\"cat\", stdin = subprocess.PIPE, stdout = subprocess.PIPE)\n\nout, err = proc.communicate(input)\n\nThe process ends after the last call. If you want to do some input iteratively, you can use proc.stdin.write, but you have to call...
[ 2, 1 ]
[]
[]
[ ".net", "c#", "python" ]
stackoverflow_0007510959_.net_c#_python.txt
Q: IOError: 13, 'Permission denied' when writing to /etc/hosts via Python I have a Python app that I'm working on that needs to access the hosts file to append a few lines. Everything worked on my test file, but when I told the program to actually modify my hosts file in /etc/hosts I get IOError 13. From what I under...
IOError: 13, 'Permission denied' when writing to /etc/hosts via Python
I have a Python app that I'm working on that needs to access the hosts file to append a few lines. Everything worked on my test file, but when I told the program to actually modify my hosts file in /etc/hosts I get IOError 13. From what I understand, my app doesn't have root privileges. My question is, how can I circu...
[ "The easiest way to handle this is to write out your changes to a temp file, then run a program to overwrite the protected file. Like so:\nwith open('/etc/hosts', 'rt') as f:\n s = f.read() + '\\n' + '127.0.0.1\\t\\t\\thome_sweet_home\\n'\n with open('/tmp/etc_hosts.tmp', 'wt') as outf:\n outf.write(s...
[ 8, 6 ]
[]
[]
[ "hosts_file", "io", "privileges", "python", "sudo" ]
stackoverflow_0007510617_hosts_file_io_privileges_python_sudo.txt
Q: VS breaks solution file I have a (python) script that accomplishes the following: Scanning a folder looking for .csproj and .vcproj files. Creating a solution file to contain all the projects by writing text according to the .csproj and .vcproj files. Building that solution. By calling devenv.exe /Build from comm...
VS breaks solution file
I have a (python) script that accomplishes the following: Scanning a folder looking for .csproj and .vcproj files. Creating a solution file to contain all the projects by writing text according to the .csproj and .vcproj files. Building that solution. By calling devenv.exe /Build from command line (subprocess.call on ...
[ "The simple answer is, indentation matters to the VS sln parser.\nSo folks at the company claimed it all worked back in the day, and I found it hard to believe. Over and over again I scanned the code that builds it and the sln file that is produced and couldn't tell any difference. \nBeacuse I didn't look at whites...
[ 0 ]
[]
[]
[ ".net", "python", "scripting", "visual_c++", "visual_studio_2008" ]
stackoverflow_0007315677_.net_python_scripting_visual_c++_visual_studio_2008.txt
Q: GDB+Python: Determining target type Is there a way to determine whether the debugged target is a core dump or a 'live' process? A: As far as I know, there is no dedicated way to do it in Python, however, you can still use gdb.execute("<command>", to_string=<boolean>) to execute a "CLI" command in Python, where...
GDB+Python: Determining target type
Is there a way to determine whether the debugged target is a core dump or a 'live' process?
[ "As far as I know, there is no dedicated way to do it in Python, however, you can still use \n\ngdb.execute(\"<command>\", to_string=<boolean>) to execute a \"CLI\" command in Python, where to_string being True will tell GDB to collect the output and return it as a string (cf. doc)\nmaint print target-stack which w...
[ 3 ]
[]
[]
[ "core", "gdb", "python" ]
stackoverflow_0007510865_core_gdb_python.txt
Q: Non-English Characters are being converted to Decimal While I was checking an RSS feed, in a browser I can see the text as below: 装,配上超短迷你裙,太过暴露,也很不得体。大专学生的随性打扮... But the same source code view is converted to decimal as below: #30701&#35044&#12289&#36855&#20320&#35033&#12289&#21514&#24102&#35013&#12289&#20154&#...
Non-English Characters are being converted to Decimal
While I was checking an RSS feed, in a browser I can see the text as below: 装,配上超短迷你裙,太过暴露,也很不得体。大专学生的随性打扮... But the same source code view is converted to decimal as below: #30701&#35044&#12289&#36855&#20320&#35033&#12289&#21514&#24102&#35013&#12289&#20154&#23383&#25302&#38795&#46;&#46;&#46;&#46;&#46;&#46;&#22823&#1...
[ "It's not that the source view is converting it to decimal - it's that the browser is handling the entities and converting them to the relevant non-ASCII characters. It's possible that it's being a little generous in terms of converting entities which don't have a terminating ';'.\nThe server is almost certainly se...
[ 2, 1, 1, 0 ]
[]
[]
[ "decimal", "non_english", "python", "utf_8", "xml" ]
stackoverflow_0007429783_decimal_non_english_python_utf_8_xml.txt
Q: finding indexes of common subarrays I have 2 large, unsorted arrays (structured set of xyz coordinates) and I'm trying to find the positions of all identical subarrays (common points consisting of 3 coordinates). Example: a = array([[0, 1, 2], [3, 4, 5]]) b = array([[3, 4, 5], [6, 7, 8]]) Here the correct subarra...
finding indexes of common subarrays
I have 2 large, unsorted arrays (structured set of xyz coordinates) and I'm trying to find the positions of all identical subarrays (common points consisting of 3 coordinates). Example: a = array([[0, 1, 2], [3, 4, 5]]) b = array([[3, 4, 5], [6, 7, 8]]) Here the correct subarray would be [3, 4, 5], but more than one i...
[ "A general solution for Python iterables (not specific to numpy or arrays) that works in linear average time (O(n+m), n is the number of subarrays and m is the number of unique subarrays):\na = [[0, 1, 2], [3, 4, 5]]\nb = [[3, 4, 5], [6, 7, 8]]\n\nfrom collections import defaultdict\n\nindexmap = defaultdict(list)\...
[ 2, 1, 0 ]
[]
[]
[ "algorithm", "arrays", "numpy", "python" ]
stackoverflow_0007492454_algorithm_arrays_numpy_python.txt
Q: python not finding library under django that's found otherwise I've just successfully installed GeoDjango and all the required libraries. I've set the environment variables and registry keys (yea working under Windows here) and everything works find from the command line. d:\...\> python >>> from django.contrib.gi...
python not finding library under django that's found otherwise
I've just successfully installed GeoDjango and all the required libraries. I've set the environment variables and registry keys (yea working under Windows here) and everything works find from the command line. d:\...\> python >>> from django.contrib.gis.geos import * >>> exit() d:\...\> python manage.py runserver 0.0.0...
[ "Thanks to @ed. and @g.d.d.c I found the solution. Problem turned up in the Django shell as well. Turns out I had set GEOS_LIBRARY_PATH = 'c:\\OSGeo4W' in my Django settings where it should've been 'c:\\OSGeo4W\\bin'. Calling plain Python ignored those settings and instead relied on the OS-own functionality to find...
[ 0 ]
[]
[]
[ "django", "geodjango", "geos", "module", "python" ]
stackoverflow_0007503416_django_geodjango_geos_module_python.txt
Q: Implementing copied and pasted code/text detection? I've a bunch of legacy javascript files looking really similar. I'd like to implement a copied/pasted code detection tool, but I was unable to find a description of an algorithm... I'm already using sonar with the javascript plugin to detect this kind of code, bu...
Implementing copied and pasted code/text detection?
I've a bunch of legacy javascript files looking really similar. I'd like to implement a copied/pasted code detection tool, but I was unable to find a description of an algorithm... I'm already using sonar with the javascript plugin to detect this kind of code, but I'd like to have a finer-grained control over the detec...
[ "You could take a look to CloneDigger, it is designed to detect clones in python or java code, but the algorithm is described here.\n" ]
[ 1 ]
[]
[]
[ "algorithm", "java", "javascript", "python" ]
stackoverflow_0007511812_algorithm_java_javascript_python.txt
Q: SQLite3 Database file - Corrupted/Encrypted only on Linux I am currently writing a Python script to interact with an SQLite database but it kept returning that the database was "Encrypted or Corrupted". The database is definitely not encrypted and so I tried to open it using the sqlite3 library at the command line...
SQLite3 Database file - Corrupted/Encrypted only on Linux
I am currently writing a Python script to interact with an SQLite database but it kept returning that the database was "Encrypted or Corrupted". The database is definitely not encrypted and so I tried to open it using the sqlite3 library at the command line (returned the same error) and with SQLite Manager add-on for F...
[ "Does your Linux box have the same version of SQLite as your Windows box? An old version of SQLite may not be able to recognize files that use newer features. For example, WAL journal mode.\n\nTo prevent older versions of SQLite from trying to recover a WAL-mode\n database (and making matters worse) the database...
[ 2, 0 ]
[]
[]
[ "database", "python", "sql", "sqlite" ]
stackoverflow_0007511965_database_python_sql_sqlite.txt