content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to detect that an axis belong to a window that has been closed in matplotlib In matplotlib, I keep a reference on an axis. I want to open a new figure if the window that contain the axis have been closed. The idea is to keep adding plots on the figure, until it is closed, then I open a new figure. Note that t...
How to detect that an axis belong to a window that has been closed in matplotlib
In matplotlib, I keep a reference on an axis. I want to open a new figure if the window that contain the axis have been closed. The idea is to keep adding plots on the figure, until it is closed, then I open a new figure. Note that the creation of new plots is triggered by an event in another figure. If it can help yo...
[ "Why not just connect a callback to the \"close_event\"? You could either add a ax.has_been_closed flag to the axes object or your class itself. (There are probably even cleaner solutions than a \"has_been_closed\" flag, depending on exactly what you're doing... The callback function can be anything.)\nimport matp...
[ 6 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006027608_matplotlib_python.txt
Q: Connection between Android phone and python server suggestion how can i connect a server code python on PC with android mobile so that i be able to then and receive data between the server and the android mobile ?? but put in consider that the socket can not be open on the mobile android despite its open on t...
Connection between Android phone and python server suggestion
how can i connect a server code python on PC with android mobile so that i be able to then and receive data between the server and the android mobile ?? but put in consider that the socket can not be open on the mobile android despite its open on the emulator and connect
[ "If you want your Android application to receive updates when things happen on the server, have you had a look at C2DM? One of the great things about this is that all Android applications share the same C2DM connection, so it is very light on battery usage.\n" ]
[ 0 ]
[]
[]
[ "android", "python", "sockets" ]
stackoverflow_0006034271_android_python_sockets.txt
Q: Why can’t Internet Explorer access my Django Development Server that’s accessible externally (i.e. not on localhost?) I've been tasked by my programming teacher to learn Django. However, I need to code on a command line linux box and therefore cannot access the web page from said linux box. To test, I need to host...
Why can’t Internet Explorer access my Django Development Server that’s accessible externally (i.e. not on localhost?)
I've been tasked by my programming teacher to learn Django. However, I need to code on a command line linux box and therefore cannot access the web page from said linux box. To test, I need to host it on the local IP of the computer rather than localhost. I’m currently running the Django development server using this c...
[ "Unfortunately (I am said teacher), I can't provide a linux host - only a linux server and a windows host to do development on. \nHe's actually running the web server correctly, with the command provided by Paul. But for some reason, it's only visible in Firefox/Chrome, IE just provides a generic \"Webpage cannot b...
[ 7, 5, 1, 1 ]
[]
[]
[ "django", "localhost", "python" ]
stackoverflow_0006034313_django_localhost_python.txt
Q: raw escape in python except last char Why in python I can't use: r"c:\" A: When a string must contain the same quote character with which it starts, escaping that character is the only available workaround -- so the design alternative was either to make raw-string literals unable to contain their leading quote c...
raw escape in python except last char
Why in python I can't use: r"c:\"
[ "When a string must contain the same quote character with which it starts, escaping that character is the only available workaround -- so the design alternative was either to make raw-string literals unable to contain their leading quote character, or keep the \"backlash escapes\" convention, even in string literal...
[ 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001764291_python.txt
Q: Bad magic number error persists even after rebuilding the .pyc file When running a Python 3 script of mine, I encounter a "Bad magic number" error (while the script tries to import another module). At first I imagined it's because there are .pyc files built by Python 2. I deleted the __pycache__ directory and rera...
Bad magic number error persists even after rebuilding the .pyc file
When running a Python 3 script of mine, I encounter a "Bad magic number" error (while the script tries to import another module). At first I imagined it's because there are .pyc files built by Python 2. I deleted the __pycache__ directory and reran the script, but the interpreter still gives me the same error when impo...
[ "The last line of the stack trace shows the path to the pyc file causing the error:\nImportError: Bad magic number in /home/mostafa/python/list.pyc\n\nAssuming you have list.py in your PYTHONPATH, you can delete /home/mostafa/python/list.pyc. When you import list, Python3 will generate a new version of list.pyc bas...
[ 12 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006034621_python_python_3.x.txt
Q: Python: Replace ith occurence of x with ith element in list Suppose we have a string a = "01000111000011" with n=5 "1"s. The ith "1", I would like to replace with the ith character in "ORANGE". My result should look like: b = "0O000RAN0000GE" What could be the finest way to solve this problem in Python? Is it pos...
Python: Replace ith occurence of x with ith element in list
Suppose we have a string a = "01000111000011" with n=5 "1"s. The ith "1", I would like to replace with the ith character in "ORANGE". My result should look like: b = "0O000RAN0000GE" What could be the finest way to solve this problem in Python? Is it possible to bind an index to each substitution? Many thanks! Helga
[ "Tons of answers/ways to do it. Mine uses a fundamental assumption that your #of 1s is equal to the length of the word you are subsituting. \na = \"01000111000011\"\na = a.replace(\"1\", \"%s\")\nb = \"ORANGE\"\nprint a % tuple(b)\n\nOr the pythonic 1 liner ;)\nprint \"01000111000011\".replace(\"1\", \"%s\") % tu...
[ 6, 5, 3, 0, 0 ]
[]
[]
[ "loops", "python", "replace", "string", "substitution" ]
stackoverflow_0006033321_loops_python_replace_string_substitution.txt
Q: Scraping ASP.NET with Python and urllib2 I've been trying (unsuccessfully, I might add) to scrape a website created with the Microsoft stack (ASP.NET, C#, IIS) using Python and urllib/urllib2. I'm also using cookielib to manage cookies. After spending a long time profiling the website in Chrome and examining the...
Scraping ASP.NET with Python and urllib2
I've been trying (unsuccessfully, I might add) to scrape a website created with the Microsoft stack (ASP.NET, C#, IIS) using Python and urllib/urllib2. I'm also using cookielib to manage cookies. After spending a long time profiling the website in Chrome and examining the headers, I've been unable to come up with a w...
[ "For anyone else that might be in a similar predicament in the future: \nI'd just like to note that I've had a lot of success with a Greasemonkey user script in Chrome to do all of my scraping and automation. I found it to be a lot easier than Python + urllib2 (at least for this particular case). The user scripts...
[ 2, 1 ]
[]
[]
[ "asp.net", "asp.net_ajax", "python", "screen_scraping", "urllib2" ]
stackoverflow_0005973245_asp.net_asp.net_ajax_python_screen_scraping_urllib2.txt
Q: Valid fields while Inserting a contact using google shared contact api using python trying to add a contact below is sample code from api where can i get all the valid fields like organization etc and some sample python code for that? new_contact = gdata.contacts.ContactEntry(title=atom.Title(text=name)) new_conta...
Valid fields while Inserting a contact using google shared contact api using python
trying to add a contact below is sample code from api where can i get all the valid fields like organization etc and some sample python code for that? new_contact = gdata.contacts.ContactEntry(title=atom.Title(text=name)) new_contact.content = atom.Content(text=notes) # Create a work email address for the contact and u...
[ "There's a pretty full list of attributes in the gdata-python-client source code (see the PersonEntry and ContactEntry classes) and some example code for using the client as well.\n" ]
[ 0 ]
[]
[]
[ "gdata_python_client", "python" ]
stackoverflow_0005592908_gdata_python_client_python.txt
Q: python mysqldb multiple connections Hey guys, i have the following problem: 1 process executes a very large query and writes the results to a file, inbetween the process should update an status to the database. first thaught: NO PROBLEM, pseudo code: db = mysqldb.connect() cursor = db.cursor() large = cursor.execu...
python mysqldb multiple connections
Hey guys, i have the following problem: 1 process executes a very large query and writes the results to a file, inbetween the process should update an status to the database. first thaught: NO PROBLEM, pseudo code: db = mysqldb.connect() cursor = db.cursor() large = cursor.execute(SELECT * FROM VERYLARGETABLE) for resu...
[ "Try using a MySQL SSCursor. It will keep the result set in the server (MySQL data structure), rather than transfer the result set to the client (Python data structure) which is what the default cursor does. Using an SSCursor will avoid the long initial delay caused by the default cursor trying to build a Python da...
[ 6, 4, 2 ]
[]
[]
[ "connection", "mysql_python", "python" ]
stackoverflow_0006035312_connection_mysql_python_python.txt
Q: Writing out a list of strings to a file I have a list of abbreviations Letters = ['Ala', 'Asx', 'Cys', ... 'Glx'] I want to output this to a text file that will look this like: #Letters Ala, Asx, Cys, ..... Glx Noob programmer here! I always forget the simplest things! ah please help and thanks! import Bio from ...
Writing out a list of strings to a file
I have a list of abbreviations Letters = ['Ala', 'Asx', 'Cys', ... 'Glx'] I want to output this to a text file that will look this like: #Letters Ala, Asx, Cys, ..... Glx Noob programmer here! I always forget the simplest things! ah please help and thanks! import Bio from Bio import Seq from Bio.Seq import Alphabet ...
[ "How about fh.write(', '.join(Letters))?\n", "I don't know much about the bio package but I guess ...\nfor letter in letters:\n fh.write(letter + ',')\n\nor \nfh.write(\",\".join(letters))\n\n" ]
[ 5, 1 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0006035904_bioinformatics_biopython_python.txt
Q: python regex strips out backslash With this code I get: newContent='asdf asdf \nOUTPUT_DIRECTORY = working\topOnly' I'd expect it to be: newContent='asdf asdf \nOUTPUT_DIRECTORY = working\\topOnly' The reg ex is stripping out a """\""" between """working""" and """topOnly""". If I do something lik...
python regex strips out backslash
With this code I get: newContent='asdf asdf \nOUTPUT_DIRECTORY = working\topOnly' I'd expect it to be: newContent='asdf asdf \nOUTPUT_DIRECTORY = working\\topOnly' The reg ex is stripping out a """\""" between """working""" and """topOnly""". If I do something like """valStr = 'working\\ytopOnly'""" th...
[ "The help for re.sub says:\n\nrepl can be either a string or a callable; if a string, backslash escapes in it are processed.\n\nSince it's doing its own layer of processing escapes, you will need another layer of escapes:\nnewContent = re.compile(varRegEx, re.VERBOSE).sub(r'\\1%s'%valStr.replace('\\\\', '\\\\\\\\')...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006035347_python_regex.txt
Q: Python closure not working as expected When I run the following script, both lambda's run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value "f" was set to when the lambda was created. Is there a way to get this to function as I expect? import os def main(): files = [r'...
Python closure not working as expected
When I run the following script, both lambda's run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value "f" was set to when the lambda was created. Is there a way to get this to function as I expect? import os def main(): files = [r'C:\_local\test.txt', r'C:\_local\junk.txt']...
[ "One way is to do this:\ndef main():\n files = [r'C:\\_local\\test.txt', r'C:\\_local\\junk.txt']\n funcs = []\n for f in files:\n # create a new lambda and store the current `f` as default to `path`\n funcs.append(lambda path=f: os.stat(path))\n print funcs\n\n # calling the lambda wit...
[ 24, 5 ]
[]
[]
[ "closures", "lambda", "python" ]
stackoverflow_0006035848_closures_lambda_python.txt
Q: Is MVC a good design pattern for a GAE app? my GAE app is currently setup with the following filenames main.py (2 main models and logic for creating and updating the models) i18n.py (user interface logic how to view objects with i18n) reports.py (cron-based reporting script) I think the names are clear enough bu...
Is MVC a good design pattern for a GAE app?
my GAE app is currently setup with the following filenames main.py (2 main models and logic for creating and updating the models) i18n.py (user interface logic how to view objects with i18n) reports.py (cron-based reporting script) I think the names are clear enough but I am considering to follow a model-view-control...
[ "You are miss-understanding MVC. Model, View, Controler is in three parts. \nModel - contains the business logic. Knows how to read/write to the database.\n View - Contains the display logic. Knows how to fetch data from model and display it to the user. \n Controller - understands user gestures, loads/finds th...
[ 2 ]
[]
[]
[ "design_patterns", "google_app_engine", "modularization", "python" ]
stackoverflow_0006034265_design_patterns_google_app_engine_modularization_python.txt
Q: Example for accessing Tcl functions from Python elmer enables one to run Python code from Tcl. What about the other way around? Could anyone give an example in Python? Update: by this I mean, being able to access Tcl objects, invoke Tcl functions, etc. instead of simply running some Tcl code. A: This is a rather...
Example for accessing Tcl functions from Python
elmer enables one to run Python code from Tcl. What about the other way around? Could anyone give an example in Python? Update: by this I mean, being able to access Tcl objects, invoke Tcl functions, etc. instead of simply running some Tcl code.
[ "This is a rather old thread, but I recently stumbled on Tkinter.Tcl() which gives you direct access to a Tcl interpreter in python without having to spawn a Tk GUI as Tkinter.Tk() requires.\nAn example... suppose you have a Tcl file (foo.tcl) with a proc called main that requires an single filename as an argument....
[ 8, 4, 1 ]
[ "This?\nimport subprocess\nsubprocess.Popen( \"tclsh someFile.tcl\", shell=True )\n\n" ]
[ -4 ]
[ "python", "tcl" ]
stackoverflow_0002519532_python_tcl.txt
Q: How to parse MySQL built-code from within Python? I've exported my MySQL database to a .txt/.sql file (link) and want to use this to rebuilt the database on other computers. While running the script in HeidiSQL works perfectly fine, I want to make sure all the tables exist and are correct before starting my applic...
How to parse MySQL built-code from within Python?
I've exported my MySQL database to a .txt/.sql file (link) and want to use this to rebuilt the database on other computers. While running the script in HeidiSQL works perfectly fine, I want to make sure all the tables exist and are correct before starting my application. I could copy paste the built code into my Python...
[ "You can just execute the sql from the file fully and directly via a python database adapter:\nimport MySQLdb\nsql_dump = open('builtcode.sql', 'r').read()\n\nconn = MySQLdb.connect(db='soans', passwd='*****')\ncur = conn.cursor()\n\ncur.execute(sql_dump)\n\ncur.connection.close()\n\nGives:\nmysql> show tables;\n+-...
[ 3, 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006035972_mysql_python.txt
Q: How do I change the attributes of elements in a list of instances of a user defined class? I'm trying to iterate through a list, workerl of instances of a class I defined, worker, and based on one of the class attributes, isemployed, grab 5 of those and call a function on them, fire(). I've tried many different w...
How do I change the attributes of elements in a list of instances of a user defined class?
I'm trying to iterate through a list, workerl of instances of a class I defined, worker, and based on one of the class attributes, isemployed, grab 5 of those and call a function on them, fire(). I've tried many different ways, but I either get stuck in an endless loop or I get the wrong values. Please let me know wha...
[ "What you are looking for is the random.choice function. It allows you to choose a randomly selected value from a list. Here's how it might work:\nclass Population:\n employee_list = []\n ...\n\n # Create a set that will contain the unique indices of newly fired employees\n fired_indices = set()\n\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006035926_python.txt
Q: Opening a file in text mode can lead to data loss in Python: why? The documentation for codecs.open() mentions that Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. How can using text mode for a file lead to "data l...
Opening a file in text mode can lead to data loss in Python: why?
The documentation for codecs.open() mentions that Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. How can using text mode for a file lead to "data loss"? It sounds like opening a file in text mode might truncate bytes ...
[ "I think what they mean is that some encodings use all 8 bits in at least some bytes, so that all 256 values are possible (and in particular, it's possible to get 0x0A or 0x0D that don't mean CR or LF).\nIn contrast, in a UTF-8 file, CR and LF characters (and all other character below 0x80) always translate to them...
[ 5 ]
[]
[]
[ "7_bit", "8_bit", "codec", "python" ]
stackoverflow_0006036677_7_bit_8_bit_codec_python.txt
Q: A numpy.arange style function with array inputs I have numpy arrays of start indices and end indices from which I'd like to construct a flattened array of ranges. e.g. with inputs s = np.array([1,2,3]) e = np.array([4,5,10]) and output array([1,2,3,2,3,4,3,4,5,6,7,8,9]) any way to do this efficiently? A: How a...
A numpy.arange style function with array inputs
I have numpy arrays of start indices and end indices from which I'd like to construct a flattened array of ranges. e.g. with inputs s = np.array([1,2,3]) e = np.array([4,5,10]) and output array([1,2,3,2,3,4,3,4,5,6,7,8,9]) any way to do this efficiently?
[ "How about just\nnp.concatenate([np.arange(x, y) for x, y in zip(s, e)])\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006036837_numpy_python.txt
Q: How to use Python to search for file by name, find the latest modified, find next file and repeat steps? I have a folder that has many DWG files and an example of some files might be LINCOLN 09-17 #1-29H ASBUILT 10-26-2010.dwg LINCOLN 09-17 #1-29H FINAL 01-20-2011.dwg CAMPBELL 07-17 #5-29H DRAFT 01-20-2011.dwg CAM...
How to use Python to search for file by name, find the latest modified, find next file and repeat steps?
I have a folder that has many DWG files and an example of some files might be LINCOLN 09-17 #1-29H ASBUILT 10-26-2010.dwg LINCOLN 09-17 #1-29H FINAL 01-20-2011.dwg CAMPBELL 07-17 #5-29H DRAFT 01-20-2011.dwg CAMPBELL 07-17 #5-29H FINAL 01-27-2011.dwg CAMPBELL 07-17 #5-29H FINAL 01-27-2011_1.dwg I would need to capture ...
[ "You need to go searching for the suitable files, and remeber the newest of each one as\nyou come accross it. Then report the latest.\nIn pseudo-code.\ndates = dict() // key is filename, value is date\nfor subdir,dirs, files in os.walk(startdir):\nif filename ends with \"dwg\":\n if filename contains \"FINAL\"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006035263_python.txt
Q: google app engine: getting form fields How do I get access to the form data. I want to do this before is_valid() is carried out. How do I access a field. I seem to be getting a blank address though. The code looks like: def post(self): data = CompanyForm(data=self.request.POST) map_url = '' address...
google app engine: getting form fields
How do I get access to the form data. I want to do this before is_valid() is carried out. How do I access a field. I seem to be getting a blank address though. The code looks like: def post(self): data = CompanyForm(data=self.request.POST) map_url = '' address = str(data['company_postcode']) addres...
[ "According to the Request class documentation, Request does not have a POST instance variable. You can call self.request.get('company_postcode') to obtain the posted value for company_postcode.\nFor debugging, the raw POST data can be obtained from self.request.body.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006036776_google_app_engine_python.txt
Q: Python data structure for sparse list of x/y co-ordinates Consider list of x/y co-ordinates and a byte 'count'. x/y will have a range of perhaps 0 to 5000 which is 25 million cells. However the data will be quite sparsely populated, there will be at most a few thousand entries and the majority of co-ordinates will...
Python data structure for sparse list of x/y co-ordinates
Consider list of x/y co-ordinates and a byte 'count'. x/y will have a range of perhaps 0 to 5000 which is 25 million cells. However the data will be quite sparsely populated, there will be at most a few thousand entries and the majority of co-ordinates will have zero entries. The structure will be occasionally looked u...
[ "A dictionary keyed by a point (ie a 2-tuple) sound good to me. It's O(1) like an array, and significantly more compact. As long as you never need to do range queries or the like, it should be fine.\n# increment\np = (x, y)\ncounts[p] = counts.get(p, 0) + 1\n\n# list\nfor (p, count) in counts.iteritems():\n x, y...
[ 5, 4, 2 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0006037084_data_structures_python.txt
Q: Reordering Modified QuerySet My database is set up with a list of cases with an ID from our ticketing system, a location, an assigned person and a short description taken from the ticket: Case ID Location Assigned Person Short Description Status Now to help better sort things, depending on certain status values...
Reordering Modified QuerySet
My database is set up with a list of cases with an ID from our ticketing system, a location, an assigned person and a short description taken from the ticket: Case ID Location Assigned Person Short Description Status Now to help better sort things, depending on certain status values, we change the QuerySet after qu...
[ "Since you're evaluating the queryset and then modifying some of the elements without saving, you need to avoid anything that goes back to the database and re-evaluates it. In your case, there's nothing wrong with simply ordering the list in Python - for example:\ncurrent_active.sort(key=lambda x: x.assigned_tech)\...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_queryset", "python", "sorting" ]
stackoverflow_0006036602_django_django_queryset_python_sorting.txt
Q: need help with a function problem hi im in need of some help for some basic programming exercises im working through. here's the problem. a) Write a function that returns the maximum value from a list of names. The list of names is passed to the the function, the function returns the 'max' string.(essentially get ...
need help with a function problem
hi im in need of some help for some basic programming exercises im working through. here's the problem. a) Write a function that returns the maximum value from a list of names. The list of names is passed to the the function, the function returns the 'max' string.(essentially get the name that comes first alphabeticall...
[ "For part a), read how to use list.sort(). For part b), read this previous question on how to replace items in a list.\n" ]
[ 1 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0006037396_list_python_string.txt
Q: Unable to connect Django app to an external PostgreSQL database Short Description I am having a number of issues trying to connect a Django app (currently setup as SQLite3) to a newly created PostgreSQL on my Ubuntu Server. The Question(s) Can anyone share their success in doing this? Is there a good step-by-st...
Unable to connect Django app to an external PostgreSQL database
Short Description I am having a number of issues trying to connect a Django app (currently setup as SQLite3) to a newly created PostgreSQL on my Ubuntu Server. The Question(s) Can anyone share their success in doing this? Is there a good step-by-step tutorial on doing this? Or at least useful pointers on how to deb...
[ "I'm no Python guy but you do need the PostgreSQL libraries installed as the Python interface to PostgreSQL (psycopg) is just a Python layer on top of the PostgreSQL C libraries. So, no PostgreSQL development libraries means there's nothing to wrap in Python and no way to talk to PostgreSQL from Python.\n", "You ...
[ 1, 0, 0 ]
[]
[]
[ "django", "macos", "postgresql", "python", "ubuntu" ]
stackoverflow_0005986340_django_macos_postgresql_python_ubuntu.txt
Q: Detecting blog or forum software using python? Is there a way beside checking for known signatures in the site content to find out what kind of software is the website running e.g vbbuliten,WP etc, preferably python. A: re_generator = re.compile('<meta name="generator" content="(.*?)" /?>', re.IGNORECASE) This ...
Detecting blog or forum software using python?
Is there a way beside checking for known signatures in the site content to find out what kind of software is the website running e.g vbbuliten,WP etc, preferably python.
[ "re_generator = re.compile('<meta name=\"generator\" content=\"(.*?)\" /?>', re.IGNORECASE)\n\nThis might be helpful\n", "Some sites will set the 'generator' meta-tag in the html head. \n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006037379_python.txt
Q: Add specific columns to a single row list (might be a little basic) I am designing a password recovery program, and I want to make it "right"/modular enough to be plugged into other programs, so I am trying to avoid ugly hacks. Here's the rundown: I have a list with a string myString = "Hey what's up?" myString2DL...
Add specific columns to a single row list (might be a little basic)
I am designing a password recovery program, and I want to make it "right"/modular enough to be plugged into other programs, so I am trying to avoid ugly hacks. Here's the rundown: I have a list with a string myString = "Hey what's up?" myString2DList = [ myString, ] Now I have a 2D list with a single row. All ...
[ "If I under stand your question properly. Take a look at this to see if it will work for you.\nstr_1 = 'Hey What\\'s Up?'\nstr_2 = 'Hey, Not Much!'\nmy2dlist = [[str_1]] #Note the double brackets\nmy2dlist.append([str_2]) # Note that you are appending a List to the other list.\nprint my2dlist # Yields: [[\"Hey Wha...
[ 2, 2 ]
[]
[]
[ "2d", "append", "list", "python" ]
stackoverflow_0006037556_2d_append_list_python.txt
Q: variable within a nested loop in python I'm trying to figure what the values of xcoord_orig and ycoord_orig are when the last conditional statement is true i.e. when board[xcoordT][ycoordT] == computer. I feel that as I have it right now, I'm simply printing their values if the conditional statement is true. But...
variable within a nested loop in python
I'm trying to figure what the values of xcoord_orig and ycoord_orig are when the last conditional statement is true i.e. when board[xcoordT][ycoordT] == computer. I feel that as I have it right now, I'm simply printing their values if the conditional statement is true. But what I really want are the values of xcoord_...
[ "This\nfor i in range(len(valid_list)):\n ... \n for i in range(2,8):\n\nIs epic fail. It can't be correct.\n" ]
[ 2 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0006037428_for_loop_python.txt
Q: Outputting and Responding to Javascript with PyQt I am trying to use PyQt to load the html of a web page which can then be manipulated and fed back to the page for web scraping. I am basically trying to log into a page with Javascript on it, search for documents to download (by selecting a check box next to the co...
Outputting and Responding to Javascript with PyQt
I am trying to use PyQt to load the html of a web page which can then be manipulated and fed back to the page for web scraping. I am basically trying to log into a page with Javascript on it, search for documents to download (by selecting a check box next to the correct one's names), and then clicking a download button...
[ "I use pyqt/pyside to load a page, wait for the JavaScript to execute, then parse the resulting HTML for the content of interest.\nHere is an example script:\nhttp://webscraping.com/blog/Scraping-JavaScript-webpages-with-webkit/\n", "I think you are confused about where things happen, so it is not clear to me wha...
[ 2, 0 ]
[]
[]
[ "javascript", "pyqt", "pyside", "python", "screen_scraping" ]
stackoverflow_0006032287_javascript_pyqt_pyside_python_screen_scraping.txt
Q: Remove a bad tag completely with html5lib.sanitizer I'm trying to use html5lib.sanitizer to clean user-input as suggested in the docs The problem is I want to remove bad tags completely and not just escape them (which seems like a bad idea anyway). The workaround suggested in the patch here doesn't work as expecte...
Remove a bad tag completely with html5lib.sanitizer
I'm trying to use html5lib.sanitizer to clean user-input as suggested in the docs The problem is I want to remove bad tags completely and not just escape them (which seems like a bad idea anyway). The workaround suggested in the patch here doesn't work as expected (it keeps inner content of a <tag>content</tag>). Speci...
[ "The challenge is to also strip unwanted nested tags. It isn't pretty but it's a step in the right direction:\nfrom lxml.html import fromstring\nfrom lxml import etree\n\nhtml = '''\n<script>bad_thing();</script>\n<style>* { background: #000; }</style>\n<h1>Hello world<script>bad_thing();</script></h1>\nLorem ipsum...
[ 1 ]
[]
[]
[ "html5lib", "html_sanitizing", "python", "sanitizer", "tokenize" ]
stackoverflow_0006032457_html5lib_html_sanitizing_python_sanitizer_tokenize.txt
Q: python encoding/decoding problem I'm trying to use python's Template object to create html emails. However, when the app tries to send the emails I get the error: File "/base/data/home/apps/hanksandbox/1.350486862928605153/main.py", line 573, in post html = messages.email_document_html(document) File "/base/data/h...
python encoding/decoding problem
I'm trying to use python's Template object to create html emails. However, when the app tries to send the emails I get the error: File "/base/data/home/apps/hanksandbox/1.350486862928605153/main.py", line 573, in post html = messages.email_document_html(document) File "/base/data/home/apps/hanksandbox/1.350486862928605...
[ "Use unicode everywhere.\nemail_document = Template(u\"\"\"\n ...\n\n\"Unicode In Python, Completely Demystified\"\n", "Put a u before your template string to specify that it is intended to be a unicode string. Python < 3 interprets strings like that as ASCII unless told otherwise.\nemail_document = Template(u\"\...
[ 6, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006038043_google_app_engine_python.txt
Q: best platform to draw curves and create JPEGs i have an equation of a curve that i need to draw like: ((X^z)-1)/z = y does anyone know how i can draw this curve and save it as an image using python or .net? A: A good library for 2d plots in Python is http://matplotlib.sourceforge.net/. The resulting plot can be...
best platform to draw curves and create JPEGs
i have an equation of a curve that i need to draw like: ((X^z)-1)/z = y does anyone know how i can draw this curve and save it as an image using python or .net?
[ "A good library for 2d plots in Python is http://matplotlib.sourceforge.net/. The resulting plot can be saved straight from the plot dialog.\n", "Here's an example of drawing your curve in .NET/C#:\nReferences:\nusing System;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\n...
[ 7, 1 ]
[]
[]
[ ".net", "curve", "graph", "math", "python" ]
stackoverflow_0006037656_.net_curve_graph_math_python.txt
Q: Create Loop from Existing Code Below is a code that will open a .csv file and insert a header at line '0' What I want to do is create a loop so that I can point the code at a directory and loop through each file one by one. Each file in the directory have 23 million lines and I am running into memory errors when ...
Create Loop from Existing Code
Below is a code that will open a .csv file and insert a header at line '0' What I want to do is create a loop so that I can point the code at a directory and loop through each file one by one. Each file in the directory have 23 million lines and I am running into memory errors when I try to write the loop. The code be...
[ "Yeah, don't do that. Open the new file, write out the header, use shutil.copyfileobj() to copy the contents, then rename.\n", "Readlines reads the entire file in to memory. Do this to read the file one line at atime.\nfor line in f:\n L.append(line)\n\nYou don't need to use xrange in the second loop. You can...
[ 3, 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0006038646_for_loop_python.txt
Q: What is the most elegant way of selecting a subset of columns using pytables? I have a dataset with 300+ columns in pytables, and I want to be able to choose different subsets easily. There doesn't seem to be a very elegant solution to this, or is there something I'm missing? I would also be happy with a way to...
What is the most elegant way of selecting a subset of columns using pytables?
I have a dataset with 300+ columns in pytables, and I want to be able to choose different subsets easily. There doesn't seem to be a very elegant solution to this, or is there something I'm missing? I would also be happy with a way to create another table that is simply aliasing select columns from the original tabl...
[ "Would something like this work?\nfrom numpy import array, dtype\nfrom h5py import File\nfrom operator import itemgetter\n\n# Dummy data\n\nd = dtype([('a', int),('b', int),('c', int)])\na = array([(1, 6, 4), (5, 7, 1), (9, 7, 8), (3, 1, 2), (2, 1, 6)],dtype=d)\n\nhdf = File('tmp.hdf','a')\nhdf.create_dataset('data...
[ 6 ]
[]
[]
[ "hdf5", "pytables", "python" ]
stackoverflow_0006038241_hdf5_pytables_python.txt
Q: How to tell if a Python modules I being reload()ed from within the module When writing a Python module, is there a way to tell if the module is being imported or reloaded? I know I can create a class, and the __init__() will only be called on the first import, but I hadn't planning on creating a class. Though, I ...
How to tell if a Python modules I being reload()ed from within the module
When writing a Python module, is there a way to tell if the module is being imported or reloaded? I know I can create a class, and the __init__() will only be called on the first import, but I hadn't planning on creating a class. Though, I will if there isn't an easy way to tell if we are being imported or reloaded.
[ "The documentation for reload() actually gives a code snippet that I think should work for your purposes, at least in the usual case. You'd do something like this:\ntry:\n reloading\nexcept NameError:\n reloading = False # means the module is being imported\nelse:\n reloading = True # means the module is b...
[ 3, 0 ]
[]
[]
[ "python", "python_module", "reload" ]
stackoverflow_0006038898_python_python_module_reload.txt
Q: Do I need to update the watch when new sub-folder add in the monitor folder I have watch a folder that will create a new sub-folder use date as name(e.g 201105124) everyday. I have start a daemon to watch it but if a new sub-folder added, the event in the new sub-folder cannot be trigger. IS that I need to update ...
Do I need to update the watch when new sub-folder add in the monitor folder
I have watch a folder that will create a new sub-folder use date as name(e.g 201105124) everyday. I have start a daemon to watch it but if a new sub-folder added, the event in the new sub-folder cannot be trigger. IS that I need to update the watch for the new folder? Thx for your answer. Regards Roy
[ "And I find that there is an parameter auto_add in function add_watch,\nwhich can auto add the directory in the watch when it is created.\nBut it need the event IN_CREATE.\n", "Yes, you need to use update_watch after directory creation.\n" ]
[ 2, 0 ]
[]
[]
[ "pyinotify", "python" ]
stackoverflow_0006014836_pyinotify_python.txt
Q: How to return a list containing common elements with no duplicates def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(["this","this","n","that"],["this","not","t...
How to return a list containing common elements with no duplicates
def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(["this","this","n","that"],["this","not","that","that"]) ['this', 'that'] """ result = [] for elem...
[ "Using set.intersection() because it means that it is not necessary to convert list2 to a set\ndef common_elements(list1, list2):\n return set(list1).intersection(list2)\n\nIt is more efficient to choose the shorter list to convert to a set\ndef common_elements(list1, list2):\n short_list, long_list = sorted(...
[ 6, 4, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006039009_python.txt
Q: How do I replace part of a large string in Python? I have a file with multiple lines, each having a long sequence of characters (no spaces). For example in one line: qwerrqweqweasdqweqwe*replacethistext*asdasdasd qwerrqweqweasdqweqwe*withthistext*asdasdasd The specific string I am looking for can happen any where...
How do I replace part of a large string in Python?
I have a file with multiple lines, each having a long sequence of characters (no spaces). For example in one line: qwerrqweqweasdqweqwe*replacethistext*asdasdasd qwerrqweqweasdqweqwe*withthistext*asdasdasd The specific string I am looking for can happen any where in a certain line. How would I accomplish this? Thank...
[ ">>> s = 'qwerrqweqweasdqweqwe*replacethistext*asdasdasd'\n>>> s.replace('*replacethistext*', '*withthistext*')\n'qwerrqweqweasdqweqwe*withthistext*asdasdasd'\n\n", "import string\nfor line in file:\n print string.replace(line, \"replacethistext\", \"withthistext\")\n\n", "line = \"qwerrqweqweasdqweqwe*repla...
[ 7, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006039109_python.txt
Q: How to elegantly send/receive a large C struct using Python? I have started to write a Python 3.x client application. The server application exists already and is written in C. The server provides a C header file with the definition of two structures used to send and receive data via UDP (I am using Python's socke...
How to elegantly send/receive a large C struct using Python?
I have started to write a Python 3.x client application. The server application exists already and is written in C. The server provides a C header file with the definition of two structures used to send and receive data via UDP (I am using Python's socket module). The problem is that the C structures are quite large (a...
[ "You can write a class that has member functions to pack/unpack the data to/from class attributes, using struct.pack etc.\nI would suggest looking into Construct. But I don't think it has been ported to Python 3.x yet. Construct has been on hiatus for some time, but recently been picked up by a new developer, so pe...
[ 1, 1, 1 ]
[]
[]
[ "c", "python", "python_3.x", "sockets", "struct" ]
stackoverflow_0006037555_c_python_python_3.x_sockets_struct.txt
Q: Python beginner: read elements in one file and use them to modify another file I'm an economist with no programming background. I'm trying to learn how to use python because I've been told that it is very powerful for parsing data from websites. At the moment, I'm stuck with the following code and I would be extre...
Python beginner: read elements in one file and use them to modify another file
I'm an economist with no programming background. I'm trying to learn how to use python because I've been told that it is very powerful for parsing data from websites. At the moment, I'm stuck with the following code and I would be extremely grateful for any suggestion. First of all, I wrote a code to parse the data fro...
[ "One little thing you need to fix:\nThis:\nfor city in citylist:\n outfile = open(\"%s.txt\", \"w\") % city\n# ^^^^^^\n\nShould be this:\nfor city in citylist:\n outfile = open(\"%s.txt\" % city, \"w\")\n# ^^^^^^\n\n", "If the file is in CSV format t...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "iteration", "loops", "python" ]
stackoverflow_0006038084_iteration_loops_python.txt
Q: Sequence find function? How do I find an object in a sequence satisfying a particular criterion? List comprehension and filter go through the entire list. Is the only alternative a handmade loop? mylist = [10, 2, 20, 5, 50] find(mylist, lambda x:x>10) # Returns 20 A: Here's the pattern I use: mylist = [10, 2, 20...
Sequence find function?
How do I find an object in a sequence satisfying a particular criterion? List comprehension and filter go through the entire list. Is the only alternative a handmade loop? mylist = [10, 2, 20, 5, 50] find(mylist, lambda x:x>10) # Returns 20
[ "Here's the pattern I use:\nmylist = [10, 2, 20, 5, 50]\nfound = next(i for i in mylist if predicate(i))\n\nOr, in Python 2.4/2.5, next() is a not a builtin:\nfound = (i for i in mylist if predicate(i)).next()\n\nDo note that next() raises StopIteration if no element was found. In most cases, that's probably good. ...
[ 38, 13, 5 ]
[ "Too lazy to write:\nmylist = [10, 2, 20, 5, 50]\nmax(mylist, key=lambda x: x>10)\n\n" ]
[ -1 ]
[ "find", "python", "sequence" ]
stackoverflow_0006039425_find_python_sequence.txt
Q: why can't i __init__ my custom FancyURLopener with the user & passwd I'm unable to write a custom urllib.FancyURLopener which initializes the user and passwd values in the constructor. I can get it to work fine with an empty constructor and a subsequent call to setpasswd. When I try to set the user and password ...
why can't i __init__ my custom FancyURLopener with the user & passwd
I'm unable to write a custom urllib.FancyURLopener which initializes the user and passwd values in the constructor. I can get it to work fine with an empty constructor and a subsequent call to setpasswd. When I try to set the user and password in the constructor, I get strange errors regarding a missing attribute 'te...
[ "You probably have to call the parent object's init which sets the tempcache attribute.\ndef __init__(self, user, passwd):\n self.__user = user\n self.__passwd = passwd\n urllib.FancyURLopener.__init__(self)\n\n(Call it with the proper arguments for the urllib.FancyURLopener creator)\n", "Make sure you c...
[ 5, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0006039613_python_urllib.txt
Q: uml / class design tool for Python? I am looking for an open source, easy to use tool that will help me design and get a quick sense of a single class' outline (member variables, public/private methods, what they do etc). Can you recommend on any such tools? I am looking for a tool that can work under Linux enviro...
uml / class design tool for Python?
I am looking for an open source, easy to use tool that will help me design and get a quick sense of a single class' outline (member variables, public/private methods, what they do etc). Can you recommend on any such tools? I am looking for a tool that can work under Linux environment. If possible, such a tool should so...
[ "Try Elclipse pyuml. It is open source and ran as plugin of eclipse. Therefore, it should be fine in Linux.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006039592_python.txt
Q: Pyramid and Chameleon ZPT I'm new to web development and am trying to make a simple webpage in python using Pyramid. I've run into a bit of a snag though when it comes to making template files using Chameleon. What I'm trying to do right now is very simple. The view callable returns a list of dictionaries (all dic...
Pyramid and Chameleon ZPT
I'm new to web development and am trying to make a simple webpage in python using Pyramid. I've run into a bit of a snag though when it comes to making template files using Chameleon. What I'm trying to do right now is very simple. The view callable returns a list of dictionaries (all dictionaries have same keys just d...
[ "You need to use \"tal:repeat\". If you've passed in \"people\" to the template, which is a list of dictionaries:\n<ul>\n <li tal:repeat=\"person people\">${person['firstname']} ${person['lastname']}</li>\n</ul>\n\n" ]
[ 7 ]
[]
[]
[ "chameleon", "pyramid", "python", "template_tal" ]
stackoverflow_0006037850_chameleon_pyramid_python_template_tal.txt
Q: Why Beautiful Soup cannot display all data in the tables? I tried to page scrape wikipedia a week ago. But i could not figure out why Beautiful Soup will only show some string from the table column and show "none" for other table column. NOTE: the table column all contains data. My program will extract all tabl...
Why Beautiful Soup cannot display all data in the tables?
I tried to page scrape wikipedia a week ago. But i could not figure out why Beautiful Soup will only show some string from the table column and show "none" for other table column. NOTE: the table column all contains data. My program will extract all table columns with the tag "description". I am trying to extract all...
[ "Do all the description strings come up empty? From the documentation:\n\nFor your convenience, if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]. \n\nIn this case, the description often have child nodes, i.e.: a <a> link to...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0006039603_beautifulsoup_python_web_scraping.txt
Q: Accessing Lower Triangle of a Numpy Matrix? Okay, so basically lets say i have a matrix: matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) Is it possible to get the area below the diagonal easily when working with numpy matrixs? I looked ...
Accessing Lower Triangle of a Numpy Matrix?
Okay, so basically lets say i have a matrix: matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) Is it possible to get the area below the diagonal easily when working with numpy matrixs? I looked around and could not find anything. I can do the ...
[ "You could use tril and triu. See them here:\nhttp://docs.scipy.org/doc/numpy/reference/routines.array-creation.html\n", "def tri_flat(array):\n R = array.shape[0]\n mask = np.asarray(np.invert(np.tri(R,R,dtype=bool)),dtype=float)\n x,y = mask.nonzero()\n return array[x,y]\n\nI was looking for a conve...
[ 11, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002349260_numpy_python.txt
Q: python-oauth2 with Twitter's oauth_callback I'm using Twython as my Twitter API wrapper, and oauth2 to handle authentication. I'm trying to have a use login via twitter, and then redirecting him after the oauth dance to a dynamically generated oauth_callback. This, however, appears to be impossible to do with th...
python-oauth2 with Twitter's oauth_callback
I'm using Twython as my Twitter API wrapper, and oauth2 to handle authentication. I'm trying to have a use login via twitter, and then redirecting him after the oauth dance to a dynamically generated oauth_callback. This, however, appears to be impossible to do with these libraries straight out of the box. My proble...
[ "Found the answer here\nAll you have to do is pass Twython the parameter callback_url and replace line 205 in Twython.py with \nresp, content = client.request(request_token_url, \"POST\",body=urllib.urlencode({'oauth_callback':my_callback_url}))\nNotice, if you want twitter to respect your oauth_callback argument, ...
[ 10 ]
[]
[]
[ "oauth", "python", "twitter", "twitter_oauth", "twython" ]
stackoverflow_0006038761_oauth_python_twitter_twitter_oauth_twython.txt
Q: (Py)Qt: problem with image downloading guys I want to display some images with their captions in QTextEdit. I have a dictionary with captions and corresponding URLs. The problem is when I post a request with QNetworkAccessManager and wait for a signal finished(QNetworkReply*), I get reply with image only. How can...
(Py)Qt: problem with image downloading
guys I want to display some images with their captions in QTextEdit. I have a dictionary with captions and corresponding URLs. The problem is when I post a request with QNetworkAccessManager and wait for a signal finished(QNetworkReply*), I get reply with image only. How can I determine a corresponding caption this im...
[ "Assuming a recent Qt version, the QNetworkReply::request() will give you a pointer to the QNetworkRequest that triggered this reply.\nSo you can access the information you're after with QNetworkRequest::url().\n" ]
[ 2 ]
[]
[]
[ "image_loading", "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0006038270_image_loading_pyqt_pyqt4_python_qt.txt
Q: Python Queue waiting for thread before getting next item I have a queue that always needs to be ready to process items when they are added to it. The function that runs on each item in the queue creates and starts thread to execute the operation in the background so the program can go do other things. However, th...
Python Queue waiting for thread before getting next item
I have a queue that always needs to be ready to process items when they are added to it. The function that runs on each item in the queue creates and starts thread to execute the operation in the background so the program can go do other things. However, the function I am calling on each item in the queue simply start...
[ "A fundamental issue with Python threads is that you can't just kill them - they have to agree to die.\nWhat you should do is:\n\nImplement the thread as a class\nAdd a threading.Event member which the join method clears and the thread's main loop occasionally checks. If it sees it's cleared, it returns. For this o...
[ 7 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0006039671_multithreading_python_queue.txt
Q: Fixtures with picklefield library for Django A straight forward question: Is there some easy way to write fixtures (i.e. in JSON format, but I don't care really) when using models that incorporate PickleFields? EDIT: In the end I think I'll just get rid of fixtures altogether. I'll use named *.py scripts that will...
Fixtures with picklefield library for Django
A straight forward question: Is there some easy way to write fixtures (i.e. in JSON format, but I don't care really) when using models that incorporate PickleFields? EDIT: In the end I think I'll just get rid of fixtures altogether. I'll use named *.py scripts that will create all the objects for me. I've always found ...
[ "Assuming you are using django-picklefield you can use dumpdata/loaddata just like you would with any other model. Tested it briefly and everything works fine.\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "fixtures", "pickle", "python" ]
stackoverflow_0006040125_django_django_models_fixtures_pickle_python.txt
Q: How can i get a list of all MUC 's in XMPP server using python xmpppy? I need to get a list of MUC's in a XMPP server (OpenFire). I have read about XEP 0030 and service discovery, but can not find documentation or examples about implementing it with xmpppy. A: Look in xmpp/features.py, and try code like this: fo...
How can i get a list of all MUC 's in XMPP server using python xmpppy?
I need to get a list of MUC's in a XMPP server (OpenFire). I have read about XEP 0030 and service discovery, but can not find documentation or examples about implementing it with xmpppy.
[ "Look in xmpp/features.py, and try code like this:\nfor i in discoverItems(conn, jid.getDomain()):\n (ids, features) = discoverInfo(conn, i.jid)\n if NS_MUC in features:\n print i.jid\n\n(warning: completely untested)\n" ]
[ 0 ]
[]
[]
[ "python", "service_discovery", "xmpp", "xmpppy" ]
stackoverflow_0006020866_python_service_discovery_xmpp_xmpppy.txt
Q: How to cache a webpage using web programming? I want to write a web application, which takes the snapshot of the webpage as it is now. By snapshot I don't mean photo/image/picture. Instead I want to save the webpage along with javascripts , CSS & images used in the webpage. If there are frames, I need to detect th...
How to cache a webpage using web programming?
I want to write a web application, which takes the snapshot of the webpage as it is now. By snapshot I don't mean photo/image/picture. Instead I want to save the webpage along with javascripts , CSS & images used in the webpage. If there are frames, I need to detect them too and do the same for frame source URLs. I ot...
[ "You can do this with any language that has a descent HTML parser. Hoewever, you migth also want to look at wget which has a nice \"mirror\" feature and does link rewriting for you.\n", "Python has a great library from scraping websites called scrapy. It has tons of features and great docs. Alternately you can wr...
[ 4, 3, 1, 1 ]
[]
[]
[ "asp.net", "language_agnostic", "php", "python" ]
stackoverflow_0006040260_asp.net_language_agnostic_php_python.txt
Q: Anyone have experience using the Nessi Python Network Simulator? I am working on creating a simulation for the selective-reject ARQ protocol for my networking class. I found a great network simulator, written in python called Nessi: http://jer.iict.ch/logiciels The one problem is that it seems Nessi relies on an o...
Anyone have experience using the Nessi Python Network Simulator?
I am working on creating a simulation for the selective-reject ARQ protocol for my networking class. I found a great network simulator, written in python called Nessi: http://jer.iict.ch/logiciels The one problem is that it seems Nessi relies on an older version of python (2.4) than what I currently have installed on m...
[ "It is possible to run it in Snow Leopard.\nUse a package management system like fink to install the dependencies required for this package, I think most of the dependencies can be installed using fink like(psyco, numpy, matplotlib,wxpython), you have to experiment with newer version of python to see how it goes, b...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006040160_numpy_python.txt
Q: How to render DOT file using only pos attributes I have taken an initial DOT file and modified the pos attributes of some nodes using pydot. Now I want to render an image file that shows the nodes in their new positions. The catch is, I don't want a layout program to mess with the positions! I just want to see the...
How to render DOT file using only pos attributes
I have taken an initial DOT file and modified the pos attributes of some nodes using pydot. Now I want to render an image file that shows the nodes in their new positions. The catch is, I don't want a layout program to mess with the positions! I just want to see the nodes exactly where the pos attribute indicates. I do...
[ "dot.write_png('filename.png')? Or is there something I'm missing?\nAlso, the neato command-line program has a -n option for graph files that already have layout. The program description says it is for undirected graphs, but I tried it with a digraph and it produced the correct result.\n" ]
[ 2 ]
[]
[]
[ "dot", "pydot", "python" ]
stackoverflow_0006040603_dot_pydot_python.txt
Q: Grouping integers by set membership in Python Working in Python, given a list of N sets of integers from the range range(s,n), how can I build a list that groups all these integers according to their set memberships? An example is really going to help me explain here: Example input (N=2 sets): integerRange = range...
Grouping integers by set membership in Python
Working in Python, given a list of N sets of integers from the range range(s,n), how can I build a list that groups all these integers according to their set memberships? An example is really going to help me explain here: Example input (N=2 sets): integerRange = range(0,13) input = [set([0,1,2,3,7,8,9,12]), set([0,1,2...
[ "I cringe even thinking about the efficiency of this, but it's pretty compact:\n out = [set(range(x, y))]\n for in_set in input:\n out_diff = [out_set - in_set for out_set in out]\n out_union = [out_set & in_set for out_set in out]\n out = out_diff + out_union\n\n" ]
[ 2 ]
[]
[]
[ "grouping", "integer", "list", "python", "set" ]
stackoverflow_0006040919_grouping_integer_list_python_set.txt
Q: Python ElementTree: Error Trying to implement a pretty-print I have some python xml code using ElementTree that writes a very ugly xml file. I wanted to make the xml file a bit more readable. But ElementTree has no pretty-print function. In the documentation ElementTree shows an 'indent' method. When I try t...
Python ElementTree: Error Trying to implement a pretty-print
I have some python xml code using ElementTree that writes a very ugly xml file. I wanted to make the xml file a bit more readable. But ElementTree has no pretty-print function. In the documentation ElementTree shows an 'indent' method. When I try to use this indent method, I get the following error. Traceback ...
[ "You say \ni = \"\\n\" + level*\" \"\nTypeError: object cannot be interpreted as an index\n\nbut there is nothing in that statement that looks even vaguely like an index operation. Suggestion: without changing your code in any other way, insert\nprint repr(elem), repr(level)\nbefore the above statement and edit yo...
[ 1, 1 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0006039949_elementtree_python_xml.txt
Q: How to read a header from a CSV file using python i tried the following script as per ur suggestion and i get an error import csv def main(): col_name = "\\xyz-abc\Procz(abcd)\Digital" with open('C:\\read.csv', 'rb') as inf: reader = csv.reader(inf) col_index = next(reader).index(col_name) ...
How to read a header from a CSV file using python
i tried the following script as per ur suggestion and i get an error import csv def main(): col_name = "\\xyz-abc\Procz(abcd)\Digital" with open('C:\\read.csv', 'rb') as inf: reader = csv.reader(inf) col_index = next(reader).index(col_name) highest = max(rec[col_index] for rec in reader)...
[ "Give this a go. Prevent the back-slashes being interpreted as escape characters by using a raw string\ncol_name = r\"\\\\xyz-abc\\Procz(abcd)\\Digital\"\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006041177_python.txt
Q: wx.Gauge fails to update beyond 25% in Windows, works in Linux I seem to have nothing but trouble with wxPython and cross-platform compatibility :( I have the function below. It's called when the user clicks a button, it does some work which may take a while, during which a progress gauge is shown in the status ba...
wx.Gauge fails to update beyond 25% in Windows, works in Linux
I seem to have nothing but trouble with wxPython and cross-platform compatibility :( I have the function below. It's called when the user clicks a button, it does some work which may take a while, during which a progress gauge is shown in the status bar. def Go(self, event): progress = 0 self.statbar.se...
[ "So, actually, you are blocking the GUI thread by your long running task. It may and may not run fine on some platforms and/or computers.\nimport wx\nfrom wx.lib.delayedresult import startWorker\n\nclass MainFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n super(MainFrame, self).__init__(*args, *...
[ 2 ]
[]
[]
[ "python", "windows", "wxpython" ]
stackoverflow_0006003340_python_windows_wxpython.txt
Q: what python function replace functionaly for php operator $$ hi in php im able to create variable like this $param = array('product', 'brand'); foreach ($param as $item) { $$item = $item; } so the result will be $product = 'product'; how can i achieve this in python? param = ['product', 'brand'] for item in pa...
what python function replace functionaly for php operator $$
hi in php im able to create variable like this $param = array('product', 'brand'); foreach ($param as $item) { $$item = $item; } so the result will be $product = 'product'; how can i achieve this in python? param = ['product', 'brand'] for item in param: ??? = item
[ "You can't, sanely. Use a dict instead.\nitems = {}\nfor item in param:\n items[item] = item\n\n", "param = ['product', 'brand']\nfor item in param:\n globals()[item] = item\n\nBut it's not a good idea to do so.\n" ]
[ 4, 1 ]
[]
[]
[ "php", "python", "variables" ]
stackoverflow_0006041697_php_python_variables.txt
Q: Reason for two similar codes giving different result and different approaches to this task The question is def sum_numbers_in_file(filename): """ Return the sum of the numbers in the given file (which only contains integers separated by whitespace). >>> sum_numbers_in_file("numbers.txt") 19138...
Reason for two similar codes giving different result and different approaches to this task
The question is def sum_numbers_in_file(filename): """ Return the sum of the numbers in the given file (which only contains integers separated by whitespace). >>> sum_numbers_in_file("numbers.txt") 19138 """ this is my first code: rtotal = 0 myfile = open(filename,"r") num = myfile.readline() ...
[ "Because m = f.readLine() already reads 1 line from f and then you do the operation with the rest of the lines. If you delete that statement the 2 outputs will be the same. (I think :))\n", "I'd say that m = f.readline() in the second snippet skips the first line (which contains 1000), that's why you get a wrong ...
[ 4, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006041978_python.txt
Q: Hardcoding a python datetime I have a datetime where the input is hardcoded as datetime.datetime(2008,5,5,16,20) In the same format how to get the current datetime? I am using python 2.4 A: >>> datetime.datetime.now() datetime.datetime(2011, 5, 18, 10, 59, 42, 518352) For more info, see the documentation.
Hardcoding a python datetime
I have a datetime where the input is hardcoded as datetime.datetime(2008,5,5,16,20) In the same format how to get the current datetime? I am using python 2.4
[ ">>> datetime.datetime.now()\ndatetime.datetime(2011, 5, 18, 10, 59, 42, 518352)\n\nFor more info, see the documentation.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0006042869_python.txt
Q: Remove/Replace all whitespaces from a multi-lines string, except newline characters I want to remove all whitespace characters from a multi-line string using regex. What I am looking for is something like: exp = re.compile("\s-[\r\n]") exp.sub('', text) Is there a regex that does the above. Since the text is unic...
Remove/Replace all whitespaces from a multi-lines string, except newline characters
I want to remove all whitespace characters from a multi-line string using regex. What I am looking for is something like: exp = re.compile("\s-[\r\n]") exp.sub('', text) Is there a regex that does the above. Since the text is unicode, which has a possibility of other characters that could form the \s class besides [\t...
[ "Try this double-negative character class:\n[^\\S\\r\\n]\n\nExample: http://rubular.com/r/t2Ahjs9UzF\n" ]
[ 7 ]
[]
[]
[ "newline", "python", "regex", "removing_whitespace", "whitespace" ]
stackoverflow_0006042883_newline_python_regex_removing_whitespace_whitespace.txt
Q: BioPython Alphabet Soup Biopython noob here, I'm trying to create a program that uses the Biopython package Alphabet and alphabet module IUPAC to write out the letters of the classes listed to a file called alphabetSoupOuput.txt. ThreeLetterProtein IUPACProtein unambiguous_dna ambiguous_dna ExtendedIUPACProtein E...
BioPython Alphabet Soup
Biopython noob here, I'm trying to create a program that uses the Biopython package Alphabet and alphabet module IUPAC to write out the letters of the classes listed to a file called alphabetSoupOuput.txt. ThreeLetterProtein IUPACProtein unambiguous_dna ambiguous_dna ExtendedIUPACProtein ExtendedIUPACDNA Each group o...
[ "This was answered on the BioStar StackExchange:\nhttp://biostar.stackexchange.com/questions/8370/working-with-alphabet-soup\nhttp://biostar.stackexchange.com/questions/8371/extracting-data-from-classes-in-python\n" ]
[ 1 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0006027064_bioinformatics_biopython_python.txt
Q: How to halt, kill, stop or close a PycURL request on a stream example given using Twitter Stream Im currently cURLing the twitter API stream (http://stream.twitter.com/1/statuses/sample.json), so am constantly receiving data. I wish to stop cURLing the stream once i have retrieved X number of objects from it (in t...
How to halt, kill, stop or close a PycURL request on a stream example given using Twitter Stream
Im currently cURLing the twitter API stream (http://stream.twitter.com/1/statuses/sample.json), so am constantly receiving data. I wish to stop cURLing the stream once i have retrieved X number of objects from it (in the example I give 10 as an arbitrary number). You can see how I have attempted to close the connection...
[ "You can abort the write callback by returning a number that isn't the same amount as was passed in to it. (By default it treats returning 'None' the same as returning the same number as was passed in to it)\nWhen you abort it, the entire transfer will be considered done and your perform() call returns properly.\nT...
[ 4 ]
[]
[]
[ "curl", "kill", "pycurl", "python", "stream" ]
stackoverflow_0006031921_curl_kill_pycurl_python_stream.txt
Q: Detect high amplitudes in a plot I plotted a couple of values, that represent a signal strength being weak or high. My problem is, that I want to statistically evaluate the start and end X-coordinate. My issue with that is, that these high-valued blue amplitudes within do have little sections where the Y coordina...
Detect high amplitudes in a plot
I plotted a couple of values, that represent a signal strength being weak or high. My problem is, that I want to statistically evaluate the start and end X-coordinate. My issue with that is, that these high-valued blue amplitudes within do have little sections where the Y coordinate is low (if I zoom). So using an ave...
[ "You can try to filter the signal with something like this:\nsignal: s[i]\nfiltered signal : f[i]\ndecrease coeff : c (choose a value between 0 and 1)\nf[0] = s[0]\nf[i] = max(c * f[i-1], s[i])\nThis method will introduce a bias on the end of high-amplitude areas. You will have to tune c to get the result with the...
[ 3 ]
[]
[]
[ "algorithm", "plot", "python", "search", "statistics" ]
stackoverflow_0006042855_algorithm_plot_python_search_statistics.txt
Q: Python get whole hour values between 2 datetime objects I have 2 datetime values: 'start' and end'. I'd like to return a list of all the datetimes that fall exactly on the hour between the two (inclusive). For example 'start' is 09:30 and 'end' is 14:00 (same day). The values I'd like returned are 10:00, 11:00, 12...
Python get whole hour values between 2 datetime objects
I have 2 datetime values: 'start' and end'. I'd like to return a list of all the datetimes that fall exactly on the hour between the two (inclusive). For example 'start' is 09:30 and 'end' is 14:00 (same day). The values I'd like returned are 10:00, 11:00, 12:00, 13:00, 14:00. I guess what you would do is get the next ...
[ "The easiest would be to replace the minutes and seconds of the start time with zero and then add one hour.\nYou will need a special case if the start time is exactly on the hour and you wish to include it\neg\n>>> from datetime import datetime, timedelta\n>>> start_time = datetime.now()\n>>> start_time\ndatetime.d...
[ 3, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0006043079_datetime_python.txt
Q: file i/o problem I am having trouble with a really simple problem. I'm trying to remove line breaks in a file and send the output to a new file. This is my code: infile = open('seq.txt', mode='r', encoding='utf-8') lines = infile.readlines() for line in lines: par = line.strip('\n') outfile = open('seqpar.txt...
file i/o problem
I am having trouble with a really simple problem. I'm trying to remove line breaks in a file and send the output to a new file. This is my code: infile = open('seq.txt', mode='r', encoding='utf-8') lines = infile.readlines() for line in lines: par = line.strip('\n') outfile = open('seqpar.txt', mode='w', encoding=...
[ "par = line.strip('\\n')\n\nThis isn't being stored anywhere, so every line read overwrites the previous par. Your final line in the input file is presumably blank, and that final line is all that gets written to the output file, so nothing gets written to the output - several times, once for each line in lines. Yo...
[ 3, 3, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006043537_file_io_python.txt
Q: carriage characters are lost in the resulted string when reading a file on windows When reading a txt file in windows by python, carriage characoters are lost in resulted string. c:/text.txt aaa\r\nbbb\r\nccc\r\nddd code: input = open('c:/text.txt') str = input.read() import repr for i,ch in enumerate(str): p...
carriage characters are lost in the resulted string when reading a file on windows
When reading a txt file in windows by python, carriage characoters are lost in resulted string. c:/text.txt aaa\r\nbbb\r\nccc\r\nddd code: input = open('c:/text.txt') str = input.read() import repr for i,ch in enumerate(str): print i,ord(ch),repr.repr(ch) result: 0 97 'a' 1 97 'a' 2 97 'a' 3 10 '\n' 4 98 'b' 5 98...
[ "If you open the file in text mode, Windows line endings \\r\\n are automatically substituted by standard line endings \\n. To prevent this from happening, open the file in binary mode:\ninput = open('c:/text.txt', 'rb')\n\n" ]
[ 6 ]
[]
[]
[ "io", "python", "windows" ]
stackoverflow_0006043660_io_python_windows.txt
Q: Python dict with timer entry I want to create a dict having as an entry a timer. When the entry timer times-out, a function should be called to make some treatment on that entry. e.g.: dict = [key, timer] if timer == 0 f(key, timer) Is there any method to do it. Thanks alot for your help. regards, Karim ...
Python dict with timer entry
I want to create a dict having as an entry a timer. When the entry timer times-out, a function should be called to make some treatment on that entry. e.g.: dict = [key, timer] if timer == 0 f(key, timer) Is there any method to do it. Thanks alot for your help. regards, Karim
[ "You could make all your values timer objects which will fire after a given amount of time. This will make your program rely on the threading module though. \nAlternatively, you could have a single \"timer thread\" that goes through the all the elements in the dictionary once in a while and decrements the counts. I...
[ 2, 1 ]
[]
[]
[ "dictionary", "python", "timer" ]
stackoverflow_0006043462_dictionary_python_timer.txt
Q: Python - Importing file from subpackage I have following directory structure: / package/ subpackage/ __init__.py file.py __init__.py file.py main.py /package/subpackage/__init__.py has following code: from .. import file; It imports /package/file.py as expected. /main.py has following code: from package ...
Python - Importing file from subpackage
I have following directory structure: / package/ subpackage/ __init__.py file.py __init__.py file.py main.py /package/subpackage/__init__.py has following code: from .. import file; It imports /package/file.py as expected. /main.py has following code: from package import subpackage as foo; from package.subpa...
[ "Nothing is wrong, it does exactly what you told it to:\nWhen you import package.subpackage, you're executing /package/subpackage/__init__.py. And there you do from .. import file. So file in package.subpackage is package.file. \n", "Because it imports file from .., just as your first snippet says.\n" ]
[ 6, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006044107_import_python.txt
Q: Split unicode string into 300 byte chunks without destroying characters I want to split u"an arbitrary unicode string" into chunks of say 300 bytes without destroying any characters. The strings will be written to a socket that expects utf8 using unicode_string.encode("utf8"). I don't want to destroy any character...
Split unicode string into 300 byte chunks without destroying characters
I want to split u"an arbitrary unicode string" into chunks of say 300 bytes without destroying any characters. The strings will be written to a socket that expects utf8 using unicode_string.encode("utf8"). I don't want to destroy any characters. How would I do this?
[ "UTF-8 is designed for this.\ndef split_utf8(s, n):\n \"\"\"Split UTF-8 s into chunks of maximum length n.\"\"\"\n while len(s) > n:\n k = n\n while (ord(s[k]) & 0xc0) == 0x80:\n k -= 1\n yield s[:k]\n s = s[k:]\n yield s\n\nNot tested. But you find a place to split,...
[ 11, 5, 2, 0 ]
[ "Use unicode encoding which by design have fixed length of each character, for example utf-32:\n>>> u_32 = u'Юникод'.encode('utf-32')\n>>> u_32\n'\\xff\\xfe\\x00\\x00.\\x04\\x00\\x00=\\x04\\x00\\x008\\x04\\x00\\x00:\\x04\\x00\\x00>\\x04\\x00\\x\n004\\x04\\x00\\x00'\n>>> len(u_32)\n28\n>>> len(u_32)%4\n0\n>>>\n\nAft...
[ -2 ]
[ "python", "string", "utf_8" ]
stackoverflow_0006043463_python_string_utf_8.txt
Q: PyOpenGL FPS improvement I'm trying to improve my FPS rate for an python OpenGL program. So far my approach is: self.bufferVertices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER_ARB, self.bufferVertices) glBufferData(GL_ARRAY_BUFFER_ARB, ADT.arrayByteCount(vertices), ADT.voidDataPointer(vertices), GL_...
PyOpenGL FPS improvement
I'm trying to improve my FPS rate for an python OpenGL program. So far my approach is: self.bufferVertices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER_ARB, self.bufferVertices) glBufferData(GL_ARRAY_BUFFER_ARB, ADT.arrayByteCount(vertices), ADT.voidDataPointer(vertices), GL_STATIC_DRAW_ARB) self.buf...
[ "Since you're using vertex buffer objects you're not CPU limited. So either you have a lot of geometry, or you're not actually got HW acceleration. Either way a decrease in performance switching from points to filled triangles is to be expected, due to higher fillrate demands.\n" ]
[ 0 ]
[]
[]
[ "opengl", "pyopengl", "python" ]
stackoverflow_0006044189_opengl_pyopengl_python.txt
Q: how to concatenate multiple files for stdin of Popen I'm porting a bash script to python 2.6, and want to replace some code: cat $( ls -tr xyz_`date +%F`_*.log ) | filter args > bzip2 I guess I want something similar to the "Replacing shell pipe line" example at http://docs.python.org/release/2.6/library/subproce...
how to concatenate multiple files for stdin of Popen
I'm porting a bash script to python 2.6, and want to replace some code: cat $( ls -tr xyz_`date +%F`_*.log ) | filter args > bzip2 I guess I want something similar to the "Replacing shell pipe line" example at http://docs.python.org/release/2.6/library/subprocess.html, ala... p1 = Popen(["filter", "args"], stdin=*?WHA...
[ "You can replace everything that you're doing with Python code, except for your external utility. That way your program will remain portable as long as your external util is portable. You can also consider turning the C++ program into a library and using Cython to interface with it. As Messa showed, date is replace...
[ 6, 2, 1, 1 ]
[]
[]
[ "concatenation", "pipe", "popen", "python" ]
stackoverflow_0006042210_concatenation_pipe_popen_python.txt
Q: Django forms, getting a select box from a different model Hay, say i have 2 models listing and category. How would i use djangos form framework to automatically create a select drop down box for category? class NewListingForm(forms.Form): name = forms.CharField(required=True) description = forms.CharField(...
Django forms, getting a select box from a different model
Hay, say i have 2 models listing and category. How would i use djangos form framework to automatically create a select drop down box for category? class NewListingForm(forms.Form): name = forms.CharField(required=True) description = forms.CharField(widget=forms.Textarea, required=True) category ...
[ "ModelChoiceField \ncategory = forms.ModelChoiceField(queryset=Category.objects.all(), \n empty_label=\"(Nothing)\")\n\n" ]
[ 6 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0006045021_django_forms_python.txt
Q: Django - Sort the list into 3 columns on templates My Models: Item: name desc order created_at And I got a list of items from Item like this: items = Item.objects.all().order_by('order', '-created_at') Now I send this list into templates. But I have to sort it in a pattern. For examples: <ul> ...
Django - Sort the list into 3 columns on templates
My Models: Item: name desc order created_at And I got a list of items from Item like this: items = Item.objects.all().order_by('order', '-created_at') Now I send this list into templates. But I have to sort it in a pattern. For examples: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li>...
[ "Did you check the various snippets for partitioning lists?\n", "I did this yesterday.\n{% for link in footer_links %}\n {% if forloop.first or forloop.counter0|divisibleby:\"6\" %}\n <ul>\n {% endif %}\n <li><a href='{{ link.href }}'>{{ link.title }}</a></li>\n {% if forloop.last or forloop.co...
[ 2, 2, 0 ]
[]
[]
[ "algorithm", "django", "django_templates", "django_views", "python" ]
stackoverflow_0006003799_algorithm_django_django_templates_django_views_python.txt
Q: Python Command Line input? Possible Duplicate: How do you read from stdin in python Whats the best/easiest way to get information from a command line. For example Im going to be running a bunch of shell scripts that return either: 200 SOLUTIONS_REVISION or 400 SOLUTIONS_REVISION after I run each script. I nee...
Python Command Line input?
Possible Duplicate: How do you read from stdin in python Whats the best/easiest way to get information from a command line. For example Im going to be running a bunch of shell scripts that return either: 200 SOLUTIONS_REVISION or 400 SOLUTIONS_REVISION after I run each script. I need to capture these "returned" s...
[ "If you're going to run the command from your Python script then you want to look at subprocess with its stdout arguments. If you're going to run both that script and the Python script from a separate shell script then you want to pipe from one to the next and then read from sys.stdin.\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0006045109_python.txt
Q: Python lxml wrapping elements I was wondering what the easiest way to wrap an element with another element using lxml and Python for example if I have a html snippet: <h1>The cool title</h1> <p>Something Neat</p> <table> <tr> <td>aaa</td> <td>bbb</td> </tr> </table> <p>The end of the snippet</p> And I want to wra...
Python lxml wrapping elements
I was wondering what the easiest way to wrap an element with another element using lxml and Python for example if I have a html snippet: <h1>The cool title</h1> <p>Something Neat</p> <table> <tr> <td>aaa</td> <td>bbb</td> </tr> </table> <p>The end of the snippet</p> And I want to wrap the table element with a section ...
[ "lxml's awesome for parsing well formed xml, but's not so good if you've got non-xhtml html. If that's the case then go for BeautifulSoup as suggested by systemizer. \nWith lxml, this is a fairly easy way to insert a section around all tables in the document:\nimport lxml.etree\n\nTEST=\"<html><h1>...</html>\"\n\nd...
[ 7, 0 ]
[]
[]
[ "django", "lxml", "python" ]
stackoverflow_0006038616_django_lxml_python.txt
Q: Can python freeze be made to compile 32 bit binaries on a 64 bit linux I've a number of python scripts that I am likely to need to distribute to users who may have minimal x86 linux setups and no guarantees of having python or a particular version of it. My desktop is an x86-84 architecture setup, but I am able to...
Can python freeze be made to compile 32 bit binaries on a 64 bit linux
I've a number of python scripts that I am likely to need to distribute to users who may have minimal x86 linux setups and no guarantees of having python or a particular version of it. My desktop is an x86-84 architecture setup, but I am able to cross compile 32 bit elf's with GCC. The python freeze script is currently ...
[ "Could you use something likemake CFLAGS=\"-m32\".?\n" ]
[ 1 ]
[]
[]
[ "32bit_64bit", "freeze", "linux", "python" ]
stackoverflow_0006045515_32bit_64bit_freeze_linux_python.txt
Q: Efficient way to get index of minimum value in long vector, python I have a long list of longitude values (len(Lon) = 420481), and another one of latitude values. I want to find the corresponding latitude to the minimum of the longitude. I tried: SE_Lat = [Lat[x] for x,y in enumerate(Lon) if y == min(Lon)] but th...
Efficient way to get index of minimum value in long vector, python
I have a long list of longitude values (len(Lon) = 420481), and another one of latitude values. I want to find the corresponding latitude to the minimum of the longitude. I tried: SE_Lat = [Lat[x] for x,y in enumerate(Lon) if y == min(Lon)] but this takes ages to finish. Does anyone know a more efficient way? Maybe ...
[ "May I recommend numpy?\nimport numpy\nnplats = numpy.array(lats)\nnplons = numpy.array(lons)\n\n# this part is 20x faster than using the built-in python functions\nindex = numpy.argmin(nplats)\n\nprint nplats[index], nplons[index]\n\nthis is way faster than the min(izip()) solution (~20x using my setup when using ...
[ 7, 6, 4, 0, 0, 0 ]
[]
[]
[ "indexing", "latitude_longitude", "list", "minimum", "python" ]
stackoverflow_0006044645_indexing_latitude_longitude_list_minimum_python.txt
Q: Can I install Python 2.7.1 64bit along side of an exsiting 32bit install on OS X? Short Description Is it possible to install Python 2.7.1 64/32bit from python.org on top of an existing install (from python.org) of Python 2.7.1 32bit? Background I installed the 32bit version for wxPython(2.8) support which until...
Can I install Python 2.7.1 64bit along side of an exsiting 32bit install on OS X?
Short Description Is it possible to install Python 2.7.1 64/32bit from python.org on top of an existing install (from python.org) of Python 2.7.1 32bit? Background I installed the 32bit version for wxPython(2.8) support which until now has given me zero issues. There are a few modules that I am now having difficultl...
[ "Check out http://www.macports.org/ Which provides ports of various flavors of linux/unix tools that don't appear in the default MacInstallation and duplicates those that it needs otherwise. It installs everthing in /opt/local instead of stepping on the installed base. With some manipulation of PATH and LD_LIBR...
[ 2, 0, 0 ]
[]
[]
[ "django", "homebrew", "macos", "osx_snow_leopard", "python" ]
stackoverflow_0006032440_django_homebrew_macos_osx_snow_leopard_python.txt
Q: greedy multiple knapsack (minimize/reduce number of bins) actually, I already have a partial answer for this question, but I'm wondering if this small piece of greedy code can be generalized to something closer to the optimal solution. how I met this problem (not relevant for problem itself, but maybe interesting...
greedy multiple knapsack (minimize/reduce number of bins)
actually, I already have a partial answer for this question, but I'm wondering if this small piece of greedy code can be generalized to something closer to the optimal solution. how I met this problem (not relevant for problem itself, but maybe interesting): I receive a large collection of objects (it's a set of profi...
[ "I like the idea of your colleague to add some noise data, But may be it's better to make a few swaps in ordered after you call ordered = sorted(orig)?\n" ]
[ 0 ]
[]
[]
[ "greedy", "knapsack_problem", "python" ]
stackoverflow_0006044859_greedy_knapsack_problem_python.txt
Q: how do I sign sha1 signature in Django? I have not really dug in deep into django and signatures I am trying to create a signature based on a given requirements i = my username, v = expiration, and s = signature i: MYUSERNAME v: UNIX TIMESTAMP + 2 hours a: MY_API_KEY s: SHA1 SIGNATURE that is ("i=MYUSERNAME&v=(UNI...
how do I sign sha1 signature in Django?
I have not really dug in deep into django and signatures I am trying to create a signature based on a given requirements i = my username, v = expiration, and s = signature i: MYUSERNAME v: UNIX TIMESTAMP + 2 hours a: MY_API_KEY s: SHA1 SIGNATURE that is ("i=MYUSERNAME&v=(UNIX_TIMESTAMP + API_KEY)") What I have so far. ...
[ "The only thing I can see from your description is that you are not grabbing the hex digest at the end, which I can only assume is what the server expects. Send this value instead:\nhashed = signature.hexdigest()\nOtherwise please post the documentation for this web service and make sure you are honoring case requ...
[ 0 ]
[]
[]
[ "digital_signature", "django", "python", "sha1" ]
stackoverflow_0006045594_digital_signature_django_python_sha1.txt
Q: Open file with pyQt There is a button. When it is clicked, file C:\file.txt should be opened with default text editor (as if it is double clicked). Is it possible in pyQt? Button is pressed -> file is opened. All I can google is just dialogs, but I don't need them. file = 'C:\file.txt' widget.connect(button, QtCor...
Open file with pyQt
There is a button. When it is clicked, file C:\file.txt should be opened with default text editor (as if it is double clicked). Is it possible in pyQt? Button is pressed -> file is opened. All I can google is just dialogs, but I don't need them. file = 'C:\file.txt' widget.connect(button, QtCore.SIGNAL('clicked()'), ??...
[ "def openFile(file):\n if sys.platform == 'linux2':\n subprocess.call([\"xdg-open\", file])\n else:\n os.startfile(file)\n\nAnd edit your 2nd line to:\nwidget.connect(button, QtCore.SIGNAL('clicked()'), openFile(file))\n\nCode for opening file copied from How to open a file with the standard app...
[ 4 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006045679_pyqt_python.txt
Q: Implementing my own higher level test scripting language I've inherited a bunch of test scripts which look something like this: // make connection on standard port (FD) ot 11 02 00 0F FD // wait for ACK in 12 ackValue // wait for connection confirmation in 13 ackValue 09 88 //send 5 bytes of arbitary data ot 21 a...
Implementing my own higher level test scripting language
I've inherited a bunch of test scripts which look something like this: // make connection on standard port (FD) ot 11 02 00 0F FD // wait for ACK in 12 ackValue // wait for connection confirmation in 13 ackValue 09 88 //send 5 bytes of arbitary data ot 21 ackValue 05 01 02 03 04 05 And so on. I would like to write m...
[ "You don't need any special parsers for such simple tests. Just use Python. A simple solution could start like this:\nclass TestGen(object):\n\n def __init__(self, filename):\n self._filename = filename\n\n def __enter__(self):\n self._file = open(self._filename, 'w')\n return self\n\n ...
[ 9, 3, 2 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0006045869_parsing_python.txt
Q: Connecting QPushButton's sizes I have a grid-like view with QPushButtons. The buttons content isn't static, so the column sizes expands dynamically. And I want same column size for each column for aesthetical reasons. Now I'm using an adjust_sizes function after showing the widget, because I noticed If I call it ...
Connecting QPushButton's sizes
I have a grid-like view with QPushButtons. The buttons content isn't static, so the column sizes expands dynamically. And I want same column size for each column for aesthetical reasons. Now I'm using an adjust_sizes function after showing the widget, because I noticed If I call it before showing the widget, nothing c...
[ "My apologies if this isn't really an answer (it's a bit long for comments), but I'm wondering if the version of PyQt you're using might be part of the cause. I'm using 4.8.3 (I think), and when I build a dialog this way using QGridLayout the columns, by default, are all equal sizes. Here is a (very, very, very c...
[ 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006034605_pyqt_python.txt
Q: Python memory serialisation I was wondering whether someone might know the answer to the following. I'm using Python to build a character-based suffix tree. There are over 11 million nodes in the tree which fits in to approximately 3GB of memory. This was down from 7GB by using the slot class method rather than ...
Python memory serialisation
I was wondering whether someone might know the answer to the following. I'm using Python to build a character-based suffix tree. There are over 11 million nodes in the tree which fits in to approximately 3GB of memory. This was down from 7GB by using the slot class method rather than the Dict method. When I serialise...
[ "If you try to pickle an empty list, you get:\n>>> s = StringIO()\n>>> pickle.dump([], s)\n>>> s.getvalue()\n'(l.'\n\nand similarly '(d.' for an empty dict. That's three bytes. The in-memory representation of a list, however, contains\n\na reference count\na type ID, in turn containing a pointer to the type name an...
[ 9, 3 ]
[]
[]
[ "class", "memory_management", "pickle", "python", "serialization" ]
stackoverflow_0006041395_class_memory_management_pickle_python_serialization.txt
Q: PyQt running slot from the start Why this script opens file as soon as it is launched? No program is showed. It is supposed to open file when the button is pressed. If I remove widget.connect, then everything is ok. But the button does not working. import sys import os from PyQt4 import QtGui, QtCore # open fil...
PyQt running slot from the start
Why this script opens file as soon as it is launched? No program is showed. It is supposed to open file when the button is pressed. If I remove widget.connect, then everything is ok. But the button does not working. import sys import os from PyQt4 import QtGui, QtCore # open file with os default program def openFile...
[ "In your connect line openFile('C:\\file.txt') is a call to the function openFile. When you connect a signal to a slot you're supposed to pass a callable, e.g. a function but you're passing the result of openFile.\nAs you want to hard code the parameter to openFile you need to create a new function which takes no a...
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006046362_pyqt_python.txt
Q: Counting occurrences in a Python list I have a list of integers; for example: l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2] I am trying to make a list of the three elements in l with the highest number of occurrences, in descending order of frequency. So in this case I want the list [1, 4, 2], because 1 occurs the most in l...
Counting occurrences in a Python list
I have a list of integers; for example: l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2] I am trying to make a list of the three elements in l with the highest number of occurrences, in descending order of frequency. So in this case I want the list [1, 4, 2], because 1 occurs the most in l (four times), 4 is next with three instanc...
[ "Use a collections.Counter:\nimport collections\nl= [1 ,2 ,3 ,4,4,4 , 1 ,1 ,1 ,2]\n\nx=collections.Counter(l)\nprint(x.most_common())\n# [(1, 4), (4, 3), (2, 2), (3, 1)]\n\nprint([elt for elt,count in x.most_common(3)])\n# [1, 4, 2]\n\ncollections.Counter was introduced in Python 2.7. If you are using an older ver...
[ 19, 8, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006046387_python.txt
Q: Open file on separate drive in python I have an annoying problem in python 2.7 on windows XP. I've got some code that collects a file name off the command line with the argparse library. I then try and open said file. Normally, this works fine, and if you pass in a full path name it successfully opens that too. Ho...
Open file on separate drive in python
I have an annoying problem in python 2.7 on windows XP. I've got some code that collects a file name off the command line with the argparse library. I then try and open said file. Normally, this works fine, and if you pass in a full path name it successfully opens that too. However, if the path uses a drive letter othe...
[ "I think you may want to try two slashes instead of 1. Also I think this SO Question might be helpful to you.\nTwo slashes like this C:\\>schema_split.py \"I:\\\\path\\to\\file\"\nHope this is helpful.\n", "You can use the os.path.normpath to normalize path and maybe check if the path is valid.\n", "You are as...
[ 4, 3, 3 ]
[]
[]
[ "file_io", "python", "windows" ]
stackoverflow_0006046038_file_io_python_windows.txt
Q: python dictionary values sorting I have 2 dictionaries, dict1 and dict2 which contain the same keys, but different values for the keys. What I want to do is for each dictionary, sort the values from largest to smallest, and then give each value a rank 1-N, 1 being the largest value. From here, I want to get the ...
python dictionary values sorting
I have 2 dictionaries, dict1 and dict2 which contain the same keys, but different values for the keys. What I want to do is for each dictionary, sort the values from largest to smallest, and then give each value a rank 1-N, 1 being the largest value. From here, I want to get the difference of the ranks for the values...
[ "A simple solution for small dicts is\ndict1 = {\"a\":0.6, \"b\":0.3, \"c\":0.9, \"d\":1.2, \"e\":0.2}\ndict2 = {\"a\":1.4, \"b\":7.7, \"c\":9.0, \"d\":2.5, \"e\":2.0}\nk1 = sorted(dict1, key=dict1.get)\nk2 = sorted(dict2, key=dict2.get)\ndiffs = dict((k, k2.index(k) - k1.index(k)) for k in dict1)\n\nA more efficie...
[ 8, 6, 2, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0006046049_dictionary_python_sorting.txt
Q: looking up a m2m relationship Given the model below, How can i find objects who's "days" field has has today. Basically, show me the jobs who have a certain day set. 'Wed' for example. Any help would be greatly appreciated. model.py class Day(models.Model): day = models.CharField(max_length=3) def __unic...
looking up a m2m relationship
Given the model below, How can i find objects who's "days" field has has today. Basically, show me the jobs who have a certain day set. 'Wed' for example. Any help would be greatly appreciated. model.py class Day(models.Model): day = models.CharField(max_length=3) def __unicode__(self): return "%s"%(s...
[ "Job.objects.filter(days=DAY) is correct.\n" ]
[ 2 ]
[]
[]
[ "django", "filter", "python" ]
stackoverflow_0006046817_django_filter_python.txt
Q: Explain example pipeline from Python subprocess module Section 17.1.4.2: Replacing shell pipeline of the python subprocess module says to replace output=`dmesg | grep hda` with p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a ...
Explain example pipeline from Python subprocess module
Section 17.1.4.2: Replacing shell pipeline of the python subprocess module says to replace output=`dmesg | grep hda` with p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] The comme...
[ "You are closing p1.stdout in the parent process, thus leaving dmesg as the only process with that file descriptor open. If you didn't do this, even when dmesg closed its stdout, you would still have it open, and a SIGPIPE would not be generated. (The OS basically keeps a reference count, and generates SIGPIPE wh...
[ 11 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006046779_python_subprocess.txt
Q: pyCharm Django error I am using PyCharm. And in models.py I have such model: class TaricCode(models.Model): code = models.IntegerField(primary_key=True, verbose_name="Code") description = models.CharField(max_length=256, blank=True, verbose_name="Description") But in views.py when I write: tc = TaricCode...
pyCharm Django error
I am using PyCharm. And in models.py I have such model: class TaricCode(models.Model): code = models.IntegerField(primary_key=True, verbose_name="Code") description = models.CharField(max_length=256, blank=True, verbose_name="Description") But in views.py when I write: tc = TaricCode.objects.all() objects is...
[ "Make sure that you have line\nfrom django.db import models\n\nAnd that Django package is actually in your Python path as set in PyCharm.\n" ]
[ 4 ]
[]
[]
[ "django", "pycharm", "python" ]
stackoverflow_0006046825_django_pycharm_python.txt
Q: "Unexpected indent" when trying to call os.system Pretty simple question (probably) but I guess since im new to python im not super sure about how os.system works. Basically I have a for loop (thanks to some help from SO) that goes through all my directories and runs a shell script (like 120 something different sh...
"Unexpected indent" when trying to call os.system
Pretty simple question (probably) but I guess since im new to python im not super sure about how os.system works. Basically I have a for loop (thanks to some help from SO) that goes through all my directories and runs a shell script (like 120 something different shell scripts). import os root = '/foo/' for directory,...
[ "You're mixing up your indentation (spaces vs. tabs). Use python -tt to verify.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006047055_python.txt
Q: python: How to enumerate local windows group membership I need to test group membership of specified accounts. Given Account 'X', is it a member of groups 'A' and 'B' These are local windows accounts on a 2003 server, not a DC and it does not connect to a DC. Here is the answer I formed after being pointed in the ...
python: How to enumerate local windows group membership
I need to test group membership of specified accounts. Given Account 'X', is it a member of groups 'A' and 'B' These are local windows accounts on a 2003 server, not a DC and it does not connect to a DC. Here is the answer I formed after being pointed in the correct direction import win32net import platform import getp...
[ "You need to use Python Win32 Extensions to interact with Windows. I think some of the methods in win32net module would help you to get the information you need.\n" ]
[ 2 ]
[]
[]
[ "membership", "python", "user_accounts", "windows" ]
stackoverflow_0006046696_membership_python_user_accounts_windows.txt
Q: AuthSub problems I've been combing through google's authentication documentation, and am having trouble with Auth Sub. The following code is main.py of the beginning of a Google AppEngine app. #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.ap...
AuthSub problems
I've been combing through google's authentication documentation, and am having trouble with Auth Sub. The following code is main.py of the beginning of a Google AppEngine app. #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp imp...
[ "I recently updated this article to provide better documentation on how to use GData and OAuth on App Engine:\nhttp://code.google.com/appengine/articles/python/retrieving_gdata_feeds.html\nYou should be able to use the sample code there, and replace DocClient with CalendarService.\n" ]
[ 0 ]
[]
[]
[ "authsub", "gdata_python_client", "google_app_engine", "python" ]
stackoverflow_0004713089_authsub_gdata_python_client_google_app_engine_python.txt
Q: To/From Paging in Python All, This may be a pretty novice question but I am stuck on how to do this in Python. What I need to do is, set the to and from params when requesting data from Panaramio. http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=100&minx=-180&miny=-90&maxx=180&maxy=90&size=medi...
To/From Paging in Python
All, This may be a pretty novice question but I am stuck on how to do this in Python. What I need to do is, set the to and from params when requesting data from Panaramio. http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=100&minx=-180&miny=-90&maxx=180&maxy=90&size=medium&mapfilter=true Panoramio on...
[ "for number in range(1, 301, 100):\n low = number\n high = low + 100\n\n" ]
[ 0 ]
[]
[]
[ "iteration", "paging", "panoramio", "python" ]
stackoverflow_0006046789_iteration_paging_panoramio_python.txt
Q: How to create complex data-bindings for webpage boxes? I'm building a database query wizard on Google App Engine. For the browser front-end, I need some dynamic data-binding between boxes/menus on the webpage. Specifically, when SelectBoxA is changed, a bunch of other Selectboxes should be updated (basically men...
How to create complex data-bindings for webpage boxes?
I'm building a database query wizard on Google App Engine. For the browser front-end, I need some dynamic data-binding between boxes/menus on the webpage. Specifically, when SelectBoxA is changed, a bunch of other Selectboxes should be updated (basically menus of attributes from the selected table. schema stored in an...
[ "Did you take a look at ProtoRPC ?\nIn the announcement blob post they show how to use it with jQuery.\n" ]
[ 0 ]
[]
[]
[ "ajax", "data_binding", "google_app_engine", "javascript", "python" ]
stackoverflow_0004739874_ajax_data_binding_google_app_engine_javascript_python.txt
Q: Django manytomany signals? Let's say I have such model class Event(models.Model) users_count = models.IntegerField(default=0) users = models.ManyToManyField(User) How would you recommend to update users_count value if Event add/delete some users ? A: If possible in your case, you could introduce Partici...
Django manytomany signals?
Let's say I have such model class Event(models.Model) users_count = models.IntegerField(default=0) users = models.ManyToManyField(User) How would you recommend to update users_count value if Event add/delete some users ?
[ "If possible in your case, you could introduce Participation model which would join Event and User:\nclass Participation(models.Model):\n user = models.ForeignKey(User)\n event = models.ForeignKey(Event)\n\nclass Event(models.Model):\n users = models.ManyToManyField(User, through='Participation')\n\nAnd ha...
[ 8, 4, 2 ]
[]
[]
[ "django", "django_models", "django_signals", "python" ]
stackoverflow_0001958540_django_django_models_django_signals_python.txt
Q: Pip: Specifying minor version In my requirements.txt file I want to specify that my app needs Django version 1.3.x. That is, either 1.3.0, or 1.3.1, or 1.3.2, etc. (When these come out.) But not 1.4, when it comes out. What's the syntax for this? A: According to Ian Bicking: Django>=1.3,<1.4 However, it's appar...
Pip: Specifying minor version
In my requirements.txt file I want to specify that my app needs Django version 1.3.x. That is, either 1.3.0, or 1.3.1, or 1.3.2, etc. (When these come out.) But not 1.4, when it comes out. What's the syntax for this?
[ "According to Ian Bicking:\nDjango>=1.3,<1.4\n\nHowever, it's apparently safer to do:\nDjango>=1.3,<1.3.99\n\n" ]
[ 53 ]
[]
[]
[ "distribute", "pip", "python" ]
stackoverflow_0006047670_distribute_pip_python.txt
Q: Python equivalent of Ruby blocks for Sinatra-style URL routing Is there a way of recreating Sinatra's URL routing in Python? And are there any reasons why this might not be desirable? From Sinatra: get '/' do 'Hello world!' end From Flask (using decorators for routing): @app.route("/") def hello(): return...
Python equivalent of Ruby blocks for Sinatra-style URL routing
Is there a way of recreating Sinatra's URL routing in Python? And are there any reasons why this might not be desirable? From Sinatra: get '/' do 'Hello world!' end From Flask (using decorators for routing): @app.route("/") def hello(): return "Hello World!" Sinatra achieves this succinctness through Ruby blo...
[ "As you said, Python doesn't have something like ruby blocks. Decorators are the commonly used solution for routing. The other way would be creating a list/dict containing the routes but since you seem to want the route definitions next to the underlying code, the decorator way is what you'll want to use.\n", "An...
[ 3, 0, 0 ]
[]
[]
[ "block", "flask", "python", "ruby", "sinatra" ]
stackoverflow_0005089560_block_flask_python_ruby_sinatra.txt