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: Use python tarfile add without normpath being applied to arcname I'm using python's tarfile library to create a gzipped tar file. The tar file needs to have absolute pathnames for reasons that I've got no control over. (I'm aware that this isn't normal practice.) When I call tarobject.add("/foo/xx1", "/bar/xx1") ...
Use python tarfile add without normpath being applied to arcname
I'm using python's tarfile library to create a gzipped tar file. The tar file needs to have absolute pathnames for reasons that I've got no control over. (I'm aware that this isn't normal practice.) When I call tarobject.add("/foo/xx1", "/bar/xx1") the arcname argument "/bar/xx1" is run through os.path.normpath() and ...
[]
[]
[ "You really do strange things. You need to copy /usr/lib64/python/tarfile.py to a directory in your PYTHONPATH. Then you can modify this file. But you need to bundle you own tarfile module with your code. \n" ]
[ -1 ]
[ "python", "tar" ]
stackoverflow_0007308599_python_tar.txt
Q: Chopping a large number into its digits then adding them in Python I am trying to make a program where whatever a number is entered by the user, the digits composing that number are added, and if they sum to 10, it is good, if not then they've done something wrong. This should be simple I suppose. Though I'm strug...
Chopping a large number into its digits then adding them in Python
I am trying to make a program where whatever a number is entered by the user, the digits composing that number are added, and if they sum to 10, it is good, if not then they've done something wrong. This should be simple I suppose. Though I'm struggling to add together the numbers after I split them. Do you know what I...
[ "or you can use the map function:\nIn [1]: a=\"1234567890\"\n\nIn [2]: map(int,a)\nOut[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\n\nIn [3]: sum(map(int,a))\nOut[3]: 45\n\nmap(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values. See docs.python.org This works be...
[ 6, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007308839_python.txt
Q: Code check program - Python BRIEF: I am trying to write a simple program that checks if a given code is valid. The code is valid if all the three characters entered are digits between 0 and 9. If the code is valid, your progam displays a message Thank you. We will process your order!. The output of your program sh...
Code check program - Python
BRIEF: I am trying to write a simple program that checks if a given code is valid. The code is valid if all the three characters entered are digits between 0 and 9. If the code is valid, your progam displays a message Thank you. We will process your order!. The output of your program should be an error message The veri...
[ "What you're trying to do is to check if given input matches a given pattern (three digits in your case), that's basically what regular expressions are made for.\nUsing a regex, your code would look like this:\nimport re\ncode = raw_input(\"what's your code? \")\nif re.match(r'^\\d{3}$', code):\n print \"Code OK...
[ 4, 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007309284_python.txt
Q: Python import MySQLdb error - Mac 10.6 I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/) When I attempt to import MySQLdb to a python terminal, I get the below error: Safira:~...
Python import MySQLdb error - Mac 10.6
I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/) When I attempt to import MySQLdb to a python terminal, I get the below error: Safira:~ yanigisawa$ python --version Python 2.6.1 S...
[ "In my case, I solved by adding a couple of symbolic links as in http://ageekstory.blogspot.com/2011/04/installing-massive-coupon-on-mac-os-10.html\nas following:\n\nsudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib\nsudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql\n...
[ 49, 11, 1 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0004730787_macos_mysql_python.txt
Q: Is there an equivalent of python's pulldom for java? StAX seems to be a pulling parser (like SAX but without inversion of control). But I didn't find the equivalent of python's expandNode which is what I was interested in in the first place, I don't care about inversion of control. For those who don't know pulldom...
Is there an equivalent of python's pulldom for java?
StAX seems to be a pulling parser (like SAX but without inversion of control). But I didn't find the equivalent of python's expandNode which is what I was interested in in the first place, I don't care about inversion of control. For those who don't know pulldom, it's a S(t)AX parser where at any point you can obtain t...
[ "The Java approach seems to be that either you get streaming or DOM parser but not both; while python allows mixing the two. \n" ]
[ 1 ]
[]
[]
[ "java", "python", "sax", "stax", "xml" ]
stackoverflow_0007307423_java_python_sax_stax_xml.txt
Q: Object tracking in python I'm working on a program in PYTHON which is able to do the following: A webcam is watching a movement, where an object is moving on a path. The object to be tracked is marked with a big yellow spot. I have to find this yellow spot, then calculate the center-point of this spot, and then ma...
Object tracking in python
I'm working on a program in PYTHON which is able to do the following: A webcam is watching a movement, where an object is moving on a path. The object to be tracked is marked with a big yellow spot. I have to find this yellow spot, then calculate the center-point of this spot, and then make some calculations with it. I...
[ "Here's a nice demo (using Python and OpenCV) that seems to be what you're looking for: video, code\nWhether this will work for you without modification depends on the details of your spot. The example uses cvHoughCircles to identify the circle, and if your object isn't a circle, you'll need to replace this.\n" ]
[ 2 ]
[]
[]
[ "opencv", "python", "python_imaging_library" ]
stackoverflow_0007256700_opencv_python_python_imaging_library.txt
Q: How to search for a word and then replace text after it using regular expressions in python? I'm trying to write a script that will search through a html file and then replace the form action. So in this basic code: <html> <head> <title>Forms</title> </head> <body> <form action="login.php" ...
How to search for a word and then replace text after it using regular expressions in python?
I'm trying to write a script that will search through a html file and then replace the form action. So in this basic code: <html> <head> <title>Forms</title> </head> <body> <form action="login.php" method="post"> Username: <input type="text" name="username" value="" /> <br /> ...
[ "You can use regex, or just simple string manipulation. Just a test case.\nfor line in open(\"file\"):\n if \"form action\" in line:\n line=line.rstrip()\n a=line.split('<form action=\"')\n a[-1] = '\"newlogin\" ' + a[-1].split()[-1]\n line = '<form action='.join(a)\n print line\n\n", ...
[ 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007309467_python_regex.txt
Q: How to use MathJax library on Google App Engine I'm trying to add Tex support to my application and I would like to use MathJax to render Mathematics formulas client side since I gave up the server side solution explained here. The MathJax library is pretty fat (30.000 files) and it can't be easily installed on A...
How to use MathJax library on Google App Engine
I'm trying to add Tex support to my application and I would like to use MathJax to render Mathematics formulas client side since I gave up the server side solution explained here. The MathJax library is pretty fat (30.000 files) and it can't be easily installed on App Engine due to the files number limitation. I have ...
[ "Since March 2011 MathJAX has its own CDN, so you can now use it without uploading any files to GAE. Just make sure this is in any page's header:\n<script type=\"text/javascript\" async\n src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?...\">\n</script>\n\n", "You could use http://mathjax....
[ 6, 5, 2 ]
[]
[]
[ "google_app_engine", "mathjax", "python", "tex" ]
stackoverflow_0004624154_google_app_engine_mathjax_python_tex.txt
Q: How to tell whether sys.stdout has been flushed in Python I'm trying to debug some code I wrote, which involves a lot of parallel processes. And have some unwanted behaviour involving output to sys.stdout and certain messages being printed twice. For debugging purposes it would be very useful to know whether at a ...
How to tell whether sys.stdout has been flushed in Python
I'm trying to debug some code I wrote, which involves a lot of parallel processes. And have some unwanted behaviour involving output to sys.stdout and certain messages being printed twice. For debugging purposes it would be very useful to know whether at a certain point sys.stdout has been flushed or not. I wonder if t...
[ "The answer is: you cannot tell (not without serious uglyness, an external C module or similar).\nThe reason is that python’s file-implementation is based on the C (stdio) implementation for FILE *. So an underlying python file object basically just has a reference to the opened FILE. When writing data the C-implem...
[ 1 ]
[]
[]
[ "io", "python", "stdout" ]
stackoverflow_0007302450_io_python_stdout.txt
Q: Why error is not tk attribute in python? Why this error and why not tk attribute? Error: Traceback (most recent call last): File "editor-new.py", line 90, in <module> TextEditor().mainloop() File "editor-new.py", line 48, in __init__ Button(self, text='Open', command=self.onSave).pack(side=LEFT) File...
Why error is not tk attribute in python?
Why this error and why not tk attribute? Error: Traceback (most recent call last): File "editor-new.py", line 90, in <module> TextEditor().mainloop() File "editor-new.py", line 48, in __init__ Button(self, text='Open', command=self.onSave).pack(side=LEFT) File "C:\Python27_1\lib\lib-tk\Tkinter.py", line 2...
[ "In this code:\nButton(self, text='Open', command=self.onSave).pack(side=LEFT)\n\nthe first argument to Button should be an instance of Tkinter container (e.g. a root window, or a frame). According to http://code.google.com/p/childreneditor/source/browse/trunk/editor-new.py, self is an instance of ScrolledText, whi...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007310073_python_tkinter.txt
Q: Python executing Class-dump command I am trying to execute the following code in Python import os,subprocess from glob import glob path = "/Users/armed/private_SDKs" os.chdir(path) for file in glob("*.framework"): command = ['class-dump' , '-H' , file , '-o' , '~', '/Users/armed/Desktop/Headers/'] subp...
Python executing Class-dump command
I am trying to execute the following code in Python import os,subprocess from glob import glob path = "/Users/armed/private_SDKs" os.chdir(path) for file in glob("*.framework"): command = ['class-dump' , '-H' , file , '-o' , '~', '/Users/armed/Desktop/Headers/'] subprocess.call(command) On executing this s...
[ "Check permissions of the class-dump command. chmod +x class-dump if it's not executable. Here are the docs on chmod. \nYou might also need to specify the absolute path to class-dump if it's not on your path.\nAlso, try:\nprint \" \".join(command)\n\nand see if you can run it by pasting the results into a shell.\...
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007310203_python_subprocess.txt
Q: UTF-8 Python issues with Google Datastore I've been roaming around these forums asking questions about issues related to Python and UTF-8 encoding/decoding. This time around I've stumbled upon something which initially seemed an easy problem. In my previous question (http://stackoverflow.com/questions/7138797/prob...
UTF-8 Python issues with Google Datastore
I've been roaming around these forums asking questions about issues related to Python and UTF-8 encoding/decoding. This time around I've stumbled upon something which initially seemed an easy problem. In my previous question (http://stackoverflow.com/questions/7138797/problems-with-python-in-google-app-engine-utf-8-and...
[ "encode turns unicode into bytes, and decode turns bytes into unicode. You have to be careful not to mix the two. Your error means either:\n\nchatter or msgtext is already bytes, and you are trying to encode it. One of the worst 'features' of Python 2 is that it lets you do this - it tries to first decode the bytes...
[ 3 ]
[]
[]
[ "ascii", "google_app_engine", "google_cloud_datastore", "python", "utf_8" ]
stackoverflow_0007310151_ascii_google_app_engine_google_cloud_datastore_python_utf_8.txt
Q: Web control center with Python I'd like to create some web based control center where I can start processes and watch statistics, logs and outputs. Also I would like to run something like an interactive Python console on the webpage. I'd don't know any web development yet, but I know Python. Something Python based...
Web control center with Python
I'd like to create some web based control center where I can start processes and watch statistics, logs and outputs. Also I would like to run something like an interactive Python console on the webpage. I'd don't know any web development yet, but I know Python. Something Python based would be nice. Could you please sug...
[ "If you need a custom tool for your specific needs, you might want to develop your own small Django based wep app and use celery to spawn managed tasks. You can store your log in files or in models. This will probably require a lot of effort if you are new to web development....\nIf you want to cut programming ti...
[ 1, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0007309057_python_web_applications.txt
Q: cvs command not found by a Python Mac app created using py2app Some system/software info before getting started: OS: Mac OS X 10.7.1 Python: Active Python 2.7.2.5 wxPython: wxPython2.9-osx-2.9.1.1-cocoa-py2.7 I have a small wxpython-based Mac app that just tests the availability of cvs and svn on a Mac platform. T...
cvs command not found by a Python Mac app created using py2app
Some system/software info before getting started: OS: Mac OS X 10.7.1 Python: Active Python 2.7.2.5 wxPython: wxPython2.9-osx-2.9.1.1-cocoa-py2.7 I have a small wxpython-based Mac app that just tests the availability of cvs and svn on a Mac platform. This is the python code on which the Mac app is based: import wx impo...
[ "When you run a OSX GUI app from Finder/Dock ie not the terminal a new shell is not started thus your .profile is not read.\nYou can set environment variables in ~/.MacOS/environment.plist as per Apple doc\nYou could also set the environment (e.g. add to the path) or explicitly use the full paths to cvs and svn in...
[ 2, 1 ]
[]
[]
[ "cvs", "macos", "py2app", "python", "wxpython" ]
stackoverflow_0007310843_cvs_macos_py2app_python_wxpython.txt
Q: Is __dict__.update() oldstyle? I'm getting confused reading about the differences in newstyle vs oldstyle attributes. In this example: Is this code using old-style method to modify attributes? In Event() at self.__dict__.update(kw) Do I use getattr, getattr or getattribute ? for Dispatcher.dispatch_to_parent() ...
Is __dict__.update() oldstyle?
I'm getting confused reading about the differences in newstyle vs oldstyle attributes. In this example: Is this code using old-style method to modify attributes? In Event() at self.__dict__.update(kw) Do I use getattr, getattr or getattribute ? for Dispatcher.dispatch_to_parent() The code is from http://www.pygame.o...
[ "You shouldn't update the instance dictionary directly, you will bypass custom setters. Loop over the keys and do setattr.\n", "There's a missing * in def post(self, event_name, kw): line\nIn due to make you function able to receive a dict as a parameter, you need to add ** before variables name:\ndef post(self,...
[ 3, 0 ]
[]
[]
[ "new_style_class", "pygame", "python", "python_2.7" ]
stackoverflow_0006934641_new_style_class_pygame_python_python_2.7.txt
Q: PIL - empty PSD image I'm trying to load this PSD image with Python Imaging Library. http://www.2shared.com/photo/JjSY7dN-/BG1.html I'm not very familiar with layered images. Can someone check to see what's the issue? The image appears to be completely transparent. Opening it in my image editor I noticed that the ...
PIL - empty PSD image
I'm trying to load this PSD image with Python Imaging Library. http://www.2shared.com/photo/JjSY7dN-/BG1.html I'm not very familiar with layered images. Can someone check to see what's the issue? The image appears to be completely transparent. Opening it in my image editor I noticed that the only layer in the image was...
[ "PIL provides only very rudimentary hooks into the PSD format. It doesn't support writing or much in the way of manipulation. Your image layer is not shown, so it results in a transparent image. You'll need something more advanced to modify the PSD.\nHere's all there is about the PSD format in PIL: http://www.py...
[ 0 ]
[]
[]
[ "image", "layer", "psd", "python", "python_imaging_library" ]
stackoverflow_0007310904_image_layer_psd_python_python_imaging_library.txt
Q: for loop ignores some elements of my list Possible Duplicate: Remove items from a list while iterating in Python I want to remove all the dates in a list which are later than a given date. I can't see why my method only removes some items of the list. Here's what I've got: import datetime import numpy as np imp...
for loop ignores some elements of my list
Possible Duplicate: Remove items from a list while iterating in Python I want to remove all the dates in a list which are later than a given date. I can't see why my method only removes some items of the list. Here's what I've got: import datetime import numpy as np import os list_dates = [datetime.date(2012,1,3),...
[ "James and GWW are right, you cant modify the list while you are iterating through the same. Instead copy the items which you want to keep to a new list.\nlist_dates = [datetime.date(2012,1,3), datetime.date(2012,1,1), datetime.date(2012,1,5), datetime.date(2013,1,3), datetime.date(2013,1,1)] \n\nfor item in...
[ 2, 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0007310460_for_loop_loops_python.txt
Q: NameError: name 'A' is not defined QUESTION: Write a program that takes a position on a chess board as a column col and row value row and checks whether or not the position is valid. Remember that the column in a chess board is a letter ranging from A to H (inclusive) and the row is a number between 1 and 8 (inclu...
NameError: name 'A' is not defined
QUESTION: Write a program that takes a position on a chess board as a column col and row value row and checks whether or not the position is valid. Remember that the column in a chess board is a letter ranging from A to H (inclusive) and the row is a number between 1 and 8 (inclusive). A3 or E7 are valid inputs but a1 ...
[ "The problem is here:\ncol = [A, B, C, D, E, F, G]\n\nYour list is supposed to contain strings, so you need to quote each letter just like how you quoted the strings in your print statements. Unquoted, they're being treated as identifiers (for variables, classes, functions, etc) and that's how you end up with your ...
[ 3, 2, 0, 0 ]
[ "Complete program must looks like\ncol = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\nrow = [1, 2, 3, 4, 5, 6, 7]\npos=raw_input(\"you move to:\")\ntry:\n x=pos[0] # A1 > A\n y=pos[1] # A1 > 1\n if (x in col) and (int(y) in row):\n print 'The piece is moved to %s' % pos\nexcept:\n print 'The position is no...
[ -1 ]
[ "python" ]
stackoverflow_0007311317_python.txt
Q: Looping over a list of objects within a Django template Can't seem to see where I am going wrong here. Forgive me because I am new to this. I am trying to display the 10 newest objects within a model. Here is the loop I used to put all of these objects within a list: # put the top 10 newest Recipe objects in a ...
Looping over a list of objects within a Django template
Can't seem to see where I am going wrong here. Forgive me because I am new to this. I am trying to display the 10 newest objects within a model. Here is the loop I used to put all of these objects within a list: # put the top 10 newest Recipe objects in a list entries_list = [] all_recipes = Recipes.objec...
[ "A couple of things. There is a method by which you can order your query and just get the first ten entries. It would be more efficient than the loop you have. \nThe reason your template doesn't work is that you're referring to the list rather than the individual entry. It should be:\n{% for entry in entries_li...
[ 8, 1 ]
[]
[]
[ "django", "models", "python", "templates" ]
stackoverflow_0007311203_django_models_python_templates.txt
Q: Python, mysqldb and unicode I'm having trouble to get unicode values out of mysql queries. Here is how I do it now: >>> from MySQLdb import connect >>> from MySQLdb.cursors import DictCursor >>> con = connect( passwd = "****", db = 'my_db', user = "db_user", host = "localhost", cursorclass = D...
Python, mysqldb and unicode
I'm having trouble to get unicode values out of mysql queries. Here is how I do it now: >>> from MySQLdb import connect >>> from MySQLdb.cursors import DictCursor >>> con = connect( passwd = "****", db = 'my_db', user = "db_user", host = "localhost", cursorclass = DictCursor, use_unicode=True, ...
[ "What you get is a bytestring. You must decode it in order to get a unicode string. It basically comes down to this:\n>>> byte_string = 'F\\xe9vrier'\n>>> byte_string.decode('UTF-8')\nu'Février'\n\n" ]
[ 2 ]
[]
[]
[ "mysql", "mysql_python", "python", "unicode" ]
stackoverflow_0007311397_mysql_mysql_python_python_unicode.txt
Q: What does "'module' object is not subscriptable" mean in the context of this code? Running test.py gives Traceback (most recent call last): File "test.py", line 3, in <module> Map = Parser.Map(os.path[0] + "\\start.wmap") TypeError: 'module' object is not subscriptable Parser.py import configparser def Str...
What does "'module' object is not subscriptable" mean in the context of this code?
Running test.py gives Traceback (most recent call last): File "test.py", line 3, in <module> Map = Parser.Map(os.path[0] + "\\start.wmap") TypeError: 'module' object is not subscriptable Parser.py import configparser def StringIsNumber(String): try: int(String) except: return False r...
[ "That you can't get its properties using key/index lookup like something[property]\n", "os.path is a module and you are using it as a list i think you're looking for sys.path.\n", "os.path is a module. It's unclear what you think os.path[0] is going to do for you, since it's not an iterable and has no 0th eleme...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007311466_python.txt
Q: How does asigning of @property works? (Assigning of a getter to another variable.) I have code like this: class Debug(object): ... @property def ThreadAwareLogger(self): if not self.logger_instance_for_current_thread: self.logger_instance_for_current_thread=self.cloneMainLogger() return self.l...
How does asigning of @property works? (Assigning of a getter to another variable.)
I have code like this: class Debug(object): ... @property def ThreadAwareLogger(self): if not self.logger_instance_for_current_thread: self.logger_instance_for_current_thread=self.cloneMainLogger() return self.logger_instance_for_current_thread def cloneMainLogger(self): return logger_instan...
[ "One way to get the whole property would be to just make another property:\nclass SomeOtherClass:\n\n @property\n def logger(self):\n return self.debug.ThreadAwareLogger\n\nThere might be other ways, too.\n", "self.logger will refer to what is returned by the property ThreadAwareLogger, not to the pr...
[ 2, 1, 1 ]
[]
[]
[ "getter", "logging", "properties", "python", "variable_assignment" ]
stackoverflow_0007311201_getter_logging_properties_python_variable_assignment.txt
Q: python asynchronization Imagine a text file of 20 mb. I am reading char by char and extracting the useful information. I have actually 2 main functions, one is reading the file and the second is extracting the info. Something like this: def reader(path): f = open(path, 'r') source = f.read() f.close() ...
python asynchronization
Imagine a text file of 20 mb. I am reading char by char and extracting the useful information. I have actually 2 main functions, one is reading the file and the second is extracting the info. Something like this: def reader(path): f = open(path, 'r') source = f.read() f.close() while True: # he...
[ "You can use producer/consumer threads. The threads can be synchronized using a Queue.Queue.\nEDIT: an example of a producer/consumer system:\nfrom threading import Thread\nfrom Queue import Queue\n\n\ndef produce(queue, n_items):\n for d in range(n_items):\n queue.put(d)\n print \"put {0} in queue...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007311710_python.txt
Q: Why won't re.groups() give me anything for my one correctly-matched group? When I run this code: print re.search(r'1', '1').groups() I get a result of (). However, .group(0) gives me the match. Shouldn't groups() give me something containing the match? A: To the best of my knowledge, .groups() returns a tuple ...
Why won't re.groups() give me anything for my one correctly-matched group?
When I run this code: print re.search(r'1', '1').groups() I get a result of (). However, .group(0) gives me the match. Shouldn't groups() give me something containing the match?
[ "To the best of my knowledge, .groups() returns a tuple of remembered groups. I.e. those groups in the regular expression that are enclosed in parentheses. So if you were to write:\nprint re.search(r'(1)', '1').groups()\n\nyou would get\n('1',)\n\nas your response. In general, .groups() will return a tuple of all t...
[ 25, 23, 5, 5 ]
[]
[]
[ "capture_group", "match", "object", "python", "regex" ]
stackoverflow_0007312020_capture_group_match_object_python_regex.txt
Q: Python + lxml: how to find the namespace of a tag? I am processing some HTML files with python + lxml. Some of them have been edited with MS Word, and we have <p> tags written as <o:p>&nbsp</o:p> for instance. IE and Firefox do not interpret these MS tags as real <p> tags, and do not display line breaks before and...
Python + lxml: how to find the namespace of a tag?
I am processing some HTML files with python + lxml. Some of them have been edited with MS Word, and we have <p> tags written as <o:p>&nbsp</o:p> for instance. IE and Firefox do not interpret these MS tags as real <p> tags, and do not display line breaks before and after the <o:p> tags, and that is how the original edit...
[ "From the HTML specs: \"The HTML syntax does not support namespace declarations\".\nSo I think lxml.html.HTMLParser removes/ignores the namespace. \nHowever, BeautifulSoup parses HTML differently so I thought it might be worth a shot. If you also have BeautifulSoup installed, you can use the BeautifulSoup parser wi...
[ 1, 0 ]
[]
[]
[ "lxml", "namespaces", "python" ]
stackoverflow_0007309256_lxml_namespaces_python.txt
Q: Trying to learn PyQt with knowledge from Tkinter Maybe I'm jumping into the deep end, but I'll give it a shot. Here are some useful features of Tkinter: The Tkinter Canvas widget is an object oriented drawing canvas. The elements of the drawing are essentially widgets themselves, as they can be moved, modified, ...
Trying to learn PyQt with knowledge from Tkinter
Maybe I'm jumping into the deep end, but I'll give it a shot. Here are some useful features of Tkinter: The Tkinter Canvas widget is an object oriented drawing canvas. The elements of the drawing are essentially widgets themselves, as they can be moved, modified, and bound to events. Tkinter uses bindings to trigger ...
[ "In Qt and PyQt events are called signals and you bind to them using slots (docs here). Generally speaking what you do define a slot with an @ decorator. \nclass WindowImpl (QtGui.QMainWindow, Ui_TremorMain, Ui_Graphs):\n def __init__ (self, buffer, parent = None, configuration = None):\n # do some initialisati...
[ 1 ]
[]
[]
[ "pyqt", "python", "tkinter" ]
stackoverflow_0007311943_pyqt_python_tkinter.txt
Q: How should I write tests for Forms in Django? I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request: from django.tests import TestCase class MyTests(TestCase): def test_forms(self): response = self.client...
How should I write tests for Forms in Django?
I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request: from django.tests import TestCase class MyTests(TestCase): def test_forms(self): response = self.client.post("/my/form/", {'something':'something'}) ...
[ "I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:\nfrom django.test import TestCase\nfrom myapp.forms import MyForm\n\nclass MyTests(TestCase):\n def test_forms(self):\n form_data = {'something': 'something'}...
[ 271, 85, 19 ]
[]
[]
[ "django", "django_testing", "python" ]
stackoverflow_0007304248_django_django_testing_python.txt
Q: Instant script finishing in a function called in a view I don't know how to explain in one sentence what I need, but let's look at the example in PHP. function sth() { exit(); } echo 'you can see this'; sth(); echo 'this won't be shown'; ?> In other words, in PHP I can define a function in which script can be in...
Instant script finishing in a function called in a view
I don't know how to explain in one sentence what I need, but let's look at the example in PHP. function sth() { exit(); } echo 'you can see this'; sth(); echo 'this won't be shown'; ?> In other words, in PHP I can define a function in which script can be instantly stopped executing with exit(); What about Django? ...
[ "You can return from the view early:\ndef some_view(request):\n # ...\n return direct_to_template(...)\n # this code is unreachable\n\nTo achieve this with a nested call, you'd need to raise exception and handle it from the view. But don't do that, there is absolutely no need for such things. If you have ...
[ 1 ]
[]
[]
[ "django", "execution", "function", "python" ]
stackoverflow_0007312326_django_execution_function_python.txt
Q: Access Highrise's API with Python? How can I access 37 signals Highrise's API with Python? Found wrappers for PHP/Ruby, but not Python. I'm writing my own now, anyone have advice on getting over the first hurdle of authentication with Python? A: I wrote (am writing, really) a Highrise API wrapper for Python. I...
Access Highrise's API with Python?
How can I access 37 signals Highrise's API with Python? Found wrappers for PHP/Ruby, but not Python. I'm writing my own now, anyone have advice on getting over the first hurdle of authentication with Python?
[ "I wrote (am writing, really) a Highrise API wrapper for Python. It uses Python objects for each of the Highrise classes and work a lot like the Django ORM:\n>>> from pyrise import *\n>>> Highrise.server('my-server')\n>>> Highrise.auth('api-key-goes-here')\n>>> p = Person()\n>>> p.first_name = 'Joe'\n>>> p.last_nam...
[ 4, 1, 0, 0 ]
[]
[]
[ "highrise", "python" ]
stackoverflow_0004070842_highrise_python.txt
Q: How to execute a Python script using the Python DLL? I have a Python DLL already shipped and installed on the end user (guaranteed, and with a known version number). How can I use this DLL to execute some Python scripts without shipping the Python interpreter (again)? A: You'll want to embed Python in another ap...
How to execute a Python script using the Python DLL?
I have a Python DLL already shipped and installed on the end user (guaranteed, and with a known version number). How can I use this DLL to execute some Python scripts without shipping the Python interpreter (again)?
[ "You'll want to embed Python in another application, and use PyRun_AnyFile*() to run it.\n" ]
[ 1 ]
[]
[]
[ "dll", "python" ]
stackoverflow_0007312868_dll_python.txt
Q: Creating xml doc with python/ElementTree and namespaces I'm trying to create an in-memory xml document such that the root's child nodes all require a name space. The final document should look something like this: <Feed> <FeedEntity Id="0000" xmlns="http://schemas.example.com/search/query/2010/5...
Creating xml doc with python/ElementTree and namespaces
I'm trying to create an in-memory xml document such that the root's child nodes all require a name space. The final document should look something like this: <Feed> <FeedEntity Id="0000" xmlns="http://schemas.example.com/search/query/2010/5/revision"> <FeedRequest locale="en-US" title="<some val...
[ "With xml.etree, you cannot get the exact output as in the first example, but you can use the (global) register_namespace() function to use a \"better\" prefix than \"ns0\". For example: ET.register_namespace('rev', 'http://schemas.example.com/search/query/2010/5/revision') will make sure the output will look like ...
[ 10 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0007312372_elementtree_python.txt
Q: python: create list of tuples from lists I have two lists: x = ['1', '2', '3'] y = ['a', 'b', 'c'] and I need to create a list of tuples from these lists, as follows: z = [('1','a'), ('2','b'), ('3','c')] I tried doing it like this: z = [ (a,b) for a in x for b in y ] but resulted in: [('1', '1'), ('1', '2'), (...
python: create list of tuples from lists
I have two lists: x = ['1', '2', '3'] y = ['a', 'b', 'c'] and I need to create a list of tuples from these lists, as follows: z = [('1','a'), ('2','b'), ('3','c')] I tried doing it like this: z = [ (a,b) for a in x for b in y ] but resulted in: [('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'),...
[ "Use the builtin function zip():\nIn Python 3:\nz = list(zip(x,y))\n\nIn Python 2:\nz = zip(x,y)\n\n", "You're looking for the zip builtin function.\nFrom the docs:\n>>> x = [1, 2, 3]\n>>> y = [4, 5, 6]\n>>> zipped = zip(x, y)\n>>> zipped\n[(1, 4), (2, 5), (3, 6)]\n\n", "You're after the zip function.\nTaken di...
[ 61, 12, 10 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0007313157_list_python_tuples.txt
Q: How to retrieve a webpage in python, including any images I'm trying to retrieve the source of a webpage, including any images. At the moment I have this: import urllib page = urllib.urlretrieve('http://127.0.0.1/myurl.php', 'urlgot.php') print urlgot.php which retrieves the source fine, but I also need to downl...
How to retrieve a webpage in python, including any images
I'm trying to retrieve the source of a webpage, including any images. At the moment I have this: import urllib page = urllib.urlretrieve('http://127.0.0.1/myurl.php', 'urlgot.php') print urlgot.php which retrieves the source fine, but I also need to download any linked images. I was thinking I could create a regular ...
[ "Don't use regex when there is a perfectly good parser built in to Python:\nfrom urllib.request import urlretrieve # Py2: from urllib\nfrom html.parser import HTMLParser # Py2: from HTMLParser\n\nbase_url = 'http://127.0.0.1/'\n\nclass ImgParser(HTMLParser):\n def __init__(self, *args, **kwargs):\n ...
[ 7, 3 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0007312687_python_urllib.txt
Q: regex exclusion in python I'm not so able with regex and I'm looking for the syntax to exclude something. I'm parsing <, >, " and & in html code (to replace with &lt;, etc) and I need to exclude <br/> from parsing. I.E.: <html><br/> <head><title></title></head><br/> <body><br/> </body><br/> </html> I tri...
regex exclusion in python
I'm not so able with regex and I'm looking for the syntax to exclude something. I'm parsing <, >, " and & in html code (to replace with &lt;, etc) and I need to exclude <br/> from parsing. I.E.: <html><br/> <head><title></title></head><br/> <body><br/> </body><br/> </html> I tried sometihng like i.e.: r'<\b?!...
[ "Ok, now the question is open again, I can do it as an answer, so...\nUnless I'm missing something, and once it's just <br/> (not any variants), then can just replace <(?!br/>) with &lt; and (?<!<br/)> with &gt; and that's it?\n\nIn Python, it looks like that means this:\ntext = re.sub( '<(?!br/>)' , '&lt;' , text ...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007301404_python_regex.txt
Q: Asynchronous WSGI with Twisted I'm building a web interface for a twisted application and would like to use WSGI rather than twisted.web directly (since the rest of the website is WSGI and I already have a substantial WSGI codebase). The Twisted documentation page I found about WSGIResource (http://twistedmatrix.c...
Asynchronous WSGI with Twisted
I'm building a web interface for a twisted application and would like to use WSGI rather than twisted.web directly (since the rest of the website is WSGI and I already have a substantial WSGI codebase). The Twisted documentation page I found about WSGIResource (http://twistedmatrix.com/documents/current/web/howto/web-i...
[ "Why do you want to use WSGI and do asynchronous things? The benefit of WSGI is that you can deploy your application on any WSGI container. If you start using Twisted APIs to do asynchronous things, then you can only deploy your application in Twisted's WSGI container.\nYou should probably just use Twisted Web wi...
[ 5, 5 ]
[]
[]
[ "asynchronous", "python", "twisted", "wsgi" ]
stackoverflow_0006759115_asynchronous_python_twisted_wsgi.txt
Q: Cleanup of semaphore in Python I'm using a semaphore to hand work off to another thread in Python. I.e. the master thread will put an item on a queue, then call the semaphore's release method; the worker thread will call acquire on the semaphore, then pop an item off the queue to work on. There's also a special T...
Cleanup of semaphore in Python
I'm using a semaphore to hand work off to another thread in Python. I.e. the master thread will put an item on a queue, then call the semaphore's release method; the worker thread will call acquire on the semaphore, then pop an item off the queue to work on. There's also a special TERMINATE item that the master can pu...
[ "#1: Yes, it's safe to abandon the semaphore with a non-zero count. It's just a value after all.\n#2: It's nicer to reduce the amount of code. Strive to write the minimum amount of clear code for a correct implementation.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "semaphore" ]
stackoverflow_0007313898_multithreading_python_semaphore.txt
Q: Matlab Colon Operator equivalent in Vpython After spending the last few months learning about MATLAB, it seems I need to switch to vpython! MATLAB's colon operator comes in handy often and I haven't found an equivalent in vpython. For reference, in MATLAB: -3:3 = [-3, -2, -1, 0, 1, 2, 3] Is there any easy way to d...
Matlab Colon Operator equivalent in Vpython
After spending the last few months learning about MATLAB, it seems I need to switch to vpython! MATLAB's colon operator comes in handy often and I haven't found an equivalent in vpython. For reference, in MATLAB: -3:3 = [-3, -2, -1, 0, 1, 2, 3] Is there any easy way to do the same thing in vPython?
[ "I don't know vpython, but after perusing its tutorial, I would guess it is the same as in Python:\nrange(-3,4)\n# [-3, -2, -1, 0, 1, 2, 3]\n\n", "If you use numpy, you can use numpy.r_ :\n>>> import numpy as np\n>>> np.r_[-3:4]\narray([-3, -2, -1, 0, 1, 2, 3])\n>>> np.r_[-3:4, -5:7]\narray([-3, -2, -1, 0, ...
[ 2, 2 ]
[]
[]
[ "matlab", "python", "vpython" ]
stackoverflow_0007312642_matlab_python_vpython.txt
Q: How to unit-test post request for multiple checkboxes with the same name under webapp2 Using webapp2 I create unit tests for a form where there are checkboxes for votes so multiple values can be posted for the vote field and they are retrieved via request.POST.getall('vote'): <input type="checkbox" name="vote" val...
How to unit-test post request for multiple checkboxes with the same name under webapp2
Using webapp2 I create unit tests for a form where there are checkboxes for votes so multiple values can be posted for the vote field and they are retrieved via request.POST.getall('vote'): <input type="checkbox" name="vote" value="Better"> <input type="checkbox" name="vote" value="Faster"> <input type="checkbox" name=...
[ "POST data is encoded using query string encoding, and multiple items by the same name are represented by repeating the key with different values. For instance:\nvote=Better&vote=Faster&vote=Stronger\n\nPython has library functions to do this for you, though:\nurllib.urlencode({\n 'vote': ['Better', 'Faster', 'Str...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python", "unit_testing", "webapp2" ]
stackoverflow_0007313124_google_app_engine_python_unit_testing_webapp2.txt
Q: Python Interpreter not installed after installing Aptana Studio3 I was under the impression that installing Aptana Studio 3 also installed the python interpreter. when I try to create a PyDev project it says that "Project Interpreter not specified" So it will not let me proceed. Is there any documentation on how t...
Python Interpreter not installed after installing Aptana Studio3
I was under the impression that installing Aptana Studio 3 also installed the python interpreter. when I try to create a PyDev project it says that "Project Interpreter not specified" So it will not let me proceed. Is there any documentation on how to proceed configuring the interpreter for Studio 3? I am using the lat...
[ "I'd probably recommend you just download Python from the official site, and configure Aptana to find it.\nYou can download the latest version of Python from here:\nhttp://www.python.org/download/\nYou didn't specify whether you were using Python 2.x or Python 3.x? For compatibility reasons, I'd probably go with Py...
[ 18 ]
[]
[]
[ "aptana", "pydev", "python", "windows_7" ]
stackoverflow_0007314139_aptana_pydev_python_windows_7.txt
Q: faster parsing a file for all list elements and apending into new files based on the list elements I am trying to parse a log file with threadids in every like. There could be any number of threads that can be configured. All threads write to the same log file and I am parsing the log file and creating new files s...
faster parsing a file for all list elements and apending into new files based on the list elements
I am trying to parse a log file with threadids in every like. There could be any number of threads that can be configured. All threads write to the same log file and I am parsing the log file and creating new files specific for each thread in order to check them later. Below I am capturing the threadids in a list. The ...
[ "Assuming you can fit the whole log file into memory, I'd keep a dictionary mapping thread IDs to lines written by that thread, and then write out whole files at the end.\nthread_map = {} # keys are thread IDs; values are lists of log lines\nfor line in open(filetoopen):\n for i in sThdiD:\n if i in line:\n ...
[ 1 ]
[]
[]
[ "append", "file", "list", "parsing", "python" ]
stackoverflow_0007293635_append_file_list_parsing_python.txt
Q: Index Error When Running Basic Web Scrape in Python I'm using Python 2.7. When I try to run this code, I get a problem when the function hits print findPatTitle[i], and python returns "Index Error: list index out of range". I'm taking this code from the 13th python tutorial on youtube, and I'm pretty sure the code...
Index Error When Running Basic Web Scrape in Python
I'm using Python 2.7. When I try to run this code, I get a problem when the function hits print findPatTitle[i], and python returns "Index Error: list index out of range". I'm taking this code from the 13th python tutorial on youtube, and I'm pretty sure the code is identical, so I don't understand why I would get a ra...
[ "If you regex managed to find out the title and link tags you would be getting a list of matched strings when using the findall. In that case, you can just iterate through them and print it.\nLike:\nfor title in findPatTitle:\n print title\n\nfor link in findPatLink:\n print link\n\nThe Index Error you are ge...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0007314624_beautifulsoup_python_web_scraping.txt
Q: Monitoring contents of files/directories? I'm looking for a cross-platform file monitoring python package? I know it is possible to monitor files on windows using pywin32, and there are packages working on Linux/Unix but does anyone know about a cross-platform one? A: I'm working on an MIT-licensed library that ...
Monitoring contents of files/directories?
I'm looking for a cross-platform file monitoring python package? I know it is possible to monitor files on windows using pywin32, and there are packages working on Linux/Unix but does anyone know about a cross-platform one?
[ "I'm working on an MIT-licensed library that helps Python \nprograms monitor file system events as portably as possible. \nThere are differences that I'm trying to iron out. Highly\nalpha version at the moment:\nCheck it out here:\nhttp://github.com/gorakhargosh/watchdog/\nPatches and contributions are welcome. \nH...
[ 96, 33, 3, 2, 0 ]
[]
[]
[ "cross_platform", "file", "filesystems", "monitoring", "python" ]
stackoverflow_0000597903_cross_platform_file_filesystems_monitoring_python.txt
Q: Fill in textarea within tags with python mechanize I'm having a problem with mechanize registering a text area field from within a tag. Example URL: http://www.gegononta.gr/register.php Code: mech = mechanize.Browser() url = "http://www.gegononta.gr/register.php" response = mech.open(url) mech.select_form(nr=1)...
Fill in textarea within tags with python mechanize
I'm having a problem with mechanize registering a text area field from within a tag. Example URL: http://www.gegononta.gr/register.php Code: mech = mechanize.Browser() url = "http://www.gegononta.gr/register.php" response = mech.open(url) mech.select_form(nr=1) mech.form.set_all_readonly(False) print mech.form Outp...
[ "<textarea cols=\"40\" rows=\"3\" name=\"recaptcha_challenge_field\"></textarea>\n\nis actually not a field that mechanize can fill out.\n" ]
[ 0 ]
[]
[]
[ "mechanize", "python", "screen_scraping", "textarea" ]
stackoverflow_0007231423_mechanize_python_screen_scraping_textarea.txt
Q: choosing between android and iOS for a programming novice I've been wanting to get into mobile/tablet app development but I'm not sure whether to go with iOS or Android. Here are a few specific questions I had: What would you recommend for someone who has a background in python and C++? Is developing for the h...
choosing between android and iOS for a programming novice
I've been wanting to get into mobile/tablet app development but I'm not sure whether to go with iOS or Android. Here are a few specific questions I had: What would you recommend for someone who has a background in python and C++? Is developing for the honeycomb os for tablets pretty much the same as android develop...
[ "\nWhat would you recommend for someone who has a background in python\n and C++?\n\nAndroid uses Java as the main programming language, iOS uses Objective-C.\nIMHO Java is easier to learn and more consistent compared to Obj-C. \n\nIs developing for the honeycomb os for tablets pretty much the same as\n android d...
[ 3, 2, 1 ]
[]
[]
[ "android", "c++", "ios", "python" ]
stackoverflow_0007315126_android_c++_ios_python.txt
Q: regex to remove hyphens and spaces I've got the string: <u>40 -04-11</u> How do I remove the spaces and hyphens so it returns 400411? Currently I've got this: (<u[^>]*>)(\-\s)(<\/u>) But I can't figure out why it isn't working. Any insight would be appreciated. Thanks A: (<u[^>]*>)(\-\s)(<\/u>) Your pattern ...
regex to remove hyphens and spaces
I've got the string: <u>40 -04-11</u> How do I remove the spaces and hyphens so it returns 400411? Currently I've got this: (<u[^>]*>)(\-\s)(<\/u>) But I can't figure out why it isn't working. Any insight would be appreciated. Thanks
[ "(<u[^>]*>)(\\-\\s)(<\\/u>)\n\nYour pattern above doesn't tell your regex where to expect numbers.\n(<u[^>]*>)(?:-|\\s|(\\d+))*(<\\/u>)\n\nThat should get you started, but not being a python guy, I can't give you the exact replacement syntax. Just be aware that the digits are in a repeating capture group.\nEdit: Th...
[ 6, 3, 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007314802_python_regex.txt
Q: Spell check program in python Exercise problem: "given a word list and a text file, spell check the contents of the text file and print all (unique) words which aren't found in the word list." I didn't get solutions to the problem so can somebody tell me how I went and what the correct answer should be?: As a...
Spell check program in python
Exercise problem: "given a word list and a text file, spell check the contents of the text file and print all (unique) words which aren't found in the word list." I didn't get solutions to the problem so can somebody tell me how I went and what the correct answer should be?: As a disclaimer none of this parses in...
[ "There are many things wrong with this code - I'm going to mark some of them below, but I strongly recommend that you read up on Python control flow constructs, comparison operators, and built-in data types.\na=list[....,.....,....,whatever goes here,...]\n\ndata = open(C:\\Documents and Settings\\bhaa\\Desktop\\bl...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007315114_python.txt
Q: how to sync two ftp server by python I have two FTP server a and b, I need to copy files from a server to b server. Downloading the file from a and upload to b is too complicate, I want to write a script by python to do this on my desktop, just type the command below it will do the job. python syncftp.py a.com(so...
how to sync two ftp server by python
I have two FTP server a and b, I need to copy files from a server to b server. Downloading the file from a and upload to b is too complicate, I want to write a script by python to do this on my desktop, just type the command below it will do the job. python syncftp.py a.com(source server) folder(folder name in source ...
[ "For starters, you have http://www.csync.org/ which is sort of a rsync (but since rsync only works with SSH and not FTP) but for HTTP/FTP transfers.\nIf you don't like that option there's always \"lftp\" or \"curlftpfs\", stackoverflow has a sister-site which provides your answer:\nhttps://serverfault.com/questions...
[ 3 ]
[ "This sounds like a job for rsync to me. As the name lets suggest, it can recursively sync files and directories (also with compression and other stuff).\n" ]
[ -1 ]
[ "ftp", "python", "synchronization" ]
stackoverflow_0007315294_ftp_python_synchronization.txt
Q: Is it possible to combine a slice with a regular expression in a search pattern using re.search? e[1] is equal to 192.168.1.1. I would like to add regular expression to this search to prevent a match against 192.168.11. Can anyone help? I have beat my head against this for a while. I get a syntax error if I try...
Is it possible to combine a slice with a regular expression in a search pattern using re.search?
e[1] is equal to 192.168.1.1. I would like to add regular expression to this search to prevent a match against 192.168.11. Can anyone help? I have beat my head against this for a while. I get a syntax error if I try to append anything after the slice. re.search(e[1], '192.168.1.11') <_sre.SRE_Match object at 0...
[ "Since e[1] is a string you can add to it with the '+' operator. For example, you can add r'\\b' to set a word boundary (note the raw string; without the 'r' prefix '\\b' is a backspace): \n>>> e = ['', '192.168.1.1']\n>>> pattern = r'\\b' + re.escape(e[1]) + r'\\b' #remember to escape e[1]\n\n>>> re.search(patte...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007315394_python.txt
Q: qml pyside and switches I am coding my application Groundwork and I am using pyside to develop the application. The only hiccup I am having is getting the qml switch to activate. Currently I have in the qml file: signal buttonClicked; //function start(){text.text="started";buttonClicked()} Switch { id:switchC...
qml pyside and switches
I am coding my application Groundwork and I am using pyside to develop the application. The only hiccup I am having is getting the qml switch to activate. Currently I have in the qml file: signal buttonClicked; //function start(){text.text="started";buttonClicked()} Switch { id:switchComponent anchors.vertical...
[ "I'm a little bit confused by your code (and the Switch is missing) so I can only guess.\nCalling start() in the Text component seems wrong to me. It should only be\nText {\n ...\n text: switchComponent.checked ? \"GROUNDWORK ON\" : \"Press to Start\"\n}\n\nThe text doesn't have to be set explicitely anymore ...
[ 0 ]
[]
[]
[ "meego", "pyside", "python", "qml", "qt" ]
stackoverflow_0007313844_meego_pyside_python_qml_qt.txt
Q: Xpath query 'like' substitution Okay, so I've got some example xml that looks like this: <Node name="details"> <Node name="1130482269"> <Val name="type"><u>2</u></Val> <Val name="owner"><n/></Val> <Val name="account_number"><u>99-71-39</u></Val> </Node> <Node name="570722270"> <Val...
Xpath query 'like' substitution
Okay, so I've got some example xml that looks like this: <Node name="details"> <Node name="1130482269"> <Val name="type"><u>2</u></Val> <Val name="owner"><n/></Val> <Val name="account_number"><u>99-71-39</u></Val> </Node> <Node name="570722270"> <Val name="type"><u>2</u></Val> <Va...
[ "Yes, it is possible using translate() function. Example:\n\"translate(Node/Node[@name='1130482269']/Val[@name='account_number'],'- ','')\"\n\nwill output 997139.\nYou can use then (code line broken for readability):\n\"translate(\n /Node/Node[@name='\" + \n str(accountnumber) + \n \"']/Val[@name='account_numbe...
[ 2, 0 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0007313394_python_xpath.txt
Q: Python communicate with a subprocess I have a subprocess which is constantly producing data, but most of the data I'm not interested in. However occasionally, at random times, I need to grab a sample of the output - the thing is I need to read it at well defined boundaries. For example, let's assume the process ...
Python communicate with a subprocess
I have a subprocess which is constantly producing data, but most of the data I'm not interested in. However occasionally, at random times, I need to grab a sample of the output - the thing is I need to read it at well defined boundaries. For example, let's assume the process produces a constant 100 bytes per second a...
[ "Well I am new to python, but it seems proc.communicate or proc.stdout.readline/readlines waits till the process has completed.\nAs per my knowledge, you can implement a rotational logging and redirect output to a file, then using subprocess you can fire tailf -n XX logfile, in a loop until the program ends, and pr...
[ 2, 1 ]
[ "import subprocess\nsubProc= subprocess.Popen(['tail','/dev/random'],stdout=subprocess.PIPE)\nsubProc.stdout[400:499] ?\n\nor\nsubProc.stdout.seek(400).read(100)\n\nif those doesn't work. try:\nvar = subProc.stdout\nvar[400:499]\n\nAlso to get proper output from your subprocess you need to flush() once in a while w...
[ -1 ]
[ "producer_consumer", "python", "streaming", "subprocess" ]
stackoverflow_0007315212_producer_consumer_python_streaming_subprocess.txt
Q: How do I create a macro, using Bottle's SimpleTemplate engine, that will be available in several templates? I need to format a link in certain places of my Bottle application. Previously all of the links were in one SimpleTemplate file, and I defined a macro that looks like this: %def mylink(obj): <a class="my...
How do I create a macro, using Bottle's SimpleTemplate engine, that will be available in several templates?
I need to format a link in certain places of my Bottle application. Previously all of the links were in one SimpleTemplate file, and I defined a macro that looks like this: %def mylink(obj): <a class="mylink" href="{{ get_url('view', id=obj.id) }}">{{ obj.title }}</a> %end Wherever I needed to format a link to an ...
[ "The %include statement renderes the included template immediately. \nMyby you can solve this using the %rebase command, putting your macro into the base template.\n" ]
[ 0 ]
[]
[]
[ "bottle", "python", "templates" ]
stackoverflow_0006864176_bottle_python_templates.txt
Q: Django: STATIC_URL adds appname to the url I have configured my static settings like so: STATIC_ROOT = os.path.join(SITE_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( ('js', os.path.join(STATIC_ROOT, 'js')), ('css', os.path.join(STATIC_ROOT, 'css')), ) STATICFILES_FINDERS = ( 'django.co...
Django: STATIC_URL adds appname to the url
I have configured my static settings like so: STATIC_ROOT = os.path.join(SITE_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( ('js', os.path.join(STATIC_ROOT, 'js')), ('css', os.path.join(STATIC_ROOT, 'css')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', ...
[ "Since you're using the django built-in developement server, try to remove the following line from your urls.py:\nurlpatterns += staticfiles_urlpatterns()\n\nIn production, you'de better not serve static files with django, so use the collectstatic command.\nedit\nIf settings.py, try something like this:\nSTATIC_ROO...
[ 3 ]
[]
[]
[ "django", "django_staticfiles", "python" ]
stackoverflow_0007307549_django_django_staticfiles_python.txt
Q: Django GenericManyToMany? I want to make my Book model belongs to multiple Libraries, Collections, References and Editors, together. Is it possible to do it with generic relations? Like that: content_type = generic.GenericManyToMany(ContentType) from django.conf import settings from django.contrib.contenttypes im...
Django GenericManyToMany?
I want to make my Book model belongs to multiple Libraries, Collections, References and Editors, together. Is it possible to do it with generic relations? Like that: content_type = generic.GenericManyToMany(ContentType) from django.conf import settings from django.contrib.contenttypes import generic from django.contr...
[ "I dont think there is something built into django, but a many to many relation is more or less just a connection table.\none possible solution would be to do something like this:\nclass Book(models.Model):\n pass\n\nclass BookConnection(models.Model):\n book = models.ForeignKey(Book)\n content_type = mode...
[ 1 ]
[]
[]
[ "django", "django_models", "generics", "python" ]
stackoverflow_0003746737_django_django_models_generics_python.txt
Q: I want to make Atom Reader with Python I'm trying to make an Atom Reader (0.3) with Python. I'm familiar with php and I want some equivalent commands in python. If I were using php, I would use file_get_contents and parse those Atom from it. Maybe use Simplexml parser. Is there equivalent commands like $file_get_c...
I want to make Atom Reader with Python
I'm trying to make an Atom Reader (0.3) with Python. I'm familiar with php and I want some equivalent commands in python. If I were using php, I would use file_get_contents and parse those Atom from it. Maybe use Simplexml parser. Is there equivalent commands like $file_get_contents? Also I have downloaded Universal Fe...
[ "Have a look at the documentation of Universal Feed Parser. The frontpage is nothing but examples:\n>>> import feedparser\n>>> d = feedparser.parse(\"http://feedparser.org/docs/examples/atom10.xml\")\n>>> d['feed']['title'] # feed data is a dictionary\nu'Sample Feed'\n\n" ]
[ 5 ]
[]
[]
[ "feed", "php", "python" ]
stackoverflow_0007317365_feed_php_python.txt
Q: Getting Notified on "Ethernet cable plugged in" events in linux I am writing a Python Application running on linux. I want to be able to register and be notified by the system if a network cable is plugged in/ out. I am already using pyUdev (python bindings for libUdev) in order to get notified for USB plug in eve...
Getting Notified on "Ethernet cable plugged in" events in linux
I am writing a Python Application running on linux. I want to be able to register and be notified by the system if a network cable is plugged in/ out. I am already using pyUdev (python bindings for libUdev) in order to get notified for USB plug in events. However, because the network eth0 module (for example) always re...
[ "There are many ways to get the \"UP\" status of a network interface via polling, ranging from simply parsing ifconfig output, to reading the status of /proc/net/... pseudo-files.\nHowever, for a way to be notified (i.e. not poll yourself) for such events, your best option on Ubuntu is to use the netplug package. I...
[ 1, 0 ]
[]
[]
[ "dbus", "ethernet", "linux", "python", "udev" ]
stackoverflow_0007101297_dbus_ethernet_linux_python_udev.txt
Q: Django. Empty_label custom value I want to change the value of default empty_label of field. So I did something like this with my field in: class RFXDigestModelForm(ModelForm): Time_frame_is_realistic = ModelChoiceField( queryset=models.RFXDigest.objects.all(), empty_label="(Nothing)", ...
Django. Empty_label custom value
I want to change the value of default empty_label of field. So I did something like this with my field in: class RFXDigestModelForm(ModelForm): Time_frame_is_realistic = ModelChoiceField( queryset=models.RFXDigest.objects.all(), empty_label="(Nothing)", ) class Meta: model = mod...
[ "Don't use the widgets dictionary if you're manually defining the field - put it in the field declaration.\nTime_frame_is_realistic = ModelChoiceField(queryset=models.RFXDigest.objects.all(),\n empty_label=\"(Nothing)\",\n widget=rf...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007318310_django_django_forms_python.txt
Q: What am I doing wrong(implementing alternative equality with overloading in python) A person asked a question on SO about how to get a list unique function in python with an alternative equality function. I was thinking it could be done by inheriting from the element class and overloading the equality function imp...
What am I doing wrong(implementing alternative equality with overloading in python)
A person asked a question on SO about how to get a list unique function in python with an alternative equality function. I was thinking it could be done by inheriting from the element class and overloading the equality function import functools @functools.total_ordering class ffloat(float): def __eq__(self,other): ...
[ "This is not a valid equality function, since it's not transitive:\nmfloat(0) == mfloat(1) == mfloat(2), but mfloat(0) != mfloat(2).\nAlso note that in order to be used in a set, you must override __hash__ so that the following property holds for all instances a, b of your class:\na == b ⇒ hash(a) == hash(b)\n\nset...
[ 8 ]
[]
[]
[ "equality", "python", "wrapper" ]
stackoverflow_0007318398_equality_python_wrapper.txt
Q: Django - Passing parameters to inline formset I am using inlineformset_factory to create fields for a many to many relationship between Clients and Sessions, with an intermediary Attendance model. I have the following in my views file: AttendanceFormset = inlineformset_factory( Session, Attendance, for...
Django - Passing parameters to inline formset
I am using inlineformset_factory to create fields for a many to many relationship between Clients and Sessions, with an intermediary Attendance model. I have the following in my views file: AttendanceFormset = inlineformset_factory( Session, Attendance, formset=BaseAttendanceFormSet, exclude=('user'), ...
[ "How about utilizing the inlineformset_factory's formfield_callback param instead of providing a formset ? Provide a callable which in turns returns the field which should be used in the form.\nForm fields callback gets as 1st parameter the field, and **kwargs for optional params (e.g: widget).\nFor example (using ...
[ 8 ]
[]
[]
[ "django", "formset", "python" ]
stackoverflow_0007310861_django_formset_python.txt
Q: How to skip the inaccessible folders with python's os.listdir? I'm working with python and javascript and I'm having a problem in a specific part of my program. I need to show the user/client the contents of a specific directory. I do that using python's os.listdir. This function is giving me all the contents of t...
How to skip the inaccessible folders with python's os.listdir?
I'm working with python and javascript and I'm having a problem in a specific part of my program. I need to show the user/client the contents of a specific directory. I do that using python's os.listdir. This function is giving me all the contents of the directory, even inaccessible folders (which I don't want to show ...
[ "for el in os.listdir('C:\\Users\\MyUser'):\n try:\n (check if you can open, if so, you can show this folder)\n except WindowsError:\n pass \n\n", "for myFile in myList():\n if not os.access(myFile, os.R_OK):\n myList.pop(myList.index(myFile))\n\nList should include paths only. Else...
[ 3, 1 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0007318712_directory_python.txt
Q: Add multiple Checkbutton and store the result in a list I want to add several Checkbutton in my Tkinter app. I don't know the number of Checkbutton I insert when I launch the program (depend on a DB call). I wrote this code: for row in information: self.__checkBoxValue.append(StringVar()) Checkbutton(self...
Add multiple Checkbutton and store the result in a list
I want to add several Checkbutton in my Tkinter app. I don't know the number of Checkbutton I insert when I launch the program (depend on a DB call). I wrote this code: for row in information: self.__checkBoxValue.append(StringVar()) Checkbutton(self.__frame2, variable=self.__checkBoxValue[-1], onvalue="%s*%s" ...
[ "Try setting the value of the StringVar instance to either your onvalue or offvalue.\n" ]
[ 0 ]
[]
[]
[ "list", "python", "tkinter" ]
stackoverflow_0007318968_list_python_tkinter.txt
Q: How to iterate over a file in python in a particular way as described below. A file ProgramInput.txt has this as its content <start> content ... ... ... <stop> <start> content ... ... <stop> and so on How do I iterate over the txt file , so that I take out the content between each and and store it in a differe...
How to iterate over a file in python in a particular way as described below.
A file ProgramInput.txt has this as its content <start> content ... ... ... <stop> <start> content ... ... <stop> and so on How do I iterate over the txt file , so that I take out the content between each and and store it in a different file in each iteration ?
[ "The easiest way, I can think of it is\ncontents = []\n\nwith open('file') as f:\n for line in f:\n if line.startswith('<start>'):\n pass\n contents.append(line)\n\ncontents = \"\".join(contents)\nsections = contents.split(\"<stop>\")\n\nBasically, make use of the pattern behavior and...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007319021_python.txt
Q: Mock an object in a method that is not a parameter in java similar to the following python code? following is a very cool mocking with python, is there anyway to do that also in java? mockpath = os.path mockpath.isdir = Mock(return_value=False) myObj = MyClass() myObj.invoke_some_method() myObj.some_other_method.a...
Mock an object in a method that is not a parameter in java similar to the following python code?
following is a very cool mocking with python, is there anyway to do that also in java? mockpath = os.path mockpath.isdir = Mock(return_value=False) myObj = MyClass() myObj.invoke_some_method() myObj.some_other_method.assert_called_with(False) is anything like this possible in java? meaning updating the return values a...
[ "Mockito supports partial mocks as well as mocking out a method in a real class. The latter looks more similar to your Python example.\nI believe EasyMock supports the same thing but I'm having trouble finding where it is in the documentation.\n", "I found that powermock library is the most suitable for this in j...
[ 1, 1 ]
[]
[]
[ "java", "junit", "mocking", "python", "python_unittest" ]
stackoverflow_0006776448_java_junit_mocking_python_python_unittest.txt
Q: python threading - a problem I can't figure out the problem in this code. class Threader(threading.Thread): def __init__(self, queue, url, host): threading.Thread.__init__(self) self.queue = queue self.url = url self.host = host def run(self): print self.url # http...
python threading - a problem
I can't figure out the problem in this code. class Threader(threading.Thread): def __init__(self, queue, url, host): threading.Thread.__init__(self) self.queue = queue self.url = url self.host = host def run(self): print self.url # http://www.stackoverflow.com ...
[ "Your Code doesn't work, I have taken the liberty to adapt it a bit (imports, also it doesn't know about Document and self.con), and make it compatible with python2 (that's what I use here at the moment) - it works:\nfrom __future__ import with_statement\nimport threading, Queue, urllib2, contextlib\n\nclass Thread...
[ 2, 0 ]
[]
[]
[ "multithreading", "python", "urllib" ]
stackoverflow_0007319328_multithreading_python_urllib.txt
Q: Repeating "events" in a calendar: CPU vs Database I'm building a calendar system from the ground up (requirement, as I'm working with a special type of calendar alongside Gregorian) , and I need some help with logic. I'm writing the application in Django and Python. Essentially, the logical issues I'm running int...
Repeating "events" in a calendar: CPU vs Database
I'm building a calendar system from the ground up (requirement, as I'm working with a special type of calendar alongside Gregorian) , and I need some help with logic. I'm writing the application in Django and Python. Essentially, the logical issues I'm running into is how to persist as few objects as possible as smart...
[ "This could become a heated discussion, as date logic usually is much harder than it first looks and everyone will have her own idea how to make things happen. \nI would probably sacrifice some db space and have the models be as dumb as possible (e.g by not having to define anomalies to a series). The repeat condit...
[ 3, 1, 1, 0 ]
[]
[]
[ "calendar", "database_design", "django", "logic", "python" ]
stackoverflow_0007313246_calendar_database_design_django_logic_python.txt
Q: Debug slow program; Restart from middle I have a program which has slow computations and I wish to debug the algorithm. Now it's very tedious to always rerun everything and I'd rather restart from the middle of the program. Can you think of some clever way to achieve this? The first vague idea is to define checkpo...
Debug slow program; Restart from middle
I have a program which has slow computations and I wish to debug the algorithm. Now it's very tedious to always rerun everything and I'd rather restart from the middle of the program. Can you think of some clever way to achieve this? The first vague idea is to define checkpoints (where I make a function call) where I s...
[ "Make your program more modular. Ideally, the main block of code should look something like\nimport config\nimport my_numerics\nimport post_processing\n\nmy_numerics.configure(config.numerics)\nvalues = my_numerics.run()\n\npost_processing.run(values, config.post_processing)\n\nYou get the idea. It's then easy to m...
[ 6, 3, 2, 1, 0, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0007244369_debugging_python.txt
Q: Help needed with pygame spritegroups I have modified the pygame Chimp example by replacing the Chimp image with the circle and a line using the draw method drawn from the center of the circle and also by replacing the fist with a 10 by 10 black box surface. My problem is this. When the black box(fist) punches the ...
Help needed with pygame spritegroups
I have modified the pygame Chimp example by replacing the Chimp image with the circle and a line using the draw method drawn from the center of the circle and also by replacing the fist with a 10 by 10 black box surface. My problem is this. When the black box(fist) punches the circle(chimp), the circle(chimp) has to ro...
[ "The answer lies in the punch method:\ndef punch(self,target) :\n if not self.punching:\n self.punching = 1\n hitbox = self.rect.inflate(-5,-5)\n return hitbox.colliderect(target.rect)\n\nThe attribute self.punching is set to 1 for the first chimp. For all the others, the block isn't execute...
[ 1 ]
[]
[]
[ "pygame", "python", "sprite" ]
stackoverflow_0007319124_pygame_python_sprite.txt
Q: How to get a pygtk entry accept only floats? I want the user to be able to type only a float (that is, numbers from 0 to 9 and the decimal point should show, other characters should not). How can I do that ? edit I need to get values like "4" or "3.5" or ".9", nothing like "10e23" Inconsistent values should also b...
How to get a pygtk entry accept only floats?
I want the user to be able to type only a float (that is, numbers from 0 to 9 and the decimal point should show, other characters should not). How can I do that ? edit I need to get values like "4" or "3.5" or ".9", nothing like "10e23" Inconsistent values should also be rejected, such as "10.12.45" ...
[ "I've finally an acceptable answer thanks to SO question \"How to extract a floating number from a string in Python\"\n numeric_const_pattern = r\"\"\"\n [-+]? # optional sign\n (?:\n (?: \\d* \\. \\d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc\n |\n (?: \\d+ \\.? ) # 1. 12. 123. etc 1 12 12...
[ 2, 1, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0007318965_pygtk_python.txt
Q: Terminal window close eventhandler in python for linux My Python program is running in ubuntu terminal window.If the terminal window is directly closed, need an event to occur and in that event i will send a message to server that application is exited. I tried with the following and it doesn't work. def window_ha...
Terminal window close eventhandler in python for linux
My Python program is running in ubuntu terminal window.If the terminal window is directly closed, need an event to occur and in that event i will send a message to server that application is exited. I tried with the following and it doesn't work. def window_handler(self): CommandExecutor.processCommands(0, ProjectCo...
[ "Closing a terminal will send SIGHUP to the processes which have that terminal's pseudo-tty as their controlling terminal.\nThus catching SIGHUP instead of SIGTERM should work.\nI am unsure if there are some special considerations that you need to take in account when handling signals in Python, but that is a topic...
[ 1 ]
[]
[]
[ "linux", "python", "signals" ]
stackoverflow_0007318836_linux_python_signals.txt
Q: NumPy: Apply an index selecting function to multiple axes I'm writing code to optimize quantities that depend on a variable number of parameters. For the optimization I would like to apply index selecting functions such as numpy.argmax and numpy.argmin across multiple axes at once. Below is the code I'm using ri...
NumPy: Apply an index selecting function to multiple axes
I'm writing code to optimize quantities that depend on a variable number of parameters. For the optimization I would like to apply index selecting functions such as numpy.argmax and numpy.argmin across multiple axes at once. Below is the code I'm using right now. Is there a more built-in or efficient approach to per...
[ "If you are selecting over trailing axes, you can reshape the trailing axes to -1, and apply func to axis=-1:\ndef f(func, array, start):\n shape = array.shape\n tmp = array.reshape(shape[:start] + (-1,))\n indices = func(tmp, axis=-1)\n return np.unravel_index(indices, shape[start:])\n\n" ]
[ 2 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0007315747_arrays_indexing_numpy_python.txt
Q: Psycopg2 not linked correctly, wrong includes or something? I'm having trouble in getting Django work with a postgresl database on my webhosting provider. My situation is as follows: I have an account on my webhosting provider, I do not have root-priviledges or the ability to install anything except locally in my ...
Psycopg2 not linked correctly, wrong includes or something?
I'm having trouble in getting Django work with a postgresl database on my webhosting provider. My situation is as follows: I have an account on my webhosting provider, I do not have root-priviledges or the ability to install anything except locally in my home folder. I'm running Django through fcgi (because that is the...
[ "yes, it looks like a versioning problem. more exactly the python running is lower than the one psycopg2 is built for (2.6)\nyou can check the python version by running 'python -V' or calling 'sys.version_info', but if your distribution is a debian stable then the default python is 2.5\n" ]
[ 0 ]
[]
[]
[ "django", "postgresql", "psycopg2", "python" ]
stackoverflow_0007319076_django_postgresql_psycopg2_python.txt
Q: Python: missing class attribute __module__ when using type()? I'm attempting to dynamically construct some classes which are subclasses of django's models.Model. My code looks like this: MyModel = type('MyModel', (models.Model,), { 'field': models.BooleanField() }) When Django tries to load this, it give...
Python: missing class attribute __module__ when using type()?
I'm attempting to dynamically construct some classes which are subclasses of django's models.Model. My code looks like this: MyModel = type('MyModel', (models.Model,), { 'field': models.BooleanField() }) When Django tries to load this, it gives the following exception: Traceback (most recent call last): Fil...
[ "May be metaclasses is best choice for you needs than low-level type()?\nBut in most cases you can use __name__ as a value for __module__ like\nMyModel = type('MyModel', (models.Model,), {\n 'field': models.BooleanField(),\n '__module__': __name__,\n})\n\nDjango uses __module__ value for determine which djang...
[ 16 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007320705_django_python.txt
Q: Converting C++ into Python code, Looping through directories and getting the timestamp from a file? I have been given the task of converting a C++ script into python script. The aim of the script is to loop through all the directories (by start and end date) in the mediaDB and calculate what size the zipfile is go...
Converting C++ into Python code, Looping through directories and getting the timestamp from a file?
I have been given the task of converting a C++ script into python script. The aim of the script is to loop through all the directories (by start and end date) in the mediaDB and calculate what size the zipfile is going to be. I am stuck at getting the for loop to go through the directories, its so different in python ...
[ "You're looking for os.path.walk or glob.glob for enumerating files in a directory subtree, and os.stat (or os.lstat) for getting the timestamp of the most recent modification.\n" ]
[ 2 ]
[]
[]
[ "directory", "filesize", "loops", "python", "timestamp" ]
stackoverflow_0007320898_directory_filesize_loops_python_timestamp.txt
Q: Since when does the bytes() function exist in Python? Since which version does the bytes() function exist in Python? I'm writing some code that has to be compatible with as much versions of python as possible, so this kind of information is very important to me. Is there a good source to find the answer to such qu...
Since when does the bytes() function exist in Python?
Since which version does the bytes() function exist in Python? I'm writing some code that has to be compatible with as much versions of python as possible, so this kind of information is very important to me. Is there a good source to find the answer to such questions easily?
[ "PEP 3112 added support for bytes literal in Python3. Python 3 adopted Unicode as the language’s fundamental string type and denoted 8-bit literals either as b'string' or using a bytes constructor. \nFor future compatiblity, bytes was introduced in Python2.6. But note that in 2.6 bytes is different and serves a di...
[ 7, 0 ]
[]
[]
[ "backwards_compatibility", "compatibility", "python", "python_3.x" ]
stackoverflow_0007320696_backwards_compatibility_compatibility_python_python_3.x.txt
Q: How can I interrupt a blocking method in python? Usually I can interrupt stuff with Ctrl+C, but sometimes when I'm using threads it doesn't work - example below. Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> imp...
How can I interrupt a blocking method in python?
Usually I can interrupt stuff with Ctrl+C, but sometimes when I'm using threads it doesn't work - example below. Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.sleep(100) ^CTraceback (most recent ...
[ "You can kill the Python interpreter with Ctrl+\\.\nThis will send a SIGQUIT instead of SIGINT.\n", "A quick workaround for ^C failing is suspending the process with all threads first with ^Z and then killing it.\nThis works in Linux for many cases when ^C fails, and as I've just tested it works here too (tested ...
[ 3, 1, 0 ]
[]
[]
[ "blocking", "break", "multithreading", "python", "sigint" ]
stackoverflow_0007315981_blocking_break_multithreading_python_sigint.txt
Q: Can I efficiently swap two class instances by swapping __dict__? I have a big class with lots of members, and quite a few references to instances of this class lying around. Unfortunately (for reasonable reasons) all these references are the wrong way around. Instead of re-creating each (and finding and updating e...
Can I efficiently swap two class instances by swapping __dict__?
I have a big class with lots of members, and quite a few references to instances of this class lying around. Unfortunately (for reasonable reasons) all these references are the wrong way around. Instead of re-creating each (and finding and updating everywhere the objects are referenced), or adding an extra level of ind...
[ "Edit\nWhat you're doing is possible, although it will make people cringe because it is hackish. If at all possible, I would suggest that you look at rewriting/refactoring your comparison operators. That will give you the best outcome by far. Of course, not knowing the scope or time-frame involved, it is very diffi...
[ 9, 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007255777_python.txt
Q: Django / Sqlite3 add a row for model with a foreign key I'm new to both Django and SQlite3. I have a model (Person), with a foreign key to (Person_Type): class Person(models.Model): name = models.CharField(max_length=500) pers_type = models.ForeignKey(Person_Type) def __unicode__(self): return...
Django / Sqlite3 add a row for model with a foreign key
I'm new to both Django and SQlite3. I have a model (Person), with a foreign key to (Person_Type): class Person(models.Model): name = models.CharField(max_length=500) pers_type = models.ForeignKey(Person_Type) def __unicode__(self): return self.name class Person_Type(models.Model): pers_type = ...
[ "Person.objects.create(name='Adam', person_type='Appellant') \n\nHere, as person_type argument, create() method expects to get person_type instance not string\nSo just prowide:\npers_type = Person_Type.objects.get(pers_type='Appelant') # assuming pers_type is unique\nPerson.objects.create(name='Adam', pers_type=per...
[ 5 ]
[]
[]
[ "django", "foreign_keys", "python", "shell", "sqlite" ]
stackoverflow_0007321241_django_foreign_keys_python_shell_sqlite.txt
Q: IronPython Excel RTDServer How do you build a Excel RTDServer in Python/IronPython. (IE I want to implement the IRTDServer interface in Python/IronPython. So I can push data into Excel in real time from Python/IronPython) I have looked all over the place but the only examples that I'm able to find are in C#. A: ...
IronPython Excel RTDServer
How do you build a Excel RTDServer in Python/IronPython. (IE I want to implement the IRTDServer interface in Python/IronPython. So I can push data into Excel in real time from Python/IronPython) I have looked all over the place but the only examples that I'm able to find are in C#.
[ "You can use pyrtd that implements an Excel RTD Server.\nYou can find the code on Google Code page of the project\n" ]
[ 0 ]
[]
[]
[ "excel", "ironpython", "ironpython_studio", "python", "rtd" ]
stackoverflow_0007320114_excel_ironpython_ironpython_studio_python_rtd.txt
Q: Python -- Pack Several Objects? Is it possible to 'pack' a python object (say, a list or a dict) to a variable rather than to a file? Ideally, I'd like to 'pack' a couple of different dictionaries, lists etc, and only then, 'concatenate' all the 'packed' info and save it in an external file (say, in a binary forma...
Python -- Pack Several Objects?
Is it possible to 'pack' a python object (say, a list or a dict) to a variable rather than to a file? Ideally, I'd like to 'pack' a couple of different dictionaries, lists etc, and only then, 'concatenate' all the 'packed' info and save it in an external file (say, in a binary format). Is it doable?
[ "See the pickle module. \nhttp://docs.python.org/library/pickle.html\n", "See the json module. http://docs.python.org/library/json.html\nYou can serialize objects with JSON.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007322130_python.txt
Q: Problems serving static files favicon.ico and robots.txt in CherryPy 3.1 When I try to browse to favicon.ico, for instance, I get this error: ValueError: Static tool requires an absolute filename (got 'favicon.ico') I can get to anything in my /images, /css and /js folders. Those are serving just fine. The site...
Problems serving static files favicon.ico and robots.txt in CherryPy 3.1
When I try to browse to favicon.ico, for instance, I get this error: ValueError: Static tool requires an absolute filename (got 'favicon.ico') I can get to anything in my /images, /css and /js folders. Those are serving just fine. The site looks and acts great. It's just these darn two files. Here is my root.conf f...
[ "When you turn on a CherryPy Tool for a particular URL, it's turned on for all \"child\" URL's below it as well. So the [/images], [/css], and [/js] parts of your config seem redundant. So, too, is the [/robots.txt] section.\nThe [/favicon.ico] would be redundant, too, except favicon.ico is special because CherryPy...
[ 5, 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0007308164_cherrypy_python.txt
Q: python script problem I am trying to run a python script, the error that appear is: Traceback (most recent call last): File "/opt/erange/geneMrnaCountsWeighted.py", line 266, in <module> main(sys.argv) File "/opt/erange/geneMrnaCountsWeighted.py", line 51, in main options.extendGenome, options.replaceM...
python script problem
I am trying to run a python script, the error that appear is: Traceback (most recent call last): File "/opt/erange/geneMrnaCountsWeighted.py", line 266, in <module> main(sys.argv) File "/opt/erange/geneMrnaCountsWeighted.py", line 51, in main options.extendGenome, options.replaceModels) File "/opt/erange/...
[ "You're using an old version of that particular script. Compare the old version with the newest version:\nhttp://woldlab.caltech.edu/gitweb/?p=erange.git;a=blob;f=geneMrnaCountsWeighted.py;hb=5e4ae21098dba3d1edcf11e7279da0d84c3422e4\nhttp://woldlab.caltech.edu/gitweb/?p=erange.git;a=blob;f=geneMrnaCountsWeighted.py...
[ 3, 2, 1 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0007323099_biopython_python.txt
Q: Suppress PyQt event temporarily? I'm populating a branch of a QTreeWidget and then setting the expanded attribute on the parent of the branch to true. The itemExpanded signal fires in response, which is not what I want. Is there a temporary way to suppress or absorb signals during a segment of code? A: You can s...
Suppress PyQt event temporarily?
I'm populating a branch of a QTreeWidget and then setting the expanded attribute on the parent of the branch to true. The itemExpanded signal fires in response, which is not what I want. Is there a temporary way to suppress or absorb signals during a segment of code?
[ "You can set blocking of signals using QObject::blockSignals. \nhttp://doc.qt.nokia.com/stable/qobject.html#blockSignals\n\nbool QObject::blockSignals ( bool block )\n If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). If block is false,...
[ 8 ]
[]
[]
[ "pyqt", "python", "qtreewidget" ]
stackoverflow_0007323295_pyqt_python_qtreewidget.txt
Q: how do I close the engine created by sqlalchemy.ext.sqlsoup I'm using sqlsoup to perform a simple query. My question is how do I close the engine ? thanks! import sqlalchemy.ext.sqlsoup as SqlSoup db = SqlSoup('sqlite:///test.sqlite') res = db.people.filter_by(id = 1).all() return res[0] A: I'm not really sure...
how do I close the engine created by sqlalchemy.ext.sqlsoup
I'm using sqlsoup to perform a simple query. My question is how do I close the engine ? thanks! import sqlalchemy.ext.sqlsoup as SqlSoup db = SqlSoup('sqlite:///test.sqlite') res = db.people.filter_by(id = 1).all() return res[0]
[ "I'm not really sure why you think you need this, but here it is:\nimport sqlalchemy.ext.sqlsoup as SqlSoup\nimport sqlalchemy\n\nengine = sqlalchemy.create_engine('sqlite:///test.sqlite')\n\ndb = SqlSoup(engine)\nres = db.people.filter_by(id = 1).first()\n\nengine.dispose()\n\nreturn res\n\nuse Query.first() not Q...
[ 4 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007186961_python_sqlalchemy.txt
Q: How do you get cimport to work in Cython? I have a directory structure as so: /my_module init.py A/ __init__.py a.pyx B/ __init__.py b.pyx In b.pyx I want to cimport functions from A.a. A regular python import works, but a cimport always fails. Also, I'm compiling A/ and B/ separately because I couldn...
How do you get cimport to work in Cython?
I have a directory structure as so: /my_module init.py A/ __init__.py a.pyx B/ __init__.py b.pyx In b.pyx I want to cimport functions from A.a. A regular python import works, but a cimport always fails. Also, I'm compiling A/ and B/ separately because I couldn't figure out how to put a setup.py in the top ...
[ "You have to create a cython declaration file, a .pxd \nIt shall contain only declarations of classes and functions that you want to import.\n" ]
[ 3 ]
[]
[]
[ "cimport", "cython", "distutils", "python", "static_import" ]
stackoverflow_0007295638_cimport_cython_distutils_python_static_import.txt
Q: Elegant way to make RPC Calls to Python Functions in a Django Project I'm in the middle of trying to create a django website to access data in a MySQL database. The intenion is to also create a UI in Dojo (javascript). Also I would like the django backend to also provide webservices (RPC for python functions) to...
Elegant way to make RPC Calls to Python Functions in a Django Project
I'm in the middle of trying to create a django website to access data in a MySQL database. The intenion is to also create a UI in Dojo (javascript). Also I would like the django backend to also provide webservices (RPC for python functions) to allow access to the MySQL database remotely. So for example, if someone w...
[ "what about using REST API?\n", "One possibility to do the comparisons would be to use a dict like so:\ndef func1(someparams):\n #do something\n return True\n\ndef func2(sameparams):\n #do something else\n return True\n\n\n{'func1': func1,\n 'func2': func2}\n\nThen when you get the API call, you look ...
[ 1, 1, 0 ]
[]
[]
[ "django", "json", "python", "rpc", "smd" ]
stackoverflow_0007097576_django_json_python_rpc_smd.txt
Q: Apache mod_wsgi and php in the same domain is it possible to make my webserver run python and php in the same domain? I have a website in python/django that is www.mydomain.com. Now, i have to host a blog in www.mydomain.com/blog in wordpress. Can i make it through? Apache 2.2 mod_wsgi My config now: # RUNS PYTHON...
Apache mod_wsgi and php in the same domain
is it possible to make my webserver run python and php in the same domain? I have a website in python/django that is www.mydomain.com. Now, i have to host a blog in www.mydomain.com/blog in wordpress. Can i make it through? Apache 2.2 mod_wsgi My config now: # RUNS PYTHON <VirtualHost *:80> DocumentRoot /home/padra...
[ "They should be defined in the one VirtualHost, not two separate ones.\nAn Alias directive then needs to be defined for subdir PHP application is at. This will override WSGIScriptAlias for the sub URL.\nAlternatively you need to use methods outlined in:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines...
[ 7 ]
[]
[]
[ "apache", "mod_php", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0007322336_apache_mod_php_mod_wsgi_python_wsgi.txt
Q: How to prevent 'IOError: failed to write data' when client closes connection to Django/WSGI app? I have an iPhone app that is using web services implemented in Python, using Django and Piston, running on an apache server through WSGI. Sometimes the app closes its connection to the server before a call is finished....
How to prevent 'IOError: failed to write data' when client closes connection to Django/WSGI app?
I have an iPhone app that is using web services implemented in Python, using Django and Piston, running on an apache server through WSGI. Sometimes the app closes its connection to the server before a call is finished. When it does this it causes a: [Tue Sep 06 11:29:46 2011] [error] [client 207.35.164.99] mod_wsgi (p...
[ "[disclaimer: this is a \"why it can't be easily done\" explanation, not a solution] \nAs @Slott pointed out, this is definitely the technically correct behavior when stream.close or stream.write is called on a closed socket. However, I understand the motivation for the question... in the context of a wsgi app, cli...
[ 7, 1 ]
[]
[]
[ "apache", "django", "django_piston", "mod_wsgi", "python" ]
stackoverflow_0007322578_apache_django_django_piston_mod_wsgi_python.txt
Q: Stripping spaces between XML nodes with Python Is there a easy way to accomplish the same thing in Python as xsl accomplishes with: <xsl:strip-space elements="*"/> So for instance in the following for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTre...
Stripping spaces between XML nodes with Python
Is there a easy way to accomplish the same thing in Python as xsl accomplishes with: <xsl:strip-space elements="*"/> So for instance in the following for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTree.tostring(elem) when the example nodes are printed...
[ "I believe you need to explicitly manipulate the subtree to strip every text and tail:\nfrom xml.etree import ElementTree\n\nfor event, elem in ElementTree.iterparse(\"/tmp/example.xml\"):\n if elem.tag == \"example\":\n subiter = ElementTree.ElementTree(elem).getiterator()\n for x in subiter:\n ...
[ 5, 4, 1 ]
[]
[]
[ "python", "xml", "xslt" ]
stackoverflow_0001098118_python_xml_xslt.txt
Q: Using Sphinx for documenting projects and modules on demand I use Sphinx for documenting a Python module. I have a master doc directory, where I put individual *.rst files (on for each module component) to be included in the index.rst main file. That works great (please check the source of the Python Library Refer...
Using Sphinx for documenting projects and modules on demand
I use Sphinx for documenting a Python module. I have a master doc directory, where I put individual *.rst files (on for each module component) to be included in the index.rst main file. That works great (please check the source of the Python Library Reference to see exactly how I do it). My problem is when I need to cr...
[ "First I would create a template, such as index_template.rst. Next I would write a shell script that takes one parameter. This parameter would specify the component you want to generate, otherwise it generates an index.rst for all components.\nThen customize your Makefile to support a component parameter. The Makef...
[ 2 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0003507188_python_python_sphinx.txt
Q: error comparing sequences - string interpreted as number I'm trying to do something similar with my previous question. My purpose is to join all sequences that are equal. But this time instead of letters, I have numbers. alignment file can be found here - phylip file the problem is when I try to do this: records =...
error comparing sequences - string interpreted as number
I'm trying to do something similar with my previous question. My purpose is to join all sequences that are equal. But this time instead of letters, I have numbers. alignment file can be found here - phylip file the problem is when I try to do this: records = list(SeqIO.parse(file(filename),'phylip')) I get this error:...
[ "Your PHYLIP file is broken. The header says 161 sequences but there are 166. Fixing that the current version of Biopython seems to load your file fine. Maybe use len(info_plex) when creating the header line.\nP.S. It would have been a good idea to include the version of Biopython in your question.\n", "The code ...
[ 2, 1 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0007309869_biopython_python.txt
Q: How do I initialise my Satchmo website? As an experienced PHP programmer I tend to avoid things like Python. However we all must play with the cards we have been dealt with and I now have to work with a Satchmo website. I have very little python, django and satchmo so I need some help. I'm ok with setting up a dev...
How do I initialise my Satchmo website?
As an experienced PHP programmer I tend to avoid things like Python. However we all must play with the cards we have been dealt with and I now have to work with a Satchmo website. I have very little python, django and satchmo so I need some help. I'm ok with setting up a development server but I cannot get my website t...
[ "To deploy a Django website on a production server, you have to serve it either with Apache+mod_wsgi, nginx+gunicorn, nginx+uwsgi, or any other server supporting WSGI. The Django documentation has a page on deploying Django on Apache with mod_wsgi, for the other solutions, there are plenty of useful documentation a...
[ 3, 1, 1 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0007323936_django_python_satchmo.txt
Q: Python namespaces: How to make unique objects accessible in other modules? I am writing a moderate-sized (a few KLOC) PyQt app. I started out writing it in nice modules for ease of comprehension but I am foundering on the rules of Python namespaces. At several points it is important to instantiate just one object ...
Python namespaces: How to make unique objects accessible in other modules?
I am writing a moderate-sized (a few KLOC) PyQt app. I started out writing it in nice modules for ease of comprehension but I am foundering on the rules of Python namespaces. At several points it is important to instantiate just one object of a class as a resource for other code. For example: an object that represents ...
[ "You can access objects in a module with the . operator just like with a function. So, for example: \n# Module a.py\na = 3\n\n>>> import a\n>>> print a.a\n3\n\nThis is a trivial example, but you might want to do something like:\n# Module EditWidget.py\ntheEditWidget = EditWidget()\n...\n\n# Another module\nimport ...
[ 2, 2, 1 ]
[]
[]
[ "namespaces", "pyqt", "python" ]
stackoverflow_0007313215_namespaces_pyqt_python.txt
Q: Webdriver.quit() crashes python on test end in IE I am using Webdriver implemented through Python to run my selenium test scripts in IE; however, when I call webdriver.quit(), this will randomly cause python to crash. When a test case ends and webdriver.quit is called, a windows prompt pops up detailing that pytho...
Webdriver.quit() crashes python on test end in IE
I am using Webdriver implemented through Python to run my selenium test scripts in IE; however, when I call webdriver.quit(), this will randomly cause python to crash. When a test case ends and webdriver.quit is called, a windows prompt pops up detailing that python.exe has crashed. Upon going to the event viewer and l...
[ "It sounds like a bug in Webdriver, but without a stack trace and the offending function code there's not a whole lot to look at.\nI would bring it up to the developers:\nhttp://code.google.com/p/selenium/\n" ]
[ 0 ]
[]
[]
[ "internet_explorer", "python", "selenium", "webdriver" ]
stackoverflow_0007323967_internet_explorer_python_selenium_webdriver.txt
Q: Packing ironpython app into .exe and Installer I'm not using sharpdevelop or visual studio for ironpython app development. I have my reasons for not using them for app development. What are my console based options for compiling ironpython .exe file and packaging it manually ? Is it possible to create executable ...
Packing ironpython app into .exe and Installer
I'm not using sharpdevelop or visual studio for ironpython app development. I have my reasons for not using them for app development. What are my console based options for compiling ironpython .exe file and packaging it manually ? Is it possible to create executable app with ironpython and pack it using installer ?
[ "I use IronPython\\Tools\\Scripts\\pyc.py to create .exe and then xcopy deployment instead of installer.\n", "I've used pyc and InnoSetup to create my installers. You can also download and run WIX from the command line without using #Develop or Visual Studio. The key is make sure you include all of the DLL's you...
[ 3, 1 ]
[]
[]
[ ".net", "ironpython", "python" ]
stackoverflow_0007313004_.net_ironpython_python.txt
Q: Python script to write exception.KeyError to text file I have nested dictionary as following: Dict1 | level 1-1 | level 2-1-1 | level 3-1-1-1 | core [1] | core [2] | core [3] | level ...
Python script to write exception.KeyError to text file
I have nested dictionary as following: Dict1 | level 1-1 | level 2-1-1 | level 3-1-1-1 | core [1] | core [2] | core [3] | level 3-1-1-2 | core [1] ...
[ "This should be easy to debug by stepping through with pdb\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007323758_python.txt
Q: How to augment a class from an external library with own methods? I have some special cases that I need to test for in django. I am trying to extend the the existing django tests by writing my own test cases. Here is how I am currently doing it. from django.tests import TestCase # define my own method as a functi...
How to augment a class from an external library with own methods?
I have some special cases that I need to test for in django. I am trying to extend the the existing django tests by writing my own test cases. Here is how I am currently doing it. from django.tests import TestCase # define my own method as a function def assertOptionsEqual(self, first, second): # logic here pa...
[ "I think you've covered both options. You can either subclass or monkeypatch. Typically, monkeypatching, actually changing the 3rd party class at runtime is frowned upon but depending on what change you need to make it may be the only way to work around a bug or make sure that every time that class is used it has...
[ 1 ]
[]
[]
[ "class", "inheritance", "methods", "monkeypatching", "python" ]
stackoverflow_0007324162_class_inheritance_methods_monkeypatching_python.txt
Q: Python: efficient syntax for creating a list composed of strings I am new to python and essentially trying to figure out the syntax that replicates this functionality: strings = ["foo", "bar", "apple"] with something similar to strings = [foo, bar, apple] so that I don't have to put quotes around all the entries. ...
Python: efficient syntax for creating a list composed of strings
I am new to python and essentially trying to figure out the syntax that replicates this functionality: strings = ["foo", "bar", "apple"] with something similar to strings = [foo, bar, apple] so that I don't have to put quotes around all the entries. Thanks!
[ "strings = \"foo bar apple\".split()\n\n", "strings = r\"foo, bar, apple\".split(\", \")\n\n", "You could place all the strings in a text file, one string on each line. Then strings = list(open(\"datafile\", \"r\")).\n", "I would say that there is no easier way to create a list of strings than what you're al...
[ 6, 2, 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "python_2.7", "string" ]
stackoverflow_0007323906_list_python_python_2.7_string.txt
Q: Given a module on pypi, is there a way to introspect the module and show all dependencies? For example, I am looking for a command line snippet to list all dependencies of a python module e.g. http://pypi.python.org/pypi/django-celery given the URL. Does one exist ? A: I would use a combination of virtualenv and...
Given a module on pypi, is there a way to introspect the module and show all dependencies?
For example, I am looking for a command line snippet to list all dependencies of a python module e.g. http://pypi.python.org/pypi/django-celery given the URL. Does one exist ?
[ "I would use a combination of virtualenv and pip to do the job. The snippet would look sth like this:\nvirtualenv <path_to_a_new_env> --no-site-packages\n<using this virtual env> && pip install <url or package name>\n<using this virtual env> && pip freeze\n---\n<using this virtualenv> - source bin/activate on Linux...
[ 2, 0 ]
[]
[]
[ "dependencies", "module", "python" ]
stackoverflow_0006462582_dependencies_module_python.txt
Q: Equivalent of this Python random number generator in C++? Just switch from Python to C++ and I begin to re-write my Python tools in C++ for better understanding, but can't solve this one... This function will generate range of random numbers, for example "randomRange(12)" may return range of 12 numbers like "82354...
Equivalent of this Python random number generator in C++?
Just switch from Python to C++ and I begin to re-write my Python tools in C++ for better understanding, but can't solve this one... This function will generate range of random numbers, for example "randomRange(12)" may return range of 12 numbers like "823547896545" Python: def randomRange(n): range_start = 10...
[ "You'll have trouble getting good randomness with high values of n, but: \n#include <math.h> // for pow()\n#include <stdlib.h> // for drand48()\n\nlong randomRange(int n)\n{\n // our method needs start and size of the range rather \n // than start and end.\n long range_start = pow(10,n-1);\n ...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "c++", "python", "random" ]
stackoverflow_0007324285_c++_python_random.txt
Q: Performing a moving linear fit to 1D data in Python I have a 1D array of data and wish to extract the spatial variation. The standard way to do this which I wish to pythonize is to perform a moving linear regression to the data and save the gradient... def nssl_kdp(phidp, distance, fitlen): kdp=zeros(phidp.sh...
Performing a moving linear fit to 1D data in Python
I have a 1D array of data and wish to extract the spatial variation. The standard way to do this which I wish to pythonize is to perform a moving linear regression to the data and save the gradient... def nssl_kdp(phidp, distance, fitlen): kdp=zeros(phidp.shape, dtype=float) myshape=kdp.shape for swn in ra...
[ "the calculation for linear regression is based on the sum of various values. so you could write a more efficient routine that modifies the sum as the window moves (adding one point and subtracting an earlier one).\nthis will be much more efficient than repeating the process every time the window shifts, but is op...
[ 3, 1, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0007288125_numpy_python_scipy.txt