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: python adding a title row to csv output file I have a python script that gets data from a database and outputs a csv file. Now I'm trying to add a header row containing titles for each of the columns. What do I need to add so that it outputs an initial row ahead of the db output (I'm quite a newbie to python, so I...
python adding a title row to csv output file
I have a python script that gets data from a database and outputs a csv file. Now I'm trying to add a header row containing titles for each of the columns. What do I need to add so that it outputs an initial row ahead of the db output (I'm quite a newbie to python, so I got stuck in this part and couldn't find the info...
[ "If you're using a DictWriter, you can just call writeheader.\n" ]
[ 2 ]
[]
[]
[ "csv", "header", "python" ]
stackoverflow_0006930008_csv_header_python.txt
Q: a slightly different string equivalence function in python I have a number of strings that won't match exactly but should be considered equivalent. For example 'Bob' and 'Robert' or 'WWF' and 'World Wrestling Federation'. To implement the equivalence function, I was going to put all the equivalent strings into tup...
a slightly different string equivalence function in python
I have a number of strings that won't match exactly but should be considered equivalent. For example 'Bob' and 'Robert' or 'WWF' and 'World Wrestling Federation'. To implement the equivalence function, I was going to put all the equivalent strings into tuples and then all the tuples into a list. Then for each input str...
[ "If your list of equivalence tuples is EQUIVALENCES, you can create a dictionary mapping each string to its equivalences:\nword_equivs = {}\n\nfor equiv in EQUIVALENCES:\n for word in equiv:\n word_equivs[word] = equiv\n\nThen you can check if two strings are equivalent by seeing if they map to the same e...
[ 2, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006929919_python_string.txt
Q: list[-1] yields "list index out of range" error in python program I'm trying to build a markov generator that takes an arbitrary length for the chain of words as a programming exercise, but I've found a bug I just can't quite seem to fix. When I run the markov function, I get list index out of range. I get the fe...
list[-1] yields "list index out of range" error in python program
I'm trying to build a markov generator that takes an arbitrary length for the chain of words as a programming exercise, but I've found a bug I just can't quite seem to fix. When I run the markov function, I get list index out of range. I get the feeling I'm overlooking something obvious, but I'm not sure what. The tr...
[ "If words is empty, then yes that will happen. Trying to access words[-1] in an empty array is just as invalid as words[0]. Add a check to see if len(words) == 0. The same logic holds for nextWords which in this code looks like it too could be empty.\n" ]
[ 7 ]
[]
[]
[ "markov", "python", "python_2.x" ]
stackoverflow_0006930146_markov_python_python_2.x.txt
Q: Logging across multiple co-routines / greenlets / microthreads with Gevent? What is the best approach to logging events that span multiple running co-routines / microthreads / Greenlets using Python's gevent? Example events I would like to log could include the creation of new connections or the dropping of conne...
Logging across multiple co-routines / greenlets / microthreads with Gevent?
What is the best approach to logging events that span multiple running co-routines / microthreads / Greenlets using Python's gevent? Example events I would like to log could include the creation of new connections or the dropping of connections to a socket server. Along this line of thought - is it possible for 'spawn...
[ "If this is just single process, then no, they can't possibly write at the same time. Greenlets all run in the same OS thread and are scheduled cooperatively, only one can be running at a time.\nwith open('log', 'w') as log:\n jobs = [gevent.spawn(log.write, 'event %d' % i) for i in range(10)]\n gevent.joinal...
[ 3 ]
[]
[]
[ "concurrency", "coroutine", "gevent", "logging", "python" ]
stackoverflow_0006929902_concurrency_coroutine_gevent_logging_python.txt
Q: Underscore vs Double underscore with variables and methods Somebody was nice enough to explain to me that __method() mangles but instead of bothering him further since there are a lot of other people who need help I was wondering if somebody could elaborate the differences further. For example I don't need manglin...
Underscore vs Double underscore with variables and methods
Somebody was nice enough to explain to me that __method() mangles but instead of bothering him further since there are a lot of other people who need help I was wondering if somebody could elaborate the differences further. For example I don't need mangling but does _ stay private so somebody couldn't do instance._meth...
[ "From PEP 8:\n\n\n_single_leading_underscore: weak \"internal use\" indicator. E.g.\nfrom M import *\ndoes not import objects whose name starts with an underscore.\nsingle_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.\nTkinter.Toplevel(master, class_='ClassName')\n__double_l...
[ 282, 130, 12 ]
[]
[]
[ "python" ]
stackoverflow_0006930144_python.txt
Q: Python % character problem while manipulation (Escape char problem) I try to send a confirmation email in Django but there is a problem with excape characters. I have a helper function for content of mail as def getActivationMailBody(): email_body = "<table width='100%'> email_body = email_body + '<p>' + ...
Python % character problem while manipulation (Escape char problem)
I try to send a confirmation email in Django but there is a problem with excape characters. I have a helper function for content of mail as def getActivationMailBody(): email_body = "<table width='100%'> email_body = email_body + '<p>' + '%(confirmLink)s' + '</p>' return email_body And the confirmation ur...
[ "In a format string, a % can be escaped by doubling: \nemail_body = \"<table width='100%%'>\"\n\nIt's a little odd how you've constructed this, since getActivationEmailBody isn't returning the body of the email, but instead a format string to create the body. You might want to rename the function.\n" ]
[ 3 ]
[]
[]
[ "escaping", "python", "string" ]
stackoverflow_0006930201_escaping_python_string.txt
Q: ImportError: No module named array_import -----scipy I am facing problem with importing io module in scipy and python shell shows an error as following. import scipy.io.array_import ImportError: No module named array_import Please let me know how to solve this. By reading some post on net I also tried using i...
ImportError: No module named array_import -----scipy
I am facing problem with importing io module in scipy and python shell shows an error as following. import scipy.io.array_import ImportError: No module named array_import Please let me know how to solve this. By reading some post on net I also tried using import numpy.loadtxt but that too doesnt work ImportEr...
[ "See this message on the SciPy user mailing list:\n\n\nI am facing problem with importing io module in scipy\n and python shell shows an error as following.\nimport scipy.io.array_import\nImportError: No module named array_import\n\n\narray_import was removed in Scipy 0.8. If you are looking for\n read_array a...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0006930314_numpy_python_scipy.txt
Q: Nested .pth Files or Loading Extra site-dirs from a Network The goal is to have a universal directory where I can add packages on the network that are automatically added to sys.path without needing to run site.addsitedir or sys.path.append each time I import said packages. Is there a way to do this? Background: I...
Nested .pth Files or Loading Extra site-dirs from a Network
The goal is to have a universal directory where I can add packages on the network that are automatically added to sys.path without needing to run site.addsitedir or sys.path.append each time I import said packages. Is there a way to do this? Background: I have a small network of users who all need access to the same sc...
[ "You have a couple options:\n\nmodify your site.py file -- look for the PREFIXES list and add your network path to it:\nHave one custom .pth file in each machine's site-packages folder with the following line:\nimport sys; sys.path.append('/network/path/to/modules_and_packages')\n\n\nThe downside to using site.py i...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006600938_python.txt
Q: Downloading a Torrent with libtorrent-python I have the following python code: import libtorrent as lt import time ses = lt.session() ses.listen_on(6881, 6891) params = { 'save_path': '/home/downloads/', 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is...
Downloading a Torrent with libtorrent-python
I have the following python code: import libtorrent as lt import time ses = lt.session() ses.listen_on(6881, 6891) params = { 'save_path': '/home/downloads/', 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True} link = "magnet:?xt=urn:btih:4MR6HU7...
[ "The problem turned out to be trivial. The save_path did not exist, thus the libtorrent library downloaded as long as it did not have to flush the cache, but once it attempted to write the file, it failed and could not continue downloading, therefore the slowdown and eventual halt. Once an existing path was added i...
[ 14, 3 ]
[]
[]
[ "bittorrent", "libtorrent", "magnet_uri", "python" ]
stackoverflow_0006556657_bittorrent_libtorrent_magnet_uri_python.txt
Q: App engine Channel API returns no messages Problem description: channel messages no returned to ajax script. Initially, messages are delivered to clietn side, but the problem appears when I set larger timeout in js: goog.appengine.Socket.POLLING_TIMEOUT_MS = 5000; //poll every 5 seconds I've added a very basic P...
App engine Channel API returns no messages
Problem description: channel messages no returned to ajax script. Initially, messages are delivered to clietn side, but the problem appears when I set larger timeout in js: goog.appengine.Socket.POLLING_TIMEOUT_MS = 5000; //poll every 5 seconds I've added a very basic Python code to test if Channel API works in my Go...
[ "Stay away from setting the POLLING_TIMEOUT_MS higher than 1.5 sec, the dev_appserver will assume you have disconnected.\nIt does not work via polling in production, so you do not have to worry about the timeout really.\nEdit: just saw Robert's comment; personally I have even had issues if I set the polling to 3sec...
[ 6 ]
[]
[]
[ "channel_api", "google_app_engine", "python" ]
stackoverflow_0006928518_channel_api_google_app_engine_python.txt
Q: Database view in pyqt Is there an easy way to display the contents of a table from sqlite in pyqt? The only examples I can find are either in C++ or have relational tables. A: You can use the QSqlTableModel class and pass it to a QTableView. Assuming you have a QSqlDatabase object named db, model = QtSql.QSqlTa...
Database view in pyqt
Is there an easy way to display the contents of a table from sqlite in pyqt? The only examples I can find are either in C++ or have relational tables.
[ "You can use the QSqlTableModel class and pass it to a QTableView. Assuming you have a QSqlDatabase object named db,\nmodel = QtSql.QSqlTableModel(self, db)\nmodel.setTable(\"YourTable\")\nmodel.select()\n\ntableview = QtGui.QTableView()\ntableview.setModel(model)\ntableview.show()\n\n" ]
[ 5 ]
[]
[]
[ "pyqt", "python", "sqlite" ]
stackoverflow_0006927576_pyqt_python_sqlite.txt
Q: Storing serialized object in database then restoring object state from key Alright, this is pretty fun. Code will illustrate best what I'm thinking about: class Restorable(object): def __init__(self, a=1, b=1): self.a = a self.b = b def restore(self, serialized_object): # I'm aware...
Storing serialized object in database then restoring object state from key
Alright, this is pretty fun. Code will illustrate best what I'm thinking about: class Restorable(object): def __init__(self, a=1, b=1): self.a = a self.b = b def restore(self, serialized_object): # I'm aware this is local, just illustrating self = pickle.loads(serialized_object)...
[ "As you said in your edit, create a new object (don't assign to self, obviously), but instead of copying the attributes one by one you can\ndef restore(self, serialized_object):\n original = pickle.loads(serialized_object)\n self.__dict__.update(original.__dict__)\n\nand update all your attributes at once. H...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006596800_python_python_3.x.txt
Q: Any way to zip to list of lists? Alright, so I have two lists that look like this listx = [2, 4, 5, 9, 11] listy = [3, 5, 9, 12, 14] Right now, when I do zip, I get this listz = zip(listx, listy) listz = [(2,3), (4,5), (5,9), (9, 12), (11,14)] Is there any way to make this a list of lists instead of an array, li...
Any way to zip to list of lists?
Alright, so I have two lists that look like this listx = [2, 4, 5, 9, 11] listy = [3, 5, 9, 12, 14] Right now, when I do zip, I get this listz = zip(listx, listy) listz = [(2,3), (4,5), (5,9), (9, 12), (11,14)] Is there any way to make this a list of lists instead of an array, like so listz = [[2,3], [4,5], [5,9], [9...
[ "You can use a comprehension:\nlistz = [list(i) for i in zip(listx, listy)]\n\nor generator expression:\nlistz = (list(i) for i in zip(listx, listy))\n\n", "Use map to convert the tuples to lists.\nmap(list, zip(listx, listy))\n\n", "Use a list comprehension, and use izip to avoid creating an intermediary list....
[ 10, 8, 2, 0 ]
[]
[]
[ "arrays", "list", "python", "zip" ]
stackoverflow_0006930479_arrays_list_python_zip.txt
Q: is there a Python equivalent to Perl's XML::Simple? You know, something that takes an xml input file and returns a dict, creating keys based on the tag names, and nesting a list of dict's for all the children of each node? If you are familiar with Perl's XML::Simple -- I'm looking for the Python equivalent of that...
is there a Python equivalent to Perl's XML::Simple?
You know, something that takes an xml input file and returns a dict, creating keys based on the tag names, and nesting a list of dict's for all the children of each node? If you are familiar with Perl's XML::Simple -- I'm looking for the Python equivalent of that. I'm tooling around with xml.etree.ElementTree and that ...
[ "Try Beautiful Soup as described in question Editing XML as a dictionary in python?\n", "how about python-simplexml ?\n" ]
[ 2, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0006927749_perl_python.txt
Q: Django - How to display Scientific Notation on Admin Page Field? I have a field in my admin page that I'd like to display in Scientific Notation. Right now it displays something ugly like this. How can I display this as 4.08E+13? Right now I'm using a standard Decimal field in the model. Any advice is greatly ap...
Django - How to display Scientific Notation on Admin Page Field?
I have a field in my admin page that I'd like to display in Scientific Notation. Right now it displays something ugly like this. How can I display this as 4.08E+13? Right now I'm using a standard Decimal field in the model. Any advice is greatly appreciated. I'm on Django 1.2.
[ "You have to use %e to get the scientific notation format:\nBasic Example:\nx = 374.534 \nprint(\"%e\" % x)\n# 3.745340e+02\n\nPrecision of 2\nx = 374.534\nprint(\"{0:.2E}\".format(x))\n# 3.75E+02\n\nx = 12345678901234567890.534\nprint(\"{0:.2E}\".format(x))\n# 1.23E+19\n\nPrecision of 3\nprint(\"{0:.3E}\".format(...
[ 4, 1 ]
[]
[]
[ "django", "django_admin", "django_forms", "django_models", "python" ]
stackoverflow_0006913166_django_django_admin_django_forms_django_models_python.txt
Q: writing values generated from different functions in a single file I have written this code and what I am trying to do here is to write the values generated from this function and another one which are in stored as lists in timeList and parameterList. I am not exactly supposed to write the values of timeList in th...
writing values generated from different functions in a single file
I have written this code and what I am trying to do here is to write the values generated from this function and another one which are in stored as lists in timeList and parameterList. I am not exactly supposed to write the values of timeList in the same function I guess. It should probably be done in a separate functi...
[ "Do not write timeList to the file while inside the for line in tFile loop.\nNotice how many times you are opening and closing the file (very inefficient). Also notice if you open the file in 'w' (write) mode instead of 'a' (append) mode, it overwrites the previous contents...\nInstead, wait (delay gratification!) ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006930710_python.txt
Q: gdbinit, pretty-printers, and relative directories? In my ~/.gdbinit I would like to be able to reference the GDB python pretty-printers installed in my home directory via relative path: python import sys # 1, works sys.path.insert(0, '/home/<username>/.gdb_viz') # 2, doesn't work # sys.path.insert(0, '~/.gdb_viz'...
gdbinit, pretty-printers, and relative directories?
In my ~/.gdbinit I would like to be able to reference the GDB python pretty-printers installed in my home directory via relative path: python import sys # 1, works sys.path.insert(0, '/home/<username>/.gdb_viz') # 2, doesn't work # sys.path.insert(0, '~/.gdb_viz') # 3, doesn't work # sys.path.insert(0, '.gdb_viz') from...
[ "Not tested, but should work:\npython\nimport sys, os\n\nsys.path.insert(0, os.getenv('HOME') + '/.gdb_viz')\n\n", "I stick this in path_setup.py\nand run source ~/.gdb_viz/path_setup.py\nfrom my .gdbinit\nhadn't tested 3).\n# Add the path of this script to pythons search path. \nimport os, sys\n\nsys.path.append...
[ 4, 1 ]
[]
[]
[ "c++", "gdb", "python" ]
stackoverflow_0006922093_c++_gdb_python.txt
Q: Replace "while" with "for" in given python script I have written following script in python which works fine: from sys import argv script, filename = argv def brokerage(cost): vol = 100 tamt = cost*vol br = (((cost*0.1)/100)*vol)*2 rc = (0.0074*tamt)/100 stt = (0.025*tamt)/100 std = (0.00...
Replace "while" with "for" in given python script
I have written following script in python which works fine: from sys import argv script, filename = argv def brokerage(cost): vol = 100 tamt = cost*vol br = (((cost*0.1)/100)*vol)*2 rc = (0.0074*tamt)/100 stt = (0.025*tamt)/100 std = (0.004*tamt)/100 stb = (11*br)/100 tbr = br+rc+stt+s...
[ "for cost1,cost2 in zip(range(10,501,10),range(510,1001,10)):\n # your code\n\nor faster:\nfor cost1 in range(10,501,10):\n cost2 = cost1 + 500\n # Your code\n\n", "for cost1, cost2 in zip(range(10, 501, 10), range(510, 1001, 10))):\n # remove these\n # cost1+=10\n # cost2+=10\n\n", "for cost1...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006931021_python.txt
Q: Parse log file in python I have a log file that has lines that look like this: "1","2546857-23541","f_last","user","4:19 P.M.","11/02/2009","START","27","27","3","c2546857-23541","" Each line in the log as 12 double quote sections and the 7th double quote section in the string comes from where the user typed so...
Parse log file in python
I have a log file that has lines that look like this: "1","2546857-23541","f_last","user","4:19 P.M.","11/02/2009","START","27","27","3","c2546857-23541","" Each line in the log as 12 double quote sections and the 7th double quote section in the string comes from where the user typed something into the chat window: ...
[ "The csv module is smart enough to recognize when a quoted item is not finished (and thus must contain a newline character).\nimport csv\nwith open('data.log',\"r\") as fin:\n with open('data2.log','w') as fout: \n reader=csv.reader(fin,delimiter=',', quotechar='\"', escapechar='^')\n writer...
[ 3, 0, 0 ]
[]
[]
[ "notepad++", "parsing", "python" ]
stackoverflow_0006930874_notepad++_parsing_python.txt
Q: Range in Python I want to list numbers in range and I want to find out the amount of numbers in range. For Example: X = (5,6,5,1,2,3,4,5,6,7) Y = (5, 5, 5,5 5,5 5,5 5) range(X) # Want to know how many numbers in X. If you guys could help it would be great. A: Given the tuple or list X: >>> X = (5,6,5,1,2,3,4,5,...
Range in Python
I want to list numbers in range and I want to find out the amount of numbers in range. For Example: X = (5,6,5,1,2,3,4,5,6,7) Y = (5, 5, 5,5 5,5 5,5 5) range(X) # Want to know how many numbers in X. If you guys could help it would be great.
[ "Given the tuple or list X:\n>>> X = (5,6,5,1,2,3,4,5,6,7)\n>>> X\n(5, 6, 5, 1, 2, 3, 4, 5, 6, 7)\n\nYou find the number of elements with the len function:\n>>> len(X)\n10\n\nIf you want to find the number of unique elements, create a set and look at its length:\n>>> set(X)\nset([1, 2, 3, 4, 5, 6, 7])\n>>> len(set(...
[ 10, 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006931039_python.txt
Q: python encoding error What does one do with this kind of error? You are reading lines from a file. You don't know the encoding. What does "byte 0xed" mean? What does "position 3792" mean? I'll try to answer this myself and repost but I'm slightly annoyed that I'm spending as long as I am figuring this out. Is ther...
python encoding error
What does one do with this kind of error? You are reading lines from a file. You don't know the encoding. What does "byte 0xed" mean? What does "position 3792" mean? I'll try to answer this myself and repost but I'm slightly annoyed that I'm spending as long as I am figuring this out. Is there a clobber/ignore and cont...
[ "0xed is the unicode code for í, which is contained in the input at the position 3792 (that is, if you count starting at the first letter, the 3792nd letter will be í).\nYou are using the ascii codec to decode the file, but the file is not ascii-encoded, try with a unicode aware codec instead (utf_8 maybe?), or, if...
[ 3, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0006931050_encoding_python.txt
Q: Widgets on created window appear on parent window instead I have a button that pops up an options window, when I try to populate the widgets on the new window they only appear on the parent window. here is the related code: from Tkinter import * class MainWindow: def __init__(self, master): """builds m...
Widgets on created window appear on parent window instead
I have a button that pops up an options window, when I try to populate the widgets on the new window they only appear on the parent window. here is the related code: from Tkinter import * class MainWindow: def __init__(self, master): """builds main window.""" windowAttr = {"width":450, "height":150}...
[ "Try making the first line of your original btnOptionsClick() function be ...\nopt = Toplevel()\n\nand then leave the rest as it was.\n" ]
[ 0 ]
[]
[]
[ "python", "python_2.5", "tkinter" ]
stackoverflow_0006920129_python_python_2.5_tkinter.txt
Q: lxml pretty_print python memory overload I have a poorly formatted xml file with over 350 MB of data. Basically, all the data was consolidated into one line. I am trying to pretty_print this into a new file to make life easier, but am running into memory issues. Am I doing anything wrong here and is there a way ar...
lxml pretty_print python memory overload
I have a poorly formatted xml file with over 350 MB of data. Basically, all the data was consolidated into one line. I am trying to pretty_print this into a new file to make life easier, but am running into memory issues. Am I doing anything wrong here and is there a way around this? My computer has 4GB of RAM and is a...
[ "You might want to try using the write method directly with the file handle rather than calling tostring. Change this line:\nf.write(etree.tostring(tree,pretty_print=True))\n\nto this:\ntree.write(f, pretty_print=True)\n\nThis should hopefully reduce the memory usage by half.\n" ]
[ 4 ]
[]
[]
[ "lxml", "parsing", "pretty_print", "python" ]
stackoverflow_0006931408_lxml_parsing_pretty_print_python.txt
Q: Downloading pdf files using mechanize and urllib I am new to Python, and my current task is to write a web crawler that looks for PDF files in certain webpages and downloads them. Here's my current approach (just for 1 sample url): import mechanize import urllib import sys mech = mechanize.Browser() mech.set_hand...
Downloading pdf files using mechanize and urllib
I am new to Python, and my current task is to write a web crawler that looks for PDF files in certain webpages and downloads them. Here's my current approach (just for 1 sample url): import mechanize import urllib import sys mech = mechanize.Browser() mech.set_handle_robots(False) url = "http://www.xyz.com" try: ...
[ "The documentation for urllib says this about the urlretrieve function:\n\nThe second argument, if present, specifies the file location to copy\n to (if absent, the location will be a tempfile with a generated name).\n\nThe function's return value has the location of the file:\n\nReturn a tuple (filename, headers)...
[ 3, 1 ]
[]
[]
[ "eclipse", "mechanize", "python", "urllib", "web_crawler" ]
stackoverflow_0006931364_eclipse_mechanize_python_urllib_web_crawler.txt
Q: Loop detection in django models I have an model which has a many to many relationship with itself. I want to create a validation on the model(s) which would prevent a group from being it's own subgroup, or a subgroup of it's subgroups, etc. The objective is to prevent a situation which can result in a loop / infin...
Loop detection in django models
I have an model which has a many to many relationship with itself. I want to create a validation on the model(s) which would prevent a group from being it's own subgroup, or a subgroup of it's subgroups, etc. The objective is to prevent a situation which can result in a loop / infinite recursion. I've tried implementi...
[ "Should \"target.\" really be inside this loop in your code? It seems like that would make it skip a level.\n for sub_group in self.target.all():\n sub_group.target.validate_no_group_loops(seen)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_validation", "python" ]
stackoverflow_0006920348_django_django_models_django_validation_python.txt
Q: Namespaces issue in settings.py I'm trying to customize how applications gets integrated in a generic Django project. The question is about how applications setting files can be imported into the project settings.py, so to keep app specific settings well separated from Django's. For example: settings.py # Django c...
Namespaces issue in settings.py
I'm trying to customize how applications gets integrated in a generic Django project. The question is about how applications setting files can be imported into the project settings.py, so to keep app specific settings well separated from Django's. For example: settings.py # Django configuration settings... DATABASES = ...
[ "This is one of those cases where execfile('settings_myapp.py') in the main settings file might actually be a good idea, since what you actually want to do is run some code in the current context.\nJust take out the import from settings_myapp.py and it should work fine.\nEdit: wanted to add that execfile() has been...
[ 1 ]
[]
[]
[ "django", "module", "namespaces", "python", "settings" ]
stackoverflow_0006931642_django_module_namespaces_python_settings.txt
Q: Equivalent of this two line Perl in Python? I need to find exact equivalent of this two line Perl in Python 2.x PERL: foreach my $edge (@edges){ $edge =~ s/[\(\)]//g; my @verts = split(/,/, $edge); PYTHON: for edge in edges: edge = ??? verts = ??? Thank you very much. A: edge = edge.translate(N...
Equivalent of this two line Perl in Python?
I need to find exact equivalent of this two line Perl in Python 2.x PERL: foreach my $edge (@edges){ $edge =~ s/[\(\)]//g; my @verts = split(/,/, $edge); PYTHON: for edge in edges: edge = ??? verts = ??? Thank you very much.
[ "edge = edge.translate(None, '()')\nverts = edge.split(',')\n\nYou might also want to convert strings to ints in creating verts, using:\nverts = map(int, edge.split(','))\n\n", "Using the regex module to stick closely to the Perl version:\nfor edge in edges:\n edge = re.sub( '[()]', '', edge )\n verts = fil...
[ 4, 4, 0 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0006931849_perl_python.txt
Q: Doing a file upload with python-oauth2 A Get request is pretty easy: def build_request(url, method='GET'): params = { 'oauth_version': "1.0", 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': int(time.time()) } consumer = oaut...
Doing a file upload with python-oauth2
A Get request is pretty easy: def build_request(url, method='GET'): params = { 'oauth_version': "1.0", 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': int(time.time()) } consumer = oauth2.Consumer(key='****',secret='******') ...
[ "The problem is that oauth is not supposed to sign multipart/post data, but it still needs to sign the other parameters. The way I got around it was to use python-oauth2 to sign the non-file parameters and then send the request manually with urllib2.\nHere's an example script. See lines 126 - 173.\n", "From readi...
[ 4, 1 ]
[]
[]
[ "file_upload", "oauth", "python" ]
stackoverflow_0006924569_file_upload_oauth_python.txt
Q: How to write multiple values into one line in a text file I have a number and strings, a, x, y, and z. I want to write a them to a text file with all of those values in one line. For example, I want the text file to say: a1 x1 y1 z1 a2 x2 y2 z2 a3 x3 y3 z3 a4 x4 y4 z4 There's a loop and each time the loop comple...
How to write multiple values into one line in a text file
I have a number and strings, a, x, y, and z. I want to write a them to a text file with all of those values in one line. For example, I want the text file to say: a1 x1 y1 z1 a2 x2 y2 z2 a3 x3 y3 z3 a4 x4 y4 z4 There's a loop and each time the loop completes a cycle, I want to write all of the variables at the given ...
[ "with open('output', 'w') as fout:\n while True:\n a, x, y, z = calculate_a(), calculate_x(), calculate_y(), calculate_z()\n fout.write('{} {} {} {}\\n'.format(a, x, y, z)) \n\nor, if you want to collect all the values and then write them all at once\nwith open('output', 'w') as fp:\n lines = []...
[ 9, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006931183_python.txt
Q: Declaring an empty list I just noticed that declaring two empty lists as: list1 = list2 = [] produced an entirely different result as compared to: list1 = [] list2 = [] I don't this problem is related to the whole program as such, or that the result is important. Nevertheless here is the whole program. So is the...
Declaring an empty list
I just noticed that declaring two empty lists as: list1 = list2 = [] produced an entirely different result as compared to: list1 = [] list2 = [] I don't this problem is related to the whole program as such, or that the result is important. Nevertheless here is the whole program. So is there any difference between the...
[ "list1 = list2 = []\n\nAssignes the same empty list instance ([]) to both list1 and list2. This is because object instances are assigned by reference.\nYou can do this instead:\nlist1, list2 = [], []\n\nto assign two different lists two the two variables.\nYou can check it as follows:\nlist1 = list2 = []\nprint id(...
[ 10, 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006932520_python.txt
Q: Split "dict" definition up between files I'd like to define the contents of a large dictionary object up between files. I'm wondering if this is possible in python. Ideally, this is what I'd like to do: Main File: (dict_object_main.py) # File name: dict_object_main.py import dict_object_sub1 import dict_object_s...
Split "dict" definition up between files
I'd like to define the contents of a large dictionary object up between files. I'm wondering if this is possible in python. Ideally, this is what I'd like to do: Main File: (dict_object_main.py) # File name: dict_object_main.py import dict_object_sub1 import dict_object_sub2 dict_object = {} def doSomeStuffWithTheD...
[ "Edit: The first part to my previous answer was wrong. The lesson I learned is don't have circular dependencies. The following is correct:\nAnother option is to try this in the main file:\nfrom dict_object_sub1 import dict_object_sub1\nfrom dict_object_sub2 import dict_object_sub2\ndict_object = {}\ndict_object.up...
[ 2, 1 ]
[]
[]
[ "python", "setup_project" ]
stackoverflow_0006932596_python_setup_project.txt
Q: Translation from Perl to Python, brief I really need help on this. I tried translating this Perl into Python, but it doesn't seem to do what I want. Thanks! Perl: @X_max = &MaxValue(@xCoords); $maxX = int(10 * $X_max[0]/5); @X_min = &MinValue(@xCoords); $minX = int(10 * $X_min[0]/5); $rangeX = &R...
Translation from Perl to Python, brief
I really need help on this. I tried translating this Perl into Python, but it doesn't seem to do what I want. Thanks! Perl: @X_max = &MaxValue(@xCoords); $maxX = int(10 * $X_max[0]/5); @X_min = &MinValue(@xCoords); $minX = int(10 * $X_min[0]/5); $rangeX = &Range($minX, $maxX); print GRID "X:\t $ma...
[ "The Perl does not look like it's simply the Python min, max, and range functions. Because MaxValue returns a list of values, which is disregarded in the next step as the code simply takes the first item in the list. So it might be something like this: \nx_max = max( xcoords );\nmaxx = int( 10 * x_max / 5 );\nx_...
[ 6, 1 ]
[]
[]
[ "min", "perl", "python", "range", "translation" ]
stackoverflow_0006931326_min_perl_python_range_translation.txt
Q: str object is not callable for unittest I have written a test case which shows the error from unittest import * class MyTest(unittest.TestCase): def test_add(self): self.assertEquals(1,(2-1),"Sample Subraction Test") if __name__ == '__main__': unittest.main() Output: Str object is not callable In...
str object is not callable for unittest
I have written a test case which shows the error from unittest import * class MyTest(unittest.TestCase): def test_add(self): self.assertEquals(1,(2-1),"Sample Subraction Test") if __name__ == '__main__': unittest.main() Output: Str object is not callable Instead of "from unittest import *" I have gi...
[ "from ... import * is dangerous practice, and should only be used when the module/package has been designed and advertised that way, and you have a good reason to do so. \nIt turns out that unittest has not been designed that way, and when that method is used two other 'test cases' are found, but since they aren't...
[ 4 ]
[ "I got it working like this. \nOverride runTest() method, create instance, run your test_add()\nfrom unittest import TestCase\n\nclass MyTest(TestCase):\n def runTest(self):\n pass\n\n def test_add(self):\n self.assertEquals(1,(2-2),\"Sample Subraction Test\")\n\n\nif __name__ == '__main__':\n ...
[ -1 ]
[ "python", "python_3.x", "testing" ]
stackoverflow_0006439962_python_python_3.x_testing.txt
Q: Getting started with Twitter\OAuth2\Python I'm attempting to connect to twitter using python, and I'm finding it really frustrating. Everything I read suggests that I need a consumer key, a consumer secret, an access key and an access secret - for example: Using python OAUTH2 to access OAUTH protected resources I...
Getting started with Twitter\OAuth2\Python
I'm attempting to connect to twitter using python, and I'm finding it really frustrating. Everything I read suggests that I need a consumer key, a consumer secret, an access key and an access secret - for example: Using python OAUTH2 to access OAUTH protected resources I can get the consumer key and the consumer secre...
[ "Almost all oauth examples on blogs seem to be examples of the authorisation phase of oauth and none focus on how to actually make requests once you have these, as once you understand how it works this part is quite obvious. Getting that initial understanding is quite difficult unfortunately.\nIf you're just trying...
[ 108 ]
[ "Personally I use tweepy, it provides a nice python wrapper to Twitter's API\n" ]
[ -4 ]
[ "oauth", "python", "twitter" ]
stackoverflow_0006399978_oauth_python_twitter.txt
Q: How to Identify the Python version in #! using environment variables I have a problem which is caused by our encapsulated design. Up till now lots of our scripts were written in bash and as a result the #!/bin/bash was always simple. However now that we are rewriting our scripts in python that is a bit more diffi...
How to Identify the Python version in #! using environment variables
I have a problem which is caused by our encapsulated design. Up till now lots of our scripts were written in bash and as a result the #!/bin/bash was always simple. However now that we are rewriting our scripts in python that is a bit more difficult. We deliver a specific version of python (to avoid version differenc...
[ "A common way to do this is to use the env program:\n#!/usr/bin/env python\n\nThis will cause env to look along the PATH environment for a binary called python.\n", "I'm not aware of being able to use environment variable in the shebang. You can use relative paths though\n#! ../../usr/bin/python\n\nedit:\nYou cou...
[ 6, 1, 0, 0 ]
[]
[]
[ "interpreter", "linux", "python" ]
stackoverflow_0006932925_interpreter_linux_python.txt
Q: Python: How to check that...? I'd like some advice on how to check for the correctness of the parameters I receive. The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should ha...
Python: How to check that...?
I'd like some advice on how to check for the correctness of the parameters I receive. The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should have to ensure that it meets the crit...
[ "When in doubt just work out how you would get the required effect by calling the usual Python builtins and translate it to C/C++. I'll just answer for Python, for C you would look up the global such as 'callable' and then call it like any other Python function.\n\nWhy would you care about it being a function rathe...
[ 3, 0 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0006933058_boost_boost_python_c++_python.txt
Q: working with a big list I have written this code which is, param_values = { 'aa' : [[-1,-1], [-1,-1], [-1,-1], [-1,-1], [0.15,1.0], [-1,-1]], 'ae' : [[-1,-1], [-1,-1], [0.3,0.4], [-1,-1], [0.15,1.0], [-1,-1]], 'ah' : [[-1,-1], [-1,-1], [-1,-1], [-1,-1], [0.15,1.0], [-1,-1]], 'ao' : ...
working with a big list
I have written this code which is, param_values = { 'aa' : [[-1,-1], [-1,-1], [-1,-1], [-1,-1], [0.15,1.0], [-1,-1]], 'ae' : [[-1,-1], [-1,-1], [0.3,0.4], [-1,-1], [0.15,1.0], [-1,-1]], 'ah' : [[-1,-1], [-1,-1], [-1,-1], [-1,-1], [0.15,1.0], [-1,-1]], 'ao' : [[-1,-1], [-1,-1], [-1,-1], [...
[ "First, some notes ...\n\nYou missed a comma at the end of the 'zh' line in the dictionary.\n\"tFile\" should be \"pFile\", right?\nShouldn't \nif line == \" ' \": \nbe \nif line ==\"'\":\n\nHow about this? ...\ndef coart(phonemeFile) :\n \"\"\" Coarticulation function where forward and backward coarticulation t...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006932507_python.txt
Q: How to round up (always) time to nearest ten? I did not want to take a risk of coming up with a hack for this because it involves datetime objects. Basically, I want to do the conversion as follows: 2010-04-21 06:37:53 -> 2010-04-21 06:40:00 2010-08-26 02:54:00 -> 2010-08-26 03:00:00 2010-04-21 06:37:12 -> 2010-04...
How to round up (always) time to nearest ten?
I did not want to take a risk of coming up with a hack for this because it involves datetime objects. Basically, I want to do the conversion as follows: 2010-04-21 06:37:53 -> 2010-04-21 06:40:00 2010-08-26 02:54:00 -> 2010-08-26 03:00:00 2010-04-21 06:37:12 -> 2010-04-21 06:40:00 2010-08-26 11:54:19 -> 2010-08-27 00:0...
[ "You would need to convert your time into a unix timestamp and round the timestamp as wished.\nround(Timestamp / 60 seconds [minutes conversion] / 10 [round precision]) * 60 * 10 [to get the timestamp back]\n", "You want to round-off only minutes. You'll get the correct answer even if you ignore the seconds and m...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "date", "datetime", "python" ]
stackoverflow_0006933023_date_datetime_python.txt
Q: What is the correct way to identify an Exception? If exceptions are always fatal, making use of them in Python is easy # moduleB.py import moduleC But evaluating an exception requires more than just it's type, we often need to determine where an exception came from # moduleA.py try: import moduleB except Impor...
What is the correct way to identify an Exception?
If exceptions are always fatal, making use of them in Python is easy # moduleB.py import moduleC But evaluating an exception requires more than just it's type, we often need to determine where an exception came from # moduleA.py try: import moduleB except ImportError as e: print e if str(e) == "No module na...
[ "Sorry, but the example you posted is the canonical Way Of Doing It. Python doesn't have any syntax for catching the exception raised by the import statement but not by something below it.\nJust a small warning, though: str(e) can cause unicode errors if e's message is unicode. You can fix that by using repr(e).\n"...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006933228_python.txt
Q: Python - classmethod in base class accessible via child class, without passing in class I'm trying to define some methods in a base class that can then be used as class/static methods on a child class, like so: class Common(): @classmethod def find(cls, id): # When Foo.find is called, cls needs to be Foo ...
Python - classmethod in base class accessible via child class, without passing in class
I'm trying to define some methods in a base class that can then be used as class/static methods on a child class, like so: class Common(): @classmethod def find(cls, id): # When Foo.find is called, cls needs to be Foo rows = Session.query(cls) rows = rows.filter(cls.id == id) return rows...
[ "This doesn't quite answer your question but it might be of use to you.\nAn SQLAlchemy session instance has query_property() which returns a class property that produces a query against the class. So you could implement something similar to your find() method thus:\nBase = declarative_base()\nBase.query = db_sessio...
[ 0, 0 ]
[]
[]
[ "class_method", "first_class", "python", "static_methods" ]
stackoverflow_0006628043_class_method_first_class_python_static_methods.txt
Q: Open Matlab file .mat with module PICKLE in Python I want open a Matlab project with the module Pickle or cPickle in Python language. NOT with: from scipy.io import matlab mat=matlab.loadmat('file.mat') Can I use pickle.load with a .mat file? A: For some years now, Matlab has used HDF5 to store data. Python h...
Open Matlab file .mat with module PICKLE in Python
I want open a Matlab project with the module Pickle or cPickle in Python language. NOT with: from scipy.io import matlab mat=matlab.loadmat('file.mat') Can I use pickle.load with a .mat file?
[ "For some years now, Matlab has used HDF5 to store data. Python has support for HDF5, via PyTables. No need to use Pickle. In fact, HDF5 may surprise you for its speed relative to Pickle. A friend reported 2-10X speedups in read/write for some very large datasets.\n\nUpdate 1: A concise guide to loading the fil...
[ 4, 2, 2 ]
[]
[]
[ "matlab", "pickle", "python" ]
stackoverflow_0006780080_matlab_pickle_python.txt
Q: How can I build a file-upload POST HTTP request with WebOb? I am using Ian Bicking's WebOb to very great effect in writing Python web application tests. I call webob.Request.blank('/path...'), and then use the resulting request object's get_response(app) method to invoke my web application. The response object tha...
How can I build a file-upload POST HTTP request with WebOb?
I am using Ian Bicking's WebOb to very great effect in writing Python web application tests. I call webob.Request.blank('/path...'), and then use the resulting request object's get_response(app) method to invoke my web application. The response object that is returned lets me check the HTTP response's status code, cont...
[ "As of a couple days ago you can do:\nreq = Request.blank('/path/under/test', \n POST={'query': 'some text', 'upload': ('filename', 'content')})\n\nThis was brought in in this commit, and has not yet been released.\n", "You can use WebTest for that, see this TestApp.post arguments here.\n" ]
[ 5, 1 ]
[]
[]
[ "http", "python", "testing", "webob", "wsgi" ]
stackoverflow_0006853432_http_python_testing_webob_wsgi.txt
Q: difficulties with basic file i/o in python script called from php Like the file says I am executing a python script from a PHP file sitting on my apache webserver. The example I have is extremely basic. PHP file -- test.php <?php echo "hello"; echo exec("/usr/local/bin/python2.7 test1.py"); ?> python script -- t...
difficulties with basic file i/o in python script called from php
Like the file says I am executing a python script from a PHP file sitting on my apache webserver. The example I have is extremely basic. PHP file -- test.php <?php echo "hello"; echo exec("/usr/local/bin/python2.7 test1.py"); ?> python script -- test1.py print "world" fh = open ('testtest' ,'r') for line in fh: p...
[ "exec does not do what you expect it to do. The documentation states that it only returns the last line of output. It recommends use of passthru instead.\n", "You don't want to assign to the variable file. That's a built-in in Python. You should use something like fh for file handle, or inFile, or the like. Th...
[ 3, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0006933239_php_python.txt
Q: (Python) Send structured packet over network i want to build a chat application which supports text messaging, group messaging, file transfer(like netmeeting). when i send it over TCP socket i saw that data is not structured all the data send as string over TCP. I want to send it in a structured way with few heade...
(Python) Send structured packet over network
i want to build a chat application which supports text messaging, group messaging, file transfer(like netmeeting). when i send it over TCP socket i saw that data is not structured all the data send as string over TCP. I want to send it in a structured way with few headers like name:,ip:,data:,data_type_flag:(file or te...
[ "Try google protcol buffers or apache thrift. There are many examples for how to use them.\nAs for your comment about \"peer to peer\", please realize that even in peer-to-peer one of the peers is always acting as a server (sometimes both are).\n", "TCP is a transport layer protocol, as opposed to application lay...
[ 2, 1, 0 ]
[]
[]
[ "python", "sockets", "telepathy_python" ]
stackoverflow_0006933207_python_sockets_telepathy_python.txt
Q: Why is `None` returned instead of tkinter.Entry object? I'm new to python, poking around and I noticed this: from tkinter import * def test1(): root = Tk() txtTest1 = Entry(root).place(x=10, y=10) print(locals()) def test2(): root = Tk() txtTest2 = Entry(root) txtTest2.place(x=10, y=10)#dif...
Why is `None` returned instead of tkinter.Entry object?
I'm new to python, poking around and I noticed this: from tkinter import * def test1(): root = Tk() txtTest1 = Entry(root).place(x=10, y=10) print(locals()) def test2(): root = Tk() txtTest2 = Entry(root) txtTest2.place(x=10, y=10)#difference is this line print(locals()) test1() test2() out...
[ "The place method of Entry doesn't return a value. It acts in-place on an existing Entry variable.\n", "because Entry.place() returns None\nin a more C-like language you could do:\n(txtTest1 = Entry(root)).place(x=10, y=10)\n\nand txtText1 would be the Entry object, but that syntax is illegal in Python.\n", "Yo...
[ 4, 3, 2 ]
[]
[]
[ "python", "python_3.2", "tkinter" ]
stackoverflow_0006933572_python_python_3.2_tkinter.txt
Q: System requirement for an embedded Python web server I'm working on an embedded device that runs Linux on ARM7 with 64MB RAM and 64MB storage (12MB free). The device should be configured via web therefore it needs to run an embedded web server. Currently it's using Lighttpd and LUA, but I'm thinking about replacin...
System requirement for an embedded Python web server
I'm working on an embedded device that runs Linux on ARM7 with 64MB RAM and 64MB storage (12MB free). The device should be configured via web therefore it needs to run an embedded web server. Currently it's using Lighttpd and LUA, but I'm thinking about replacing LUA (or maybe even Lighttpd) with Python. The server wil...
[ "I'm working on this device using OpenWRT + Python:\nhttp://wiki.openwrt.org/oldwiki/OpenWrtDocs/Hardware/Meraki/Mini\nThe first python run is veeeeeery slow but it are metacompiling all .pyc files, next it work well.\n" ]
[ 2 ]
[]
[]
[ "embeddedwebserver", "mod_python", "python" ]
stackoverflow_0006929451_embeddedwebserver_mod_python_python.txt
Q: After referencing an element in a WebOb.params (UnicodeMultiDict) an element gets popped off the end When I reference the params parameter of the WebOb Request an element is suddenly popped off the end. That or it's being reduced to a single element. The referenced element isn't the one getting knocked off. if req...
After referencing an element in a WebOb.params (UnicodeMultiDict) an element gets popped off the end
When I reference the params parameter of the WebOb Request an element is suddenly popped off the end. That or it's being reduced to a single element. The referenced element isn't the one getting knocked off. if req.str_params.has_key('method'): req.method = req.str_params.getone('method') Before this line logging t...
[ "This is because you are setting req.method. Probably name=some_name is in the body of the request, and so long as req.method == 'POST' you'll get that parameter back. The moment you change the method to PUT you're keeping WebOb from parsing the request body (request bodies are expected to be entities, not HTML f...
[ 2 ]
[]
[]
[ "python", "webob", "wsgi" ]
stackoverflow_0006104126_python_webob_wsgi.txt
Q: Django Celery tutorial not returning results UDATE3: found the issue. See the answer below. UPDATE2: It seems I might have been dealing with an automatic naming and relative imports problem by running the djcelery tutorial through the manage.py shell, see below. It is still not working for me, but now I get new lo...
Django Celery tutorial not returning results
UDATE3: found the issue. See the answer below. UPDATE2: It seems I might have been dealing with an automatic naming and relative imports problem by running the djcelery tutorial through the manage.py shell, see below. It is still not working for me, but now I get new log error messages. See below. UPDATE: I added the l...
[ "I found the solution to my problem from another stackoverflow post: Why does Celery work in Python shell, but not in my Django views? (import problem)\nI had to add these lines to my settings file:\nCELERY_RESULT_BACKEND = \"amqp\"\nCELERY_IMPORTS = (\"app.module.tasks\", )\n\nthen in the task.py file I named the ...
[ 15, 4 ]
[]
[]
[ "celery", "django", "python", "rabbitmq" ]
stackoverflow_0006854133_celery_django_python_rabbitmq.txt
Q: Tool to convert regex between different language syntaxes? Is there a tool to convert a regex from one popular language's syntax to another? For example a Python-style regex to a Java-style regex?. Or at least, has someone put together a set of rules to do these conversions? And obviously some constructs won't be ...
Tool to convert regex between different language syntaxes?
Is there a tool to convert a regex from one popular language's syntax to another? For example a Python-style regex to a Java-style regex?. Or at least, has someone put together a set of rules to do these conversions? And obviously some constructs won't be able to convert.
[ "Go to this article, and follow the link to \"Regex info's comparison of Regex flavors\", that got me to a tool called RegexBuddy, which sounds like it might do what you want.\n", "Yes there is a Windows tool that will do this: RegexBuddy\n" ]
[ 7, 6 ]
[]
[]
[ "java", "perl", "python", "regex" ]
stackoverflow_0006933891_java_perl_python_regex.txt
Q: Which library for video and audio recording? I am looking for a library to record images from a webcam and sound from the microphone and generate a video file (avi, mpeg or any other format). I would prefer a cross-paltform solution (Windows, MAC and Linux) and something in C/C++ or Python. Any recommendation and/...
Which library for video and audio recording?
I am looking for a library to record images from a webcam and sound from the microphone and generate a video file (avi, mpeg or any other format). I would prefer a cross-paltform solution (Windows, MAC and Linux) and something in C/C++ or Python. Any recommendation and/or sample code? Update: Folowing @Rory reccommendt...
[ "gstreamer is an open source multimedia framework with C & Python bindings.\n" ]
[ 2 ]
[]
[]
[ "audio", "c++", "cross_platform", "python", "video" ]
stackoverflow_0006933989_audio_c++_cross_platform_python_video.txt
Q: Python web framework php alike Yes, I'm in doubt if that's a duplicate, I've searched a while but nothing exactly like this one. I'm a hobbyist programmer, I know C++ and python well, but I'm a completely noob when it comes to web-development, it sounds more natural to me to learn PHP without frameworks, but then ...
Python web framework php alike
Yes, I'm in doubt if that's a duplicate, I've searched a while but nothing exactly like this one. I'm a hobbyist programmer, I know C++ and python well, but I'm a completely noob when it comes to web-development, it sounds more natural to me to learn PHP without frameworks, but then comes the question, is there any pyt...
[ "The python cgi module might be what you want, though it is hard to tell exactly what you want. You could also try using WSGI, which is low-level, similar in some ways to cgi. Anyway, these interfaces leave you at a pretty low level, so if you're doing this just to learn \"the hard way\", this is an educational w...
[ 3 ]
[]
[]
[ "php", "python" ]
stackoverflow_0006933949_php_python.txt
Q: how to integrate pystache with web.py Now, I use pystache in web.py in this way: render = render_pystache('templates_dir') class index: def GET(self): render.var('name', 'jim') return render.simple() simple.mustache hello, {{name}}! I wrote a render for web.py render_pystache.py class ren...
how to integrate pystache with web.py
Now, I use pystache in web.py in this way: render = render_pystache('templates_dir') class index: def GET(self): render.var('name', 'jim') return render.simple() simple.mustache hello, {{name}}! I wrote a render for web.py render_pystache.py class render_pystache: context = {} def __i...
[ "I built an example of integrating pystache with web.py. Have a look here: https://github.com/mattupstate/mustache-with-webpy\n" ]
[ 2 ]
[]
[]
[ "mustache", "python", "web.py" ]
stackoverflow_0006677855_mustache_python_web.py.txt
Q: easy_install broken on Mac I have copied my home folder from a Mac OSX 10.5 to a new Mac OSX 10.6. This broke east_intall for binary packages. For example if I use Python 2.5: > easy_install celery Searching for celery Reading http://pypi.python.org/simple/celery/ Reading http://github.com/ask/celery/ Reading http...
easy_install broken on Mac
I have copied my home folder from a Mac OSX 10.5 to a new Mac OSX 10.6. This broke east_intall for binary packages. For example if I use Python 2.5: > easy_install celery Searching for celery Reading http://pypi.python.org/simple/celery/ Reading http://github.com/ask/celery/ Reading http://celeryproject.org Best match:...
[ "It is difficult to tell for sure with the abbreviated tracebacks you included. One possibility is that the separate Python 2.5 you had installed on Mac OS X 10.5, most likely using a python.org installer, did not get copied over. If so, you either need to install a similar Python 2.5 there or move /Library/Frame...
[ 2, 1 ]
[]
[]
[ "easy_install", "osx_snow_leopard", "python" ]
stackoverflow_0006934137_easy_install_osx_snow_leopard_python.txt
Q: Python, Scipy: Building triplets using large adjacency matrix I am using an adjacency matrix to represent a network of friends which can be visually interpreted as Mary 0 1 1 1 Joe 1 0 1 1 Bob 1 1 0 1 Susan 1 1 1 0 ...
Python, Scipy: Building triplets using large adjacency matrix
I am using an adjacency matrix to represent a network of friends which can be visually interpreted as Mary 0 1 1 1 Joe 1 0 1 1 Bob 1 1 0 1 Susan 1 1 1 0 Mary Joe Bob Susan Using this matrix, I want to compile ...
[ "I think you can find triangles only in rows or columns. for example:\nSusan 1 1 1 0 \n Mary Joe Bob Susan\n\nthis means Mary, Joe, Bob are all friends of Susan, so, use combinations to choose two person from [Mary, Joe, Bob], and combine it with Susan will get one triangle. ite...
[ 6, 4 ]
[]
[]
[ "adjacency_matrix", "data_mining", "numpy", "python", "scipy" ]
stackoverflow_0006931985_adjacency_matrix_data_mining_numpy_python_scipy.txt
Q: Does anybody have gdb pretty-printer code for an fd_set on linux? Modern versions of gdb allow integration of python code to "pretty print" complex data structures. There are some great pretty printer implementations for C++'s STL classes as well as some of the more common boost.org types. In network programming,...
Does anybody have gdb pretty-printer code for an fd_set on linux?
Modern versions of gdb allow integration of python code to "pretty print" complex data structures. There are some great pretty printer implementations for C++'s STL classes as well as some of the more common boost.org types. In network programming, one commonly encounters select/poll calls. While poll() uses an array...
[ "Alrighty, here's something I wrote which seems to work for me under Linux. Let me know if it works for you:\nanonprint.py\nimport gdb\n\nclass fd_set_printer:\n \"\"\"\n Prints an fd_set, which is normally an opaque\n array of ints, each bit representing one file descriptor\n \"\"\"\n\n def __init__(self, va...
[ 4 ]
[]
[]
[ "c", "gdb", "linux", "network_programming", "python" ]
stackoverflow_0006832213_c_gdb_linux_network_programming_python.txt
Q: Assigning attributes values from a dictionary I have a large dictionary. I'd like to assign each key value pair to an attribute of a class. Currently I have something along the lines of the snippet below. It works, however it's not pretty. Is there a better way to do this? Pseudo-python snippet : config = A larg...
Assigning attributes values from a dictionary
I have a large dictionary. I'd like to assign each key value pair to an attribute of a class. Currently I have something along the lines of the snippet below. It works, however it's not pretty. Is there a better way to do this? Pseudo-python snippet : config = A large dictionary self.Width = config['width'] self.He...
[ "Pretty simple:\nfor key, value in config.iteritems():\n # Customize key here, for example transform 'text_height' to 'TextHeight' or \n # use 'key.title()' to obtain titlecased keys...\n setattr(self, key, value)\n\nYou may want to do key.title(), but instance attributes are suggested to be all lowercase ...
[ 5, 2 ]
[]
[]
[ "attributes", "dictionary", "python" ]
stackoverflow_0006934524_attributes_dictionary_python.txt
Q: Python subprocess.call and subprocess.Popen giving me different outputs When using subprocess.call, the output is what is expected. result = subprocess.call([securefx, '/NoPrompt', '/Q', '/RetryCount', retries, '/RetryDelay', '1', '/Log', sfxLogFile, '/List', '/S', session]) Printing the result wil...
Python subprocess.call and subprocess.Popen giving me different outputs
When using subprocess.call, the output is what is expected. result = subprocess.call([securefx, '/NoPrompt', '/Q', '/RetryCount', retries, '/RetryDelay', '1', '/Log', sfxLogFile, '/List', '/S', session]) Printing the result will output something like -533428 or 0 But when I run args = [securefx, '/No...
[ "subprocess.Popen returns a Popen object, which you can use to communicate with the process and get output, however subprocess.call will only return the return code of the process:\n\nsubprocess.call(*popenargs, **kwargs)\n Run command with arguments. Wait for command to complete, then return the returncode attrib...
[ 11 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006934696_python_subprocess.txt
Q: Web interface to a system of stochastic differential equations I have a system of stochastic differential equations implemented in MATLAB. Just 4 variables integrated with Euler-Maruyama, so nothing too fancy... the technical details aren't important for this question though. How would you recommend I go about bu...
Web interface to a system of stochastic differential equations
I have a system of stochastic differential equations implemented in MATLAB. Just 4 variables integrated with Euler-Maruyama, so nothing too fancy... the technical details aren't important for this question though. How would you recommend I go about building a web interface (i.e., let people change the parameters and i...
[ "If there are no constraints on the target language, I'd simply translate to R and use RApache. There are plenty of libraries to support this. In fact, you may not need to reimplement much code, given what's available in R libraries.\nThe reason I suggest R is that I've ported a lot of Matlab code to make it reus...
[ 1, 1 ]
[]
[]
[ "matlab", "matplotlib", "numpy", "python", "web_applications" ]
stackoverflow_0006933222_matlab_matplotlib_numpy_python_web_applications.txt
Q: SQLAlchemy - only one result being returned when count() says there are more I'm having trouble with a really large result set only returning one row. Session.query(TestSet).join(Instance).count() >> 4283878 Session.query(TestSet).join(Instance).offset(0).limit(100).count() >> 100 Session.query(TestSet).join(Insta...
SQLAlchemy - only one result being returned when count() says there are more
I'm having trouble with a really large result set only returning one row. Session.query(TestSet).join(Instance).count() >> 4283878 Session.query(TestSet).join(Instance).offset(0).limit(100).count() >> 100 Session.query(TestSet).join(Instance).offset(0).limit(100).all() >> [<model.testset.TestSet object at 0x043EC2F0>] ...
[ "The Query object, when asked to iterate through results representing an entity like TestSet, performs uniquing on the result rows based on object identity, so that if the query were to return 100 rows each with the same TestSet primary key, you'd get only one result object back. This behavior has its origins in t...
[ 20 ]
[]
[]
[ "database", "python", "select", "sqlalchemy" ]
stackoverflow_0006933478_database_python_select_sqlalchemy.txt
Q: How do i create unittest in pyramid with mongodb? I have a pyramid project that uses mongodb for storage. Now I'm trying to write a test but how do I specify connection to the mongodb? More specifically, which database should I connect to (test?) and how do I use fixtures? In Django it creates a temporary database...
How do i create unittest in pyramid with mongodb?
I have a pyramid project that uses mongodb for storage. Now I'm trying to write a test but how do I specify connection to the mongodb? More specifically, which database should I connect to (test?) and how do I use fixtures? In Django it creates a temporary database but how does it work in pyramid?
[ "Just create a database in your TestCase.setUp and delete in TestCase.tearDown\nYou need mongodb running because there is no mongolite3 like sqlite3 for sql\nI doubt that django is able to create a temporary file to store a mongodb database. It probably just use sqlite:/// which create a database with a memory stor...
[ 2 ]
[]
[]
[ "mongodb", "pyramid", "python" ]
stackoverflow_0006515160_mongodb_pyramid_python.txt
Q: Performance gain using MPI I tested the performance gain of parallelizing the (nearly) "embarassingly parallel" (i.e. perfectly parallelizable) algorithm of summing up the first N integers: The serial algorithm is simply: N = 100000000 print sum(range(N)) Execution time on my dual core laptop (Lenovo X200): 0m21...
Performance gain using MPI
I tested the performance gain of parallelizing the (nearly) "embarassingly parallel" (i.e. perfectly parallelizable) algorithm of summing up the first N integers: The serial algorithm is simply: N = 100000000 print sum(range(N)) Execution time on my dual core laptop (Lenovo X200): 0m21.111s. The parallelized (with mp...
[ "How are you doing the timing, and what's your laptop?\nIf you're doing the timing from the shell, you may be (as BiggAl suggests) hitting a delay just starting up python. That's real overhead and worth knowing about, but probably isn't your immediate concern. And I have trouble imaginging that this contribute...
[ 5, 4, 3, 2, 1, 1, 0 ]
[]
[]
[ "mpi", "parallel_processing", "python" ]
stackoverflow_0005338338_mpi_parallel_processing_python.txt
Q: Python- find all subwords that can be found inside of a word Ultimately, I want to find out which word in the English dictionary contains the most subwords that are at least three letters. I wrote this algorithm, but it's too slow to be useful. Wondering ways I can optimize it def subWords(word): return set...
Python- find all subwords that can be found inside of a word
Ultimately, I want to find out which word in the English dictionary contains the most subwords that are at least three letters. I wrote this algorithm, but it's too slow to be useful. Wondering ways I can optimize it def subWords(word): return set((word[0:i] for i in range(2, len(word)+1))) #returns all subWords...
[ "The major weakness of your algorithm is that, for every subword, you need to compare it to every other word in the dictionary. You don't need to do that, really - if your word begins with 'a', you don't really need to see if it matches words that begin with 'b'. If the next letter is 'c', then you don't really car...
[ 7, 6, 3, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006933741_algorithm_python.txt
Q: Error when i'm trying to install my own package by pip. Python When i'm trying to install my package by command: pip install tv_sched_pars-0.1.macosx-10.6-universal.tar.gz gives me error: IOError: [Errno 2] No such file or directory: '/var/folders/5W/5WnKRhNyGe0O6x6IhEkbnE+++TI/-Tmp-/pip-dZHBRf-build/setup.py' ...
Error when i'm trying to install my own package by pip. Python
When i'm trying to install my package by command: pip install tv_sched_pars-0.1.macosx-10.6-universal.tar.gz gives me error: IOError: [Errno 2] No such file or directory: '/var/folders/5W/5WnKRhNyGe0O6x6IhEkbnE+++TI/-Tmp-/pip-dZHBRf-build/setup.py' Package was made by python setup.py bdist And then found in director...
[ "You have to either use bdist_egg or sdist. Only those create artifacts installable by pip / easy_install.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006934784_python.txt
Q: how to convert a list into html column in python I have been trying to work with python and using jinja template for my HTML rendering. The problem I have is that , I have two seperate lists. Column_List [col_name1,col_name2,....] Data_List [val1_col_name1,val2_col_name2,...] [val3_col_name1,val4_col_name2,...] [...
how to convert a list into html column in python
I have been trying to work with python and using jinja template for my HTML rendering. The problem I have is that , I have two seperate lists. Column_List [col_name1,col_name2,....] Data_List [val1_col_name1,val2_col_name2,...] [val3_col_name1,val4_col_name2,...] [val1_col_name1,val2_col_name2,...] So , any pointer...
[ "Supposing that your variables are passed to jinja with the using the same names:\ncol_names = [col_name1, col_name2, ...]\n\ndata = [\n [val1_col_name1, val2_col_name2, ...]\n [val3_col_name1, val4_col_name2, ...]\n [val1_col_name1, val2_col_name2, ...]\n]\n\nThen, the following jinja snippet is not that ...
[ 0 ]
[]
[]
[ "html", "list", "python" ]
stackoverflow_0006934898_html_list_python.txt
Q: 'unicode' object has no attribute 'replace' I have been running a Django site for a couple of months now and an hour ago began receiving the following error message (about three times a minute on various pages): AttributeError: 'unicode' object has no attribute 'replace' This is happening throughout the codebase...
'unicode' object has no attribute 'replace'
I have been running a Django site for a couple of months now and an hour ago began receiving the following error message (about three times a minute on various pages): AttributeError: 'unicode' object has no attribute 'replace' This is happening throughout the codebase, including in Django code itself. The codebase h...
[ "Here's a long shot:\nclass unicode(object):\n pass\n\ntest = unicode()\ntest.replace()\n\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'unicode' object has no attribute 'replace'\n\nAre there fake unicode objects somewhere? (Like I said, a long shot.) If you fin...
[ 1 ]
[]
[]
[ "django", "python", "replace", "unicode" ]
stackoverflow_0006228868_django_python_replace_unicode.txt
Q: How do I stop this program from calling a non-existant list element? import string ## This part of the code initializes the program by recieving inputs and saving ## them as strings. ## It also currently works! intext = str.lower(raw_input("Please input the text you are going to use. ")) ##print intext instring ...
How do I stop this program from calling a non-existant list element?
import string ## This part of the code initializes the program by recieving inputs and saving ## them as strings. ## It also currently works! intext = str.lower(raw_input("Please input the text you are going to use. ")) ##print intext instring = str.lower(raw_input("Please input your string. ")) ##print instring inle...
[ "Replace\nx+=1\n\nWith\nx = (x + 1) % len(searchstring)\n\nThe modulus operator does division and returns the remainder. So x from 0 up to the length of searchstring, the modulus does nothing (returns itself). If x == the length of searchstring, it \"resets\" to 0, because there is no remainder when dividing.\n" ...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006934936_list_python.txt
Q: Difference between run_wsgi_app and wsgiref.handlers.CGIHandler I'm just learning how to use python and GAE and I've noticed that the main URL handler is shown in two different ways. What's the difference in calling run_wsgi_app vs wsgiref.handlers.CGIHandler? I've seen sample code shown in both manner. applicat...
Difference between run_wsgi_app and wsgiref.handlers.CGIHandler
I'm just learning how to use python and GAE and I've noticed that the main URL handler is shown in two different ways. What's the difference in calling run_wsgi_app vs wsgiref.handlers.CGIHandler? I've seen sample code shown in both manner. application = webapp.WSGIApplication( [ ('/', MainPage), ...
[ "run_wsgi_app is the one you should be using. Amongst other things, it runs any middleware defined in appengine_config.py. The CGIHandler approach dates from before run_wsgi_app was introduced. There shouldn't be any examples of this left in the docs - where did you find it?\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006934755_google_app_engine_python.txt
Q: How to properly organize a Python class definition with respect to helper files for that class? This has probably been asked before but I couldn't find the answer to my specific question (fairly general...) Here is an example of my question. Say my package is called 'school', and I have a class called 'book' whic...
How to properly organize a Python class definition with respect to helper files for that class?
This has probably been asked before but I couldn't find the answer to my specific question (fairly general...) Here is an example of my question. Say my package is called 'school', and I have a class called 'book' which will have .py files along side it containing the meat of its methods. I'm not sure how to organize...
[ "You're confusing packages with classes I think. Personally, I'd put every class definition and all functions that were directly related to that class in the same .py file. For instance, reading is not an object, so I would put that as a function under the Book class, not it's own .py file. So, the structure would ...
[ 7 ]
[]
[]
[ "organization", "package", "python" ]
stackoverflow_0006935029_organization_package_python.txt
Q: Fill out Ajax forms in Python I'm trying to fill forms of an ajax box (just my term for those several forms) using the mechanize module, but it seems not to work. I'm not a web programmer but afaik the ajax box updates itself 'onchange' with an event which is handled by the browser. Mechanize seems not to handle t...
Fill out Ajax forms in Python
I'm trying to fill forms of an ajax box (just my term for those several forms) using the mechanize module, but it seems not to work. I'm not a web programmer but afaik the ajax box updates itself 'onchange' with an event which is handled by the browser. Mechanize seems not to handle that, in the links list (from the it...
[ "Mechanize doesn't handle javascript, see this answer for more details and an alternative solution How to properly use mechanize to scrape AJAX sites\n" ]
[ 2 ]
[]
[]
[ "ajax", "mechanize", "mechanize_python", "python" ]
stackoverflow_0006929709_ajax_mechanize_mechanize_python_python.txt
Q: Writing a file to a USB stick in linux with Python? I'm having a lot more trouble than expected writing to a file than I expected. I have a small Single Board computer running on an arm processor with the Angstrom embedded distribution. I'm writing an application for it with python. The application should detect t...
Writing a file to a USB stick in linux with Python?
I'm having a lot more trouble than expected writing to a file than I expected. I have a small Single Board computer running on an arm processor with the Angstrom embedded distribution. I'm writing an application for it with python. The application should detect the USB stick and then dump the file to it. The issue I'm ...
[ "The mistake is in the write function which should sync the file, before closing it, as seen below. The read will always succeed because the data is already in RAM. You might want to try something different to verify it such as checking the bytecount.\ndef write_and_verify(f_n,data):\n f = file(f_n,'w')\n f.w...
[ 1 ]
[]
[]
[ "file", "linux", "python", "usb_drive" ]
stackoverflow_0006840711_file_linux_python_usb_drive.txt
Q: reading corpus by python code for Arabic language I want to read Arabic dictionary Bw and then extract some lexical items like "N" , "V" by Python. Also, I have Arabic Pen treebank I want to extract trigram from it. I am so new for using Python, where do I begin? A: There is only one place to begin. http://www.n...
reading corpus by python code for Arabic language
I want to read Arabic dictionary Bw and then extract some lexical items like "N" , "V" by Python. Also, I have Arabic Pen treebank I want to extract trigram from it. I am so new for using Python, where do I begin?
[ "There is only one place to begin.\nhttp://www.nltk.org/\nPython is the most used tool for Natural Language processing and the community of academics who built and use the NLTK have probably already made a tool that will do most of what you need.\nIt is best to start out with a tutorial like this one, http://www.de...
[ 0 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0006219539_nltk_python.txt
Q: Is list comprehension appropriate here? I have to append elements to a list only if the current iterated element is not already in the list. >>> l = [1, 2] >>> for x in (2, 3, 4): ... if x not in l: ... l.append(x) ... >>> l [1, 2, 3, 4] vs >>> l = [1, 2] >>> [l.append(i) for i in (2, 3, 4) if i ...
Is list comprehension appropriate here?
I have to append elements to a list only if the current iterated element is not already in the list. >>> l = [1, 2] >>> for x in (2, 3, 4): ... if x not in l: ... l.append(x) ... >>> l [1, 2, 3, 4] vs >>> l = [1, 2] >>> [l.append(i) for i in (2, 3, 4) if i not in l] [None, None] >>> l [1, 2, 3, 4] Th...
[ "This algorithm, either with or without a list comprehension, is not as efficient as possible; list.__contains__ is O(n), and so adding the elements of another list to it is O(n2). On the other hand, set.__contains__ is O(log n), so the best way to do this is to use a set to check for membership, and a list to pr...
[ 7, 5, 3, 3 ]
[]
[]
[ "duplicates", "list", "list_comprehension", "python" ]
stackoverflow_0006935068_duplicates_list_list_comprehension_python.txt
Q: Python subprocess.call on sfxcl.exe not working from Windows 2003 Task Scheduler I have written a script in Python to call SecureFX's commandline tool (sfxcl.exe) result = subprocess.call([securefx, '/NoPrompt', '/Q', '/RetryCount', retries, '/RetryDelay', '1', '/Log', sfxLogFile, '/List', '/S', s...
Python subprocess.call on sfxcl.exe not working from Windows 2003 Task Scheduler
I have written a script in Python to call SecureFX's commandline tool (sfxcl.exe) result = subprocess.call([securefx, '/NoPrompt', '/Q', '/RetryCount', retries, '/RetryDelay', '1', '/Log', sfxLogFile, '/List', '/S', session]) and then converted it into .exe using py2exe. I can schedule it locally on ...
[ "So I've found the problem and it really is quite dumb.\nIf it works manually, you should expect it to work in the Task Scheduler.\nNow, I forgot to mention that it was using another account in the Scheduler, and that account didn't have SecureFX sessions/config set up and thus only that part didn't run.\nIt isn't ...
[ 0 ]
[]
[]
[ "py2exe", "python", "scheduled_tasks", "windows_server_2003" ]
stackoverflow_0006922129_py2exe_python_scheduled_tasks_windows_server_2003.txt
Q: comparison between the items of one list with the items of another list both of which reside in an outer list working with a big list This is my earlier post about this program which generates the following list. The program I am writing deals with a big linked list. This list is called phonemeList. The list is li...
comparison between the items of one list with the items of another list both of which reside in an outer list
working with a big list This is my earlier post about this program which generates the following list. The program I am writing deals with a big linked list. This list is called phonemeList. The list is like the following: [[('dh', [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [0.15, 0.35], [-1, -1]]), ('ih', [[-1, -1],...
[ "Honestly, sounds like you need a class, not a nested list.\nclass Phoneme():\n def __init__(self,named,variables,for,every,paired,value,in,the,crazy,list,you,posted):\n self.named = named\n self.variables = variables\n ##etc\n ##This way, we can see what you're comparing. The compari...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006934905_python.txt
Q: Delay Sum Beamforming in Python I am trying to implement a simple delay-sum beamformer using a 4 Microphone Array. I am using MATLAB at the moment, which has an inbuilt Signal Processing toolkit that is quite helpful. I was wondering if there are such tools in Python. For starters, i want to know how to get an aud...
Delay Sum Beamforming in Python
I am trying to implement a simple delay-sum beamformer using a 4 Microphone Array. I am using MATLAB at the moment, which has an inbuilt Signal Processing toolkit that is quite helpful. I was wondering if there are such tools in Python. For starters, i want to know how to get an audio signal from a microphone in real t...
[ "use pyAudio you can get the audio signal from mic in real time.\nhttp://people.csail.mit.edu/hubert/pyaudio/\nto plot it, you can use matplotlib or Chaco:\nChaco has an example that use pyAudio and plot the spectrum of the audio signal:\nhttps://github.com/enthought/chaco/blob/master/examples/demo/advanced/spectru...
[ 2 ]
[]
[]
[ "python", "signal_processing" ]
stackoverflow_0006935349_python_signal_processing.txt
Q: How to use joinedload/contains_eager for query-enabled relationships (lazy='dynamic' option) in SQLAlchemy I have the following model classes declared by SQLAlchemy: class User(Base): id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True) created_at = Colmn(DateTime, ...
How to use joinedload/contains_eager for query-enabled relationships (lazy='dynamic' option) in SQLAlchemy
I have the following model classes declared by SQLAlchemy: class User(Base): id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True) created_at = Colmn(DateTime, nullable=False, default=func.now()) class Post(Base): id = Column(Integer, primary_key=True) user_id = ...
[ "The problem is that the property on User for posts is a dynamic relationship; It's supposed to return a Query object. There's no way for the property to know, or safely communicate, that this time, all of the related items are already loaded. \nThe simple workaround will be to have two properties, one that uses...
[ 17 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006935809_python_sqlalchemy.txt
Q: Which Python module to use to access the Proxy setting of Windows 7? I am new to Python and would like to write a script to change Windows proxy settings based on the network I am connected to. Is there any existing python module I can use? Appreciate your help. Thanks, Sethu A: I would use winreg and query the ...
Which Python module to use to access the Proxy setting of Windows 7?
I am new to Python and would like to write a script to change Windows proxy settings based on the network I am connected to. Is there any existing python module I can use? Appreciate your help. Thanks, Sethu
[ "I would use winreg and query the settings directly from the registry. \n [HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet\n Settings] \"MigrateProxy\"=dword:00000001 \n \"ProxyEnable\"=dword:00000001\n \"ProxyHttp1.1\"=dword:00000000\n \"ProxyServer\"=\"http://ProxyServername:80\" \n \"Pr...
[ 3, 0 ]
[]
[]
[ "proxy", "python", "windows" ]
stackoverflow_0006935796_proxy_python_windows.txt
Q: subprocess and extra args I'm trying to use the following code: args = 'LD_LIBRARY_PATH=/opt/java/jre/lib/i386/:/opt/java/jre/lib/amd64/ exec /opt/java/jre/bin/java -Xincgc -Xmx1G -jar craftbukkit-0.0.1-SNAPSHOT.jar'.split() p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subproce...
subprocess and extra args
I'm trying to use the following code: args = 'LD_LIBRARY_PATH=/opt/java/jre/lib/i386/:/opt/java/jre/lib/amd64/ exec /opt/java/jre/bin/java -Xincgc -Xmx1G -jar craftbukkit-0.0.1-SNAPSHOT.jar'.split() p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) However, the result I...
[ "Try adding shell = True to the Popen call:\np = subprocess.Popen(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\nThe syntax you're using to set LD_LIBRARY_PATH is a shell syntax, so it's necessary to execute the command through the shell.\n", "Here's a method that avoi...
[ 7, 5 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006908134_python_subprocess.txt
Q: Video and Voice chat operability in Python I'm trying to find resources on video and voice chat operability in Python... Does anybody know of some good resources or sample projects? Any help would really be appreciated! A: If you want something higher level you can try Empathy. It has python bindings so you can ...
Video and Voice chat operability in Python
I'm trying to find resources on video and voice chat operability in Python... Does anybody know of some good resources or sample projects? Any help would really be appreciated!
[ "If you want something higher level you can try Empathy. It has python bindings so you can use chat GUI elements on your application or create your own. If you want something lower level, you might want to try to use Telepathy Python directly. \n", "Basically a farsight lib which has xmpp-jingle that can accomoda...
[ 1, 0 ]
[]
[]
[ "audio", "chat", "python", "voice" ]
stackoverflow_0000590053_audio_chat_python_voice.txt
Q: Python multiprocessing question Trying to think of the best way to code 2 processes that have to run in parallel. I not even sure if multiprocessing is the preferred module. I am generating a lot of data for a long period of time with a dataCollector, but I would like to check the data periodically with a dataChe...
Python multiprocessing question
Trying to think of the best way to code 2 processes that have to run in parallel. I not even sure if multiprocessing is the preferred module. I am generating a lot of data for a long period of time with a dataCollector, but I would like to check the data periodically with a dataChecker while the dataCollector keeps ru...
[ "Why would you use any module at all? This is simple to do by having two separate processes that start at the same time. The dataChecker would list all files in a directory, count them, and sleep for a short time (several seconds or more). Then it would do it again and if the number of files changes, it opens the n...
[ 2 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0006936158_multiprocessing_multithreading_python.txt
Q: Classify a table in lxml I am working with a large set of html documents. One of my tasks is to extract all text from the documents. I have gotten pretty far but now I am stumped because of the use of tables as containers / formatting structures for information that is not numeric in nature My goal is to ignore ...
Classify a table in lxml
I am working with a large set of html documents. One of my tasks is to extract all text from the documents. I have gotten pretty far but now I am stumped because of the use of tables as containers / formatting structures for information that is not numeric in nature My goal is to ignore - leave behind - not extract t...
[ "I would suggest contextual data parsing, such as implemented by IBM's Watson, but I suppose otherwise it is impossible to classify the table. Could you post html examples of a numeric and a non-numeric table? I'll update my answer when they are posted.\n" ]
[ 0 ]
[]
[]
[ "data_extraction", "html_parsing", "lxml", "python" ]
stackoverflow_0003643490_data_extraction_html_parsing_lxml_python.txt
Q: lxml node comparison Is there a way to check nodes equal with lxml library? For example in php DOMDocument there is isSameNode: a->isSameNode(b) //return boolean I need it to do something like this: def find_special_node(special_node, xml): #iterating nodes in xml if node == special_node: return n...
lxml node comparison
Is there a way to check nodes equal with lxml library? For example in php DOMDocument there is isSameNode: a->isSameNode(b) //return boolean I need it to do something like this: def find_special_node(special_node, xml): #iterating nodes in xml if node == special_node: return node
[ "You may be able to use xpath to find the item, using attributes of \"special_node\" as required attributes (and values) in find(). I assume that two nodes are determined to be the same if all attributes of the nodes are the same (such as type, value, size, etc.)\nJust a guess\nMy implementation:\nimport lxml.etre...
[ 1, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0004744401_lxml_python.txt
Q: RS232 Serial - USB Converter device path (/dev/ttyUSB*) not getting listed I am using an RS232 Serial - USB Converter to connect to a controller. I am trying to connect to this port programmatically. The device is getting listed as below when I give lsusb Bus 003 Device 003: ID 05ad:0fba Y.C. Cable U.S.A., Inc. ...
RS232 Serial - USB Converter device path (/dev/ttyUSB*) not getting listed
I am using an RS232 Serial - USB Converter to connect to a controller. I am trying to connect to this port programmatically. The device is getting listed as below when I give lsusb Bus 003 Device 003: ID 05ad:0fba Y.C. Cable U.S.A., Inc. But I am not able to see it's device path (something like /dev/ttyUSB*). I woul...
[ "Centos has a fairly old kernel. It may be lacking in support for your device. \nAre you able to try with a newer distribution (Fedora, Ubuntu, etc) to test whether it works or not? Failing that, do you have a different dongle you can use?\nYou can Google for \"Centos 05ad:0fba\" or similar combinations to find out...
[ 0 ]
[]
[]
[ "python", "ruby", "serial_port", "usb" ]
stackoverflow_0006936294_python_ruby_serial_port_usb.txt
Q: Using multiple indicies for arrays in python I have a simple question about how to use multiple indicies for an array or rec.array. More specifically, I want to isolate the cell(s) in an array which meet multiple stipulations. For example: import numpy as np test = np.ones(5) test_rec = test.view(recarray) test_r...
Using multiple indicies for arrays in python
I have a simple question about how to use multiple indicies for an array or rec.array. More specifically, I want to isolate the cell(s) in an array which meet multiple stipulations. For example: import numpy as np test = np.ones(5) test_rec = test.view(recarray) test_rec.age = np.array([0,1,2,1,4]) test_rec.sex = np.a...
[ "age_is_one = test_rec.age == 1\nsex_is_one = test_rec.sex == 1\nage_and_sex = numpy.logical_and(age_is_one, sex_is_one)\nindices = numpy.nonzero(age_and_sex)\ntest_rec[indices]\n\nSee:\nnumpy logical operations\nnumpy.nonzero\n", "use logical_and() or bitwise_and(), and you can use & operator to do bitwise_and()...
[ 1, 1 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0006936344_arrays_indexing_numpy_python.txt
Q: Convert args to flat list? I know this is very similar to a few other questions, but I can't quite get this function to work correctly. def flatten(*args): return list(item for iterable in args for item in iterable) The output I'm looking for is: flatten(1) -> [1] flatten(1,[2]) -> [1, 2] flatten([1,[2]]) -> ...
Convert args to flat list?
I know this is very similar to a few other questions, but I can't quite get this function to work correctly. def flatten(*args): return list(item for iterable in args for item in iterable) The output I'm looking for is: flatten(1) -> [1] flatten(1,[2]) -> [1, 2] flatten([1,[2]]) -> [1, 2] The current function, wh...
[ "For a quick solution, just take your second function and make it recursive.\ndef flatten(*args):\n output = []\n for arg in args:\n if hasattr(arg, '__iter__'):\n output.extend(flatten(*arg))\n else:\n output.append(arg)\n return output\n\n", "If you want to flatten a...
[ 6, 4, 1 ]
[ "Solved it...\ndef flatlist(*args):\n lst = []\n for a in args:\n if hasattr(a, '__iter__'): lst.extend(flatlist(*a))\n else: lst.append(a)\n return lst\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0002536197_list_python.txt
Q: Python intern for non-strings Why is Python's intern built-in only for strings? It should be possible to extend intern to classes that are hashable and comparable, right? A: The purpose of interning things is to be able to compare them by comparing their memory address; you ensure that you never create two obje...
Python intern for non-strings
Why is Python's intern built-in only for strings? It should be possible to extend intern to classes that are hashable and comparable, right?
[ "The purpose of interning things is to be able to compare them by comparing their memory address; you ensure that you never create two objects with the same value (when the program requests the creation of a second object with the same value as an existing object, it instead receives a reference to the pre-existing...
[ 14, 1, 0 ]
[]
[]
[ "language_features", "python" ]
stackoverflow_0006934202_language_features_python.txt
Q: django settings.py and multi-database help I'm using django1.3, wanted to put my data into 1000 databases, like app_idmod_0 ~ ap_idmod_999. Now I changed my settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracl...
django settings.py and multi-database help
I'm using django1.3, wanted to put my data into 1000 databases, like app_idmod_0 ~ ap_idmod_999. Now I changed my settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'myapp', ...
[ "For a start, I can't imagine what possible use you could have for 1000 databases. Unless you are Facebook, which I doubt.\nSecondly, you are setting each instance to the same dictionary, so when you change the name in the next iteration the previous name changes too. You need to copy the dictionary before changing...
[ 0 ]
[]
[]
[ "django", "multi_database", "python" ]
stackoverflow_0006935938_django_multi_database_python.txt
Q: Host Django with XAMPP on Windows Can I run a Django (Python framework) base site with XAMPP on Windows? Please guide me. A: XAMPP for windows contains: Apache, MySQL, PHP + PEAR, Perl, mod_php, mod_perl, mod_ssl, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, ...
Host Django with XAMPP on Windows
Can I run a Django (Python framework) base site with XAMPP on Windows? Please guide me.
[ "XAMPP for windows contains: Apache, MySQL, PHP + PEAR, Perl, mod_php, mod_perl, mod_ssl, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, Ming, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV + mod_auth_mysql. \nThere are two requirements t...
[ 49, 11, 6, 5, 0 ]
[]
[]
[ "django", "python", "xampp" ]
stackoverflow_0001000444_django_python_xampp.txt
Q: [python]: problem about passing map() with a func and 2 lists with different dimensions suppose I got a list, say lst1 = [1,2,3,4] and another list, say lst2 = [8,9] and a func, say func = lambda x,y: x+y what I want to do is to produce a list whose element is the sum of lst1's element and lst2's. i.e., I wa...
[python]: problem about passing map() with a func and 2 lists with different dimensions
suppose I got a list, say lst1 = [1,2,3,4] and another list, say lst2 = [8,9] and a func, say func = lambda x,y: x+y what I want to do is to produce a list whose element is the sum of lst1's element and lst2's. i.e., I want to produce a lst with lst1 and lst2, and lst should be [1+8+9, 2+8+9, 3+8+9, 4+8+9]. how...
[ ">>> map(lambda x: x + sum(lst2), lst1)\n[18, 19, 20, 21]\n\n", ">>> map(lambda x, y: x + y, lst1, itertools.repeat(sum(lst2), len(lst1)))\n[18, 19, 20, 21]\n\n", "Your func is simply add operator so you can use 'add' from operator module the following way:\nfrom operator import add\nlst = [1,2,3,4]\nsLst = [8,...
[ 6, 1, 0 ]
[]
[]
[ "map", "python" ]
stackoverflow_0006935099_map_python.txt
Q: Python equivalent of the ! operator For the following construct what can the more pythonic way? If it were C I could just use ! but what is it equivalent in Python? file_path = # something if os.path.exists(file_path): pass else: file_path = # make new path A: file_path = # something if not os.path.exi...
Python equivalent of the ! operator
For the following construct what can the more pythonic way? If it were C I could just use ! but what is it equivalent in Python? file_path = # something if os.path.exists(file_path): pass else: file_path = # make new path
[ "file_path = # something \nif not os.path.exists(file_path):\n file_path = #make new path\n\nPython Docs - Expressions - 5.1 Boolean Expressions\n", "The not keyword.\nif not os.path.exists(file_path):\n file_path ...\n\n", "Simply:\nfile_path = # something \nif not os.path.exists(file_path):\n file_p...
[ 4, 1, 0 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0006937473_operators_python.txt
Q: a question on for loops in python I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks. import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): ...
a question on for loops in python
I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks. import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): ...
[ "Generally, you can't. Three variables, three loops.\nBut this is a special case, as nobody pointed out. You can solve this problem with two loops.\nAlso, there's no point in checking y, z and z, y.\nOh, and range(10000, 1000) = [].\nimport math\n\nfor x in range(1, 1000):\n for y in range(x, 1000):\n z = mat...
[ 8, 4, 4, 2, 2, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0000588052_for_loop_python.txt
Q: Checking the status of a sent email in django I have a simple mail sending application which runs in python using Django. After sending an email is there a way to see if the recipient has opened it or is it still un-opened? if so how can i do it? A: You can try setting require return receipt flag on the email yo...
Checking the status of a sent email in django
I have a simple mail sending application which runs in python using Django. After sending an email is there a way to see if the recipient has opened it or is it still un-opened? if so how can i do it?
[ "You can try setting require return receipt flag on the email you are sending. But, a lot of people (I know I do) ignore that return receipt so you will never find out in those cases.\nIf you are asking for a 100% certain method of finding out if the recipient read his/her email, then the straight answer is: NO, yo...
[ 3, 3, 1 ]
[]
[]
[ "django", "email", "python" ]
stackoverflow_0006936252_django_email_python.txt
Q: querying abstract elements in xpath with python I'd like to make some xpath queries over abstract elements on the KML schema (like //AbstractFeatureType on a kml file). I'm a noob in python and that make the research and trial quite painful, has anybody crossed the path of this beast during their developing hours?...
querying abstract elements in xpath with python
I'd like to make some xpath queries over abstract elements on the KML schema (like //AbstractFeatureType on a kml file). I'm a noob in python and that make the research and trial quite painful, has anybody crossed the path of this beast during their developing hours? Thanks, Nico.
[ "This is just an attempt using the page you provided. My code returns a list of elements who have tagtype==attrib. s is a string with your xml/kml.\nimport lxml.etree as etree\ndef find(s,attrib,tagtype='*'):\n tree = etree.fromstring(s)\n return tree.xpath(r'.//%s[@*=\"%s\"]'%(tagtype,attrib))\n\n" ]
[ 1 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0006253391_lxml_python_xml_xpath.txt
Q: Why is collections.deque slower than collections.defaultdict? Forgive me for asking in in such a general way as I'm sure their performance is depending on how one uses them, but in my case collections.deque was way slower than collections.defaultdict when I wanted to verify the existence of a value. I used the spe...
Why is collections.deque slower than collections.defaultdict?
Forgive me for asking in in such a general way as I'm sure their performance is depending on how one uses them, but in my case collections.deque was way slower than collections.defaultdict when I wanted to verify the existence of a value. I used the spelling correction from Peter Norvig in order to verify a user's inpu...
[ "These three data structures aren't interchangeable, they serve very different purposes and have very different characteristics:\n\nLists are dynamic arrays, you use them to store items sequentially for fast random access, use as stack (adding and removing at the end) or just storing something and later iterating o...
[ 10 ]
[]
[]
[ "defaultdict", "deque", "performance", "python", "spell_checking" ]
stackoverflow_0006937893_defaultdict_deque_performance_python_spell_checking.txt
Q: How to flush cache for socket.gethostbyname response? Anyone run into this before: After updating DNS records..I do a dig for 'test.somedomain.com' I get 167.69.143.234, however when I do a socket.gethostbyname('test.somedomain.com') I get 167.69.6.234. I'm guessing socket is still using cache...how do I clear it...
How to flush cache for socket.gethostbyname response?
Anyone run into this before: After updating DNS records..I do a dig for 'test.somedomain.com' I get 167.69.143.234, however when I do a socket.gethostbyname('test.somedomain.com') I get 167.69.6.234. I'm guessing socket is still using cache...how do I clear it ? or flush it? My code is very simple: Linux Termianl dig ...
[ "Python's socket.gethostbyname uses the operating system resolver and has no API for clearing its cache. The cache (which may be a caching DNS server used by the operating system or a operating system or standard library component) is a fundamental element of the DNS system and 'the right way' to cope with it is to...
[ 7, 4 ]
[]
[]
[ "caching", "dns", "gethostbyname", "python", "sockets" ]
stackoverflow_0006928378_caching_dns_gethostbyname_python_sockets.txt
Q: python import statements I've started working on Python for about a month now and I've ran into something I would like to understand better. It's related to imports. So I have a module: root.core.connectivity Now in this module I have defined a class Connectivity. This module also has a __main__ only for test...
python import statements
I've started working on Python for about a month now and I've ran into something I would like to understand better. It's related to imports. So I have a module: root.core.connectivity Now in this module I have defined a class Connectivity. This module also has a __main__ only for testing purposes(not sure if this ...
[ "import takes a module. from X import Y takes a module in X, and any element of that module in Y. Connectivity is not a module.\n", "Connectivity is a class defined in module, import takes module and when using from-import we can import class of a module.\nThis link explains it well\nhttp://effbot.org/zone/import...
[ 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006938277_python.txt
Q: How to deal with a Cython ValueError I'm fairly new to Cython extension-types and puzzled with the following Cython-related ValueError that is thrown during runtime: ValueError: vrptwms.node.Node has the wrong size, try recompiling The Node class is defined in the files node.pxd and node.pyx in the directory vrpt...
How to deal with a Cython ValueError
I'm fairly new to Cython extension-types and puzzled with the following Cython-related ValueError that is thrown during runtime: ValueError: vrptwms.node.Node has the wrong size, try recompiling The Node class is defined in the files node.pxd and node.pyx in the directory vrptwms. The content of the former is cdef cla...
[ "Robert Bradshaw proposed a few hints on the cython-users mailing-list. The bottom line is that manually (re-)compiling the .pyx files with cython *.pyx and the running the original setup script works. There is also a newer way of writing the setup script described in CEP 201 - Distutils Preprocessing that should h...
[ 2, 0 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0006903441_cython_python.txt
Q: Python message partition error I'm receiving the following message trough TCP: {"message": "Start", "client": "134.106.74.21", "type": 1009}<EOM> but when I'm trying to partition that msg.partition( "<EOM>" ) I'm getting the following array: ('{\x00\x00\x00"\x00\x00\x00m\x00\x00\x00e\x00\x00\x00s\x00\x00\x00s...
Python message partition error
I'm receiving the following message trough TCP: {"message": "Start", "client": "134.106.74.21", "type": 1009}<EOM> but when I'm trying to partition that msg.partition( "<EOM>" ) I'm getting the following array: ('{\x00\x00\x00"\x00\x00\x00m\x00\x00\x00e\x00\x00\x00s\x00\x00\x00s\x00\x00\x00a\x00 \x00\x00g\x00\x00\...
[ "If you print msg.encode(\"hex\") then you will likely see that this is exactly what is in the string.\nIn any case, you may have noticed that every 4th byte of the result is one of the characters that you expected. This suggests that you have a UCS4 Unicode string that you are not handling properly.\nDid you recei...
[ 1 ]
[]
[]
[ "data_partitioning", "python" ]
stackoverflow_0006938439_data_partitioning_python.txt
Q: Escaping XPath literal with Python I'm writing a common library to setup an automation test suite with Selenium 2.0 Python's webdriver. def verify_error_message_present(self, message): try: self.driver.find_element_by_xpath("//span[@class='error'][contains(.,'%s')]" % message) self.assertTrue(T...
Escaping XPath literal with Python
I'm writing a common library to setup an automation test suite with Selenium 2.0 Python's webdriver. def verify_error_message_present(self, message): try: self.driver.find_element_by_xpath("//span[@class='error'][contains(.,'%s')]" % message) self.assertTrue(True, "Found an error message containing ...
[ "Parentheses should be fine there. They're inside an XPath string literal delimited by apostrophe, so they do not prematurely end the contains condition.\nThe problem is what happens when you have apostrophes in your string, since those do end the string literal, breaking the expression. Unfortunately there is no s...
[ 10 ]
[]
[]
[ "python", "selenium", "xml" ]
stackoverflow_0006937525_python_selenium_xml.txt
Q: Default values for arguments Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument Consider the following function: def foo(L = []): L.append(1) print L Each time I call foo it will print a new list with more elements than previous time, e.g: >>> foo() [1] >>> foo() [1, 1] >>> foo...
Default values for arguments
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument Consider the following function: def foo(L = []): L.append(1) print L Each time I call foo it will print a new list with more elements than previous time, e.g: >>> foo() [1] >>> foo() [1, 1] >>> foo() [1, 1, 1] Now consider the fo...
[ "The default arguments are evaluated once when the function is defined.\nSo you get the same list object each time the function is called.\nYou'll also get the same 0 object each time the second function is called, but since int is immutable, when you add 1 as fresh object needs to be bound to a\n>>> def foo(L = []...
[ 2 ]
[]
[]
[ "default_arguments", "function", "python" ]
stackoverflow_0006938655_default_arguments_function_python.txt