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: Handling spreadsheet data through the clipboard in GTK I'm using a GtkSheet widget in PyGTK to power my application's spreadsheet, and it gives me an API to pull and push data out of cells. (I looked at using GtkTreeView, but it seemed to be too much work) What I don't understand is how to intercept paste requests...
Handling spreadsheet data through the clipboard in GTK
I'm using a GtkSheet widget in PyGTK to power my application's spreadsheet, and it gives me an API to pull and push data out of cells. (I looked at using GtkTreeView, but it seemed to be too much work) What I don't understand is how to intercept paste requests (via ie. CTRL+V) so that I can process them rather than pas...
[ "To catch the paste event, you need to first create a custom entry class (PastableEntry in this example) that inherits from gtksheet.ItemEntry. During its initialisation, we connect to the paste-clipboard signal to trap paste events:\nclass PastableEntry(gtksheet.ItemEntry):\n def __init__(self):\n gtkshe...
[ 7 ]
[]
[]
[ "clipboard", "gtk", "linux", "pygtk", "python" ]
stackoverflow_0002022594_clipboard_gtk_linux_pygtk_python.txt
Q: In what version of Python was set initialisation syntax added I only just noticed this feature today! s={1,2,3} #Set initialisation t={x for x in s if x!=3} #Set comprehension t=={1,2} What version is it in? I also noticed that it has set comprehension. Was this added in the same version? Resources Sets in Pyth...
In what version of Python was set initialisation syntax added
I only just noticed this feature today! s={1,2,3} #Set initialisation t={x for x in s if x!=3} #Set comprehension t=={1,2} What version is it in? I also noticed that it has set comprehension. Was this added in the same version? Resources Sets in Python 2.4 Docs What's new in Python 3.0
[ "The sets module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the sets module has been deprecated.)\nSo you can use sets as far back as 2.3, as long as you\nimport sets\n\nBut you will get a DeprecationWarning if you try that i...
[ 11, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001611625_python.txt
Q: All members package/module defines? How can I know which members module/package defines? By defining I mean: somemodule.py import os # <-- Not defined in this module from os.path import sep # <-- Not defined in this module I_AM_ATTRIBUTE = None # <-- Is defined in this module class SomeClass(object): # <-- Is de...
All members package/module defines?
How can I know which members module/package defines? By defining I mean: somemodule.py import os # <-- Not defined in this module from os.path import sep # <-- Not defined in this module I_AM_ATTRIBUTE = None # <-- Is defined in this module class SomeClass(object): # <-- Is defined also... pass So I need a some ...
[ "There is no way to do this. This is because simple attributes (like I_AM_ATTRIBUTE in your example) are simply values stored in the module's dictionary. When they are copied to another module, they are placed in that module's dictionary as well, and there is no way to tell which was the original location. You can ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002055961_python.txt
Q: how to perform ssh and scp equivalent function in python code I want to login in different machine in the network and copy a file from that machine to my machine.I want to do this using python.Any idea how can i do this .I have python 2.5 a nd ubuntu 8.10 A: Use subprocess and call scp directly. This has the adv...
how to perform ssh and scp equivalent function in python code
I want to login in different machine in the network and copy a file from that machine to my machine.I want to do this using python.Any idea how can i do this .I have python 2.5 a nd ubuntu 8.10
[ "Use subprocess and call scp directly. This has the advantage of using your ssh settings, private keys and agent.\nLook into Fabric if you need a more structured framework for doing local and remote operations.\n", "get paramiko or similar libraries.\n" ]
[ 5, 0 ]
[]
[]
[ "automation", "python", "scp", "ssh" ]
stackoverflow_0002056282_automation_python_scp_ssh.txt
Q: Help with Python strings I have a program which reads commands from a text file for example, the command syntax will be as follows and is a string 'index command param1 param2 param3' The number of parameters is variable from 0 up to 3 index is an integer command is a string all the params are integers I would lik...
Help with Python strings
I have a program which reads commands from a text file for example, the command syntax will be as follows and is a string 'index command param1 param2 param3' The number of parameters is variable from 0 up to 3 index is an integer command is a string all the params are integers I would like to split them so that I hav...
[ "Not sure if it's the best way, but here's one way:\nlines = open('file.txt')\nfor line in lines:\n as_list = line.split()\n result = [as_list[0], as_list[1], as_list[2:]]\n print result\n\nResult will contain\n['index', 'command', ['param1', 'param2', 'param3']]\n\n", "def add_command(index, command, *para...
[ 8, 5, 2, 1, 1, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002055738_python_string.txt
Q: How to protect Python source code? Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that? A: Use the freeze ...
How to protect Python source code?
Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that?
[ "Use the freeze tool, which is included in the Python source tree as Tools/freeze. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules. \nNote that freeze requires a C compiler.\nOther utilities:\n1- PyI...
[ 12, 5, 5, 2, 2 ]
[]
[]
[ "bytecode", "c", "compilation", "python" ]
stackoverflow_0002055355_bytecode_c_compilation_python.txt
Q: Recover process with subprocess.Popen? I have a python program that uses subprocess.Popen to launch another process (python process or whatever), and after launching it I save the child's PID to a file. Let's suppose that suddenly the parent process dies (because of an exception or whatever). Is there any way to a...
Recover process with subprocess.Popen?
I have a python program that uses subprocess.Popen to launch another process (python process or whatever), and after launching it I save the child's PID to a file. Let's suppose that suddenly the parent process dies (because of an exception or whatever). Is there any way to access again to the object returned by Popen?...
[ "The Popen object is effectively just a wrapper for the child processes PID, stdin, stdout, and stderr, plus some convenience functions for using those.\nSo the question is why do you need access to the Popen object? Do you want to communicate with the child, terminate it, or check whether it's still running?\nIn a...
[ 3, 1, 0 ]
[]
[]
[ "popen", "python" ]
stackoverflow_0002056594_popen_python.txt
Q: How to revert to content of a Dijit text box when browser back-button is clicked? I am using a Dojo Textarea Dijit to input and submit text (to be processed). I found that after submiting, if a browser back-button is pressed (IE8, Firefox) unlike regular HTML Textarea, I return to the input screen, but the Textare...
How to revert to content of a Dijit text box when browser back-button is clicked?
I am using a Dojo Textarea Dijit to input and submit text (to be processed). I found that after submiting, if a browser back-button is pressed (IE8, Firefox) unlike regular HTML Textarea, I return to the input screen, but the Textarea is EMPTY. What I would like to happen is that after back-button is pressed, I would r...
[ "You may consider using dojo.back module: http://dojocampus.org/content/2009/05/17/using-dojo-back-button-and-bookmarks to store the page's state and handle back / forward events. However not sure if it's worth powder and shot in your case. :)\n" ]
[ 2 ]
[]
[]
[ "back_button", "dojo", "python", "textarea" ]
stackoverflow_0001994581_back_button_dojo_python_textarea.txt
Q: os.makedirs doesn't understand "~" in my path I have a little problem with ~ in my paths. This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory. my_dir = "~/some_dir" if not os.path.exists(my_dir): os.makedirs(my_dir) Note this...
os.makedirs doesn't understand "~" in my path
I have a little problem with ~ in my paths. This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory. my_dir = "~/some_dir" if not os.path.exists(my_dir): os.makedirs(my_dir) Note this is on a Linux-based system.
[ "You need to expand the tilde manually:\nmy_dir = os.path.expanduser('~/some_dir')\n\n", "The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.\nIn Python, this feature is implemented by os.path.expanduser:...
[ 348, 84, 15 ]
[]
[]
[ "path", "python" ]
stackoverflow_0002057045_path_python.txt
Q: What is the Java Equivalent of Python's property()? I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Proper...
What is the Java Equivalent of Python's property()?
I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Property" class, but this doesn't appear to be the same thing. ...
[ "There's no such facility built into Java language. You have to write all the getters and setters explicitly by yourself. IDEs like Eclipse can generate this boilerplate code for you though.\nFor example :\nclass Point{\n private int x, y;\n\n public Point(int x, int y){\n this.x = x;\n this.y = y;\n }\n\n...
[ 9, 4, 2, 1, 0 ]
[ "Actually you may simulate this behavior in Java.\nWARNING: ugly solution below\nYou can write a method in an utility class like the code below:\npublic Object getProperty(String property, Object obj) {\n if (obj != null && property != null) {\n Field field = obj.getClass().getDeclaredField(property);\n ...
[ -1 ]
[ "java", "properties", "python" ]
stackoverflow_0002056752_java_properties_python.txt
Q: How to delete an inner element from a nested list in Python? I have created a list a = [[3, 4], [5], [6, 7, 8]] I want to delete 3 from this list. What is the command for this? A: lots of possible ways >>> mylist = [[3,4],[5],[6,7,8]] >>> mylist[0] = [4] >>> mylist [[4], [5], [6, 7, 8]] >>> mylist = [[3,4],[5],...
How to delete an inner element from a nested list in Python?
I have created a list a = [[3, 4], [5], [6, 7, 8]] I want to delete 3 from this list. What is the command for this?
[ "lots of possible ways\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> mylist[0] = [4]\n>>> mylist\n[[4], [5], [6, 7, 8]]\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> del mylist[0][0]\n>>> mylist\n[[4], [5], [6, 7, 8]]\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> mylist[0].remove(3)\n>>> mylist\n[[4], [5], [6, 7, 8]]\n\nTake your pick ...
[ 11, 5, 2, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002056341_python.txt
Q: Build, syntax-check, parse and evaluate a query I am building a query in a textarea with different conditions selected from the html controls. Also users are open to do modification to it. Client side: For the below list of condition: a(1, 3) > 20 b(4, 5) < 90 c(3, 0) = 80 I form a query: a(1, 3) > 20 and b(4, 5)...
Build, syntax-check, parse and evaluate a query
I am building a query in a textarea with different conditions selected from the html controls. Also users are open to do modification to it. Client side: For the below list of condition: a(1, 3) > 20 b(4, 5) < 90 c(3, 0) = 80 I form a query: a(1, 3) > 20 and b(4, 5) < 90 or c(3, 0) = 80 On the server side this has to...
[ "PLY has a simple expression example that will get you most of the way there.\n" ]
[ 4 ]
[]
[]
[ "html", "javascript", "jquery", "python" ]
stackoverflow_0002057820_html_javascript_jquery_python.txt
Q: Merging two event loops (Cherrypy and Wxpython) Okay, I have an application written with cherrypy, and I want to build a wxpython gui for it. The problem is that both modules use a close loop for event handling, which (I assume) means while one is running the other will be locked. I asked for some advice and it wa...
Merging two event loops (Cherrypy and Wxpython)
Okay, I have an application written with cherrypy, and I want to build a wxpython gui for it. The problem is that both modules use a close loop for event handling, which (I assume) means while one is running the other will be locked. I asked for some advice and it was suggested that I merge the two event loops rather t...
[ "You already asked the same question here: cherrypy and wxpython, and I gave you the best response you're going to find anywhere there, which was voted up and you approved, apparently. Why are you asking again?\n", "In the case of cherrypy, you have the source. Look in the code what quickloop() does and then try ...
[ 6, 0 ]
[]
[]
[ "cherrypy", "python", "wxpython" ]
stackoverflow_0002055193_cherrypy_python_wxpython.txt
Q: What are the major differences in object models of dynamic languages like Smalltalk, Ruby and Python I dived into understanding the Ruby object model in the last weeks, and although so far was only a user of the fruits of ruby's and python's object in the past, I became curious how these things might differ in oth...
What are the major differences in object models of dynamic languages like Smalltalk, Ruby and Python
I dived into understanding the Ruby object model in the last weeks, and although so far was only a user of the fruits of ruby's and python's object in the past, I became curious how these things might differ in other languages. Years ago I touched smalltalk's squeak. Smalltalk is often figuring as a referential object ...
[ "The main difference between Python and Smalltalk that I remember is the way attribute privacy is handled. In Smalltalk I defined attributes and had to generate all the accessors instantly (fortunately Dolphin Smalltalk did this) and the use them. On the other hand in Python everything can be accessed, even attribu...
[ 2, 2 ]
[]
[]
[ "comparison", "oop", "python", "ruby", "smalltalk" ]
stackoverflow_0002055966_comparison_oop_python_ruby_smalltalk.txt
Q: Some tables mixed together I have 2 different tables in my database. They have some variables common and some different. For example: Table1: ID Date Name Address Fax Table2: ID Date Name e-mail Telephone number I want to display data together sorted by date & ID but from both tables. For example, firs...
Some tables mixed together
I have 2 different tables in my database. They have some variables common and some different. For example: Table1: ID Date Name Address Fax Table2: ID Date Name e-mail Telephone number I want to display data together sorted by date & ID but from both tables. For example, first displayed will be the newest r...
[ "Select entries from both models, than put them into a single list and sort them. Like that:\nresult = (list(first_query) + list(second_query))\nresult.sort(cmp=foo)\nreturn result\n\nwhere foo is a function, which is used to compare two elements:\ndef foo(a, b):\n if a.date > b.date:\n return 1\n if a.date < ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002058197_django_python.txt
Q: Django custom auth backend not recognized on Apache I'm trying to deploy my Django application to an Apache2 based server with mod_python. I've set the handlers right and made the configuration to make mod_python work with my project. My project implements a custom auth backend to connect my users to twitter, and ...
Django custom auth backend not recognized on Apache
I'm trying to deploy my Django application to an Apache2 based server with mod_python. I've set the handlers right and made the configuration to make mod_python work with my project. My project implements a custom auth backend to connect my users to twitter, and my backend implementation is on: myproject |- backends/ ...
[ "The problem is that python cannot find the module twitteroauth. What is the name of the file TwitterBackend is in? Also make sure that there is a __init__.py file in backends to mark it as a package.\nedit:\nWhat happens if you run the shell\npython manage.py shell\n\nand try to import it there?\nfrom myproject.ba...
[ 2, 2, 1 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0002056384_django_mod_python_python.txt
Q: Dynamic direct_to_template In my webapp, there are a lot of errors or other messages that just show a template that is very close to the URL. At the moment, I have half a dozen static mappers like this: (r'^/message/foo/$', 'direct_to_template', {'template': 'message/foo.html'}), (r'^/message/bar/$', 'direct_to_te...
Dynamic direct_to_template
In my webapp, there are a lot of errors or other messages that just show a template that is very close to the URL. At the moment, I have half a dozen static mappers like this: (r'^/message/foo/$', 'direct_to_template', {'template': 'message/foo.html'}), (r'^/message/bar/$', 'direct_to_template', {'template': 'message/b...
[ "This is pretty easy. Do it like this:\n(r'^/message/(?<name>\\d+)/$', 'your_app.views.direct_to_template')\n\nand:\ndef direct_to_template(name):\n return render_to_response('message/%s.html' % name)\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_templates", "django_urls", "python", "regex" ]
stackoverflow_0002058261_django_django_templates_django_urls_python_regex.txt
Q: Awk, bash or python for converting a regular file? I have a text file with lots of lines and with this structure: [('name_1a', 'name_1b', value_1), ('name_2a', 'name_2b', value_2), ..... ..... ('name_XXXa', 'name_XXXb', value_XXX)] I would like to convert it to: name_1a, name_1b, value_1 name_2a, name_2b, value_2...
Awk, bash or python for converting a regular file?
I have a text file with lots of lines and with this structure: [('name_1a', 'name_1b', value_1), ('name_2a', 'name_2b', value_2), ..... ..... ('name_XXXa', 'name_XXXb', value_XXX)] I would like to convert it to: name_1a, name_1b, value_1 name_2a, name_2b, value_2 ...... name_XXXa, name_XXXb, value_XXX I wonder what w...
[ "Tried evaluating it python? Looks like a list of tuples to me.\neval(your_string)\n\nNote, it's massively unsafe! If there's code in there to delete your hard disk, evaluating it will run that code!\n", "I would like to use Python:\nlines = open('filename.txt','r').readlines()\nn = len(lines) # n % 3 == 0\nfor i...
[ 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "awk", "bash", "python" ]
stackoverflow_0002058339_awk_bash_python.txt
Q: Python’s ftplib STOR reliable? I'm using this code to upload myfile.txt from my windows machine to a ftp server. after the upoad the script deletes the file on my local machine (I'm not deleting it on the ftp). try: ftp = FTP(ftp.host.com) ftp.login(your_username, your_password) file = open(myfile.txt,...
Python’s ftplib STOR reliable?
I'm using this code to upload myfile.txt from my windows machine to a ftp server. after the upoad the script deletes the file on my local machine (I'm not deleting it on the ftp). try: ftp = FTP(ftp.host.com) ftp.login(your_username, your_password) file = open(myfile.txt, "rb") ftp.storbinary('STOR myfi...
[ "Don't use subprocess to shell out to delete a file - the os.unlink call will allow you to do this portably (the shutil library fills in the gaps when os fails)\nRight now, you are gobbling the error with your silly print statement - get a traceback from the exception which would give you a large number of clues. H...
[ 2, 2, 1 ]
[]
[]
[ "exception", "file_upload", "ftp", "ftplib", "python" ]
stackoverflow_0002058584_exception_file_upload_ftp_ftplib_python.txt
Q: Utilizing objects in another class in Python In code(pseudo) like this def path(): dirList = ['c:\\', 'y:\\', 'z:\\'] home_folder = 'peter.txt' complete = [s + home_folder for s in dirList] print complete def fileWrite(): filename = 'c:\peter.txt' text = 'Hello World' file = open(filen...
Utilizing objects in another class in Python
In code(pseudo) like this def path(): dirList = ['c:\\', 'y:\\', 'z:\\'] home_folder = 'peter.txt' complete = [s + home_folder for s in dirList] print complete def fileWrite(): filename = 'c:\peter.txt' text = 'Hello World' file = open(filename, 'w') file.write(text) file.close() I...
[ "If I understand question correclty - you can add additional parameter to fileWrite like fileWrite(filename) and simply iterate over 'complete' sequence.\n", "import os\n\ndef paths(filename):\n dirList = ['c:\\\\', 'y:\\\\', 'z:\\\\']\n complete = [os.path.join(s, filename) for s in dirList]\n return co...
[ 1, 1 ]
[]
[]
[ "class", "iteration", "python" ]
stackoverflow_0002059013_class_iteration_python.txt
Q: Contents of PyString in Qt Creator debugger? I've got a PyString* object that I would like to see the contents of. Is there any way to see the text of the PyString using Qt Creator's debugger? PyObject *import_str = PyString_InternFromString("__import__"); If it makes a difference, Qt Creator is a front end to GD...
Contents of PyString in Qt Creator debugger?
I've got a PyString* object that I would like to see the contents of. Is there any way to see the text of the PyString using Qt Creator's debugger? PyObject *import_str = PyString_InternFromString("__import__"); If it makes a difference, Qt Creator is a front end to GDB.
[ "I doubt that Qt Creator can display the contents of the string like it does with QString, etc. This is because PyObject is a custom class that Qt Creator/gdbv does not know how to handle.\nFor instance: QString is a custom class as well, but Qt Creator loads some special commands/modules/whatever which allows for...
[ 0, 0 ]
[]
[]
[ "cpython", "debugging", "python", "qt", "qt_creator" ]
stackoverflow_0001883316_cpython_debugging_python_qt_qt_creator.txt
Q: Grabbing the output of MAPLE via Python How would I use the subprocess module in Python to start a command line instance of MAPLE to feed and return output to the main code? For example I'd like: X = '1+1;' print MAPLE(X) To return the value of "2". The best I've seen is a SAGE wrapper around the MAPLE commands, ...
Grabbing the output of MAPLE via Python
How would I use the subprocess module in Python to start a command line instance of MAPLE to feed and return output to the main code? For example I'd like: X = '1+1;' print MAPLE(X) To return the value of "2". The best I've seen is a SAGE wrapper around the MAPLE commands, but I'd like to not install and use the overh...
[ "Trying to drive a subprocess \"interactively\" more often than not runs into issues with the subprocess doing some buffering, which blocks things.\nThat's why for such purposes I suggest instead using pexpect (everywhere but Windows: wexpect on Windows), which is designed exactly for this purpose -- letting your p...
[ 3, 3, 0 ]
[]
[]
[ "maple", "pexpect", "python", "subprocess" ]
stackoverflow_0002053231_maple_pexpect_python_subprocess.txt
Q: Python identity: Multiple personality disorder, need code shrink Possible Duplicate: Python “is” operator behaves unexpectedly with integers I stumbled upon the following Python weirdity: >>> two = 2 >>> ii = 2 >>> id(two) == id(ii) True >>> [id(i) for i in [42,42,42,42]] [10084276, 10084276, 10084276, 10084276...
Python identity: Multiple personality disorder, need code shrink
Possible Duplicate: Python “is” operator behaves unexpectedly with integers I stumbled upon the following Python weirdity: >>> two = 2 >>> ii = 2 >>> id(two) == id(ii) True >>> [id(i) for i in [42,42,42,42]] [10084276, 10084276, 10084276, 10084276] >>> help(id) Help on built-in function id in module __builtin__: ...
[ "Integers between -1 and 255(?), as well as string literals, are interned. Each instance in the source actually represents the same object.\nIn CPython, the result of id() is the address in the process space of the PyObject.\n", "Every implementation of Python is fully allowed to optimize to any extent (including...
[ 9, 8, 4, 2, 1 ]
[]
[]
[ "identity", "memory", "memory_management", "python", "uniqueidentifier" ]
stackoverflow_0002058948_identity_memory_memory_management_python_uniqueidentifier.txt
Q: Lazy SAX XML parser with stop/resume I am pretty sure the answer is no but of course there are cleverer guys than me! Is there a way to construct a lazy SAX based XML parser that can be stopped (e.g. raising an exception is a possible way of doing this) but also resumable ? I am looking for a possible solution for...
Lazy SAX XML parser with stop/resume
I am pretty sure the answer is no but of course there are cleverer guys than me! Is there a way to construct a lazy SAX based XML parser that can be stopped (e.g. raising an exception is a possible way of doing this) but also resumable ? I am looking for a possible solution for Python >= 2.6 with standard XML libraries...
[ "Expat can be stopped and is resumable. AFAIK Python SAX parser uses Expat. Does the API really not expose the stopping stuff to the Python side?? \nEDIT: nope, looks like the parser stopping isn't available from Python...\n" ]
[ 0 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0002059455_python_sax_xml.txt
Q: Return Django form contents on error All, I have a template page say x.html i have 3 text fields name(varchar2) ,age(int),school(varchar2) in it. If the users enters values in the form in x.html(say values name="a" ,age="2" ,school="a") and submit it.I need to return the same values back to x.html indicating an er...
Return Django form contents on error
All, I have a template page say x.html i have 3 text fields name(varchar2) ,age(int),school(varchar2) in it. If the users enters values in the form in x.html(say values name="a" ,age="2" ,school="a") and submit it.I need to return the same values back to x.html indicating an error. My question is how to return the same...
[ "from docs:\n\nThe standard pattern for processing a form in a view looks like this:\n\ndef contact(request):\n if request.method == 'POST': # If the form has been submitted...\n form = ContactForm(request.POST) # A form bound to the POST data\n if form.is_valid(): # All validation rules pass\n ...
[ 2, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002059374_django_python.txt
Q: Catching warnings pre-python 2.6 In Python 2.6 it is possible to suppress warnings from the warnings module by using with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() Versions of Python before 2.6 don't support with however, so I'm wondering if there alternatives to the above that woul...
Catching warnings pre-python 2.6
In Python 2.6 it is possible to suppress warnings from the warnings module by using with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() Versions of Python before 2.6 don't support with however, so I'm wondering if there alternatives to the above that would work with pre-2.6 versions?
[ "This is similar:\n# Save the existing list of warning filters before we modify it using simplefilter().\n# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter\n# would alias the one and only 'real' list and then we'd have nothing to restore.\noriginal_filters = warnings.filters[:]\...
[ 3 ]
[ "Depending on what the minimum version you need to support using Python 2.5's \nfrom __future__ import with_statement\n\nmight be an option, else you'll probably need to fallback to what Jon suggested.\n" ]
[ -1 ]
[ "python", "suppress_warnings", "warnings" ]
stackoverflow_0002059675_python_suppress_warnings_warnings.txt
Q: Python C API and data persistent in memory? I'm considering integrating some C code into a Python system (Django), and I was considering using the Python / C API. The alternative is two separate processes with IPC, but I'm looking into direct interaction first. I'm new to Python so I'm trying to get a feel for the...
Python C API and data persistent in memory?
I'm considering integrating some C code into a Python system (Django), and I was considering using the Python / C API. The alternative is two separate processes with IPC, but I'm looking into direct interaction first. I'm new to Python so I'm trying to get a feel for the right direction to take. Is it possible for a ca...
[ "Cython\n", "You can certainly use the C API to do what you want. You'll create a class in C, which can hold onto any memory it wants. That memory doesn't have to be exposed to Python at all if you don't want.\nIf you are comfortable building C DLLs, and don't need to perform Python operations in C, then ctypes...
[ 2, 1 ]
[]
[]
[ "c", "ipc", "python" ]
stackoverflow_0002059685_c_ipc_python.txt
Q: How to refine an initial query in Django? Following the reply to this question (Thanks again Ellie P!) I created a search page and a results page. For instance if you search for the lawyer "delelle" the result page shows her firm, school and year graduated. But instead of displaying her info, I want to display ot...
How to refine an initial query in Django?
Following the reply to this question (Thanks again Ellie P!) I created a search page and a results page. For instance if you search for the lawyer "delelle" the result page shows her firm, school and year graduated. But instead of displaying her info, I want to display other lawyers who graduated from the same school ...
[ "This view function answers the question:\ndef search(request):\n if 'q' in request.GET and request.GET['q']:\n q = request.GET['q']\n q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)\n q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_gr...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002058573_django_python.txt
Q: drop table in python with sqlite3 I have question about python and sqlite3. I want to drop a table from within Python. The command cur.execute('drop table if exists tab1') Does not work. cur.executescript('drop table if exists tab1;') does the job. The execute method allows the creation of tables. However, it...
drop table in python with sqlite3
I have question about python and sqlite3. I want to drop a table from within Python. The command cur.execute('drop table if exists tab1') Does not work. cur.executescript('drop table if exists tab1;') does the job. The execute method allows the creation of tables. However, it won't drop them? Is there a reason fo...
[ "The cur.executescript command issues a COMMIT before running the provided script. Additionally a CREATE executes a COMMIT intrinsically. Perhaps you have an open transaction that needs committed before your changes take place.\n" ]
[ 14 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002060032_python_sqlite.txt
Q: Python: sort the list I want to sort the array c. But I don't get the answer a,b,c,d. Instead I get a,b,d,c. What could I do, for sorting the whole array and not only one row? EDIT: I want to sort the numbers. And the connected letters, should have the same order like the sorted numbers. sorry my question wasn't c...
Python: sort the list
I want to sort the array c. But I don't get the answer a,b,c,d. Instead I get a,b,d,c. What could I do, for sorting the whole array and not only one row? EDIT: I want to sort the numbers. And the connected letters, should have the same order like the sorted numbers. sorry my question wasn't clear. Maybe I should join n...
[ "Let's take a look at what's going on here:\n# Initialize the lists\na = ['a','b','d','c']\nb = [1,2,4,3]\nc = [[],[]]\n\n# Assign the lists to positions in c\nc[0]=a\nc[1]=b\n\n# Sort b, which was assigned to c[1]\nc[1].sort()\nprint(c)\n\nSo, of course you could not expect a to get sorted. Try this instead:\n# S...
[ 5, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0002059564_list_python_sorting.txt
Q: Qt winId() forcing 32bit values Im trying to embed a display from an alien application (python OCC) into (Py)Qt using the winId of the widget. But when i pass it to OCC i get an overflow error. Inspecting the winId qt returns its 4318283408 which is more than a 32bit number. Im running 64bits (osx) and both libra...
Qt winId() forcing 32bit values
Im trying to embed a display from an alien application (python OCC) into (Py)Qt using the winId of the widget. But when i pass it to OCC i get an overflow error. Inspecting the winId qt returns its 4318283408 which is more than a 32bit number. Im running 64bits (osx) and both libraries are compiled for 64bit, but i ha...
[ "Looking in Qt's source code, in the file src/gui/kernel/qwindowdefs.h, you'll find that WId is typedef'd to long for 64-bits OSX (it's int for 32-bits OSX). A long on 64-bits OSX is 8 bytes long (or 64 bits), and therefore 4318283408 is a valid value.\nIf you want to force winId() to return a 32 bits value, you wi...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0002053949_pyqt4_python_qt.txt
Q: How important are design patterns in web development? What are the design patterns that I should be completely familiar with? And what is one easy example that each can be used for? I am a web developer (I use Django, and is familiar with separation of logic), but I work at a Desktop-app company. They are always ...
How important are design patterns in web development?
What are the design patterns that I should be completely familiar with? And what is one easy example that each can be used for? I am a web developer (I use Django, and is familiar with separation of logic), but I work at a Desktop-app company. They are always talking about singletons, and I forget...but it leaves me n...
[ "MVP or MVC\nModel View Presenter or Model View Controller\nMore architecural patterns but neverless, they are a combination of design patterns.\n", "Forget Singleton. It's confusing and rarely necessary.\nLearn State, Strategy and Command. They're used all the time.\nState is for anything that has logic that d...
[ 11, 10, 2, 1, 1, 0 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0002060341_design_patterns_oop_python.txt
Q: super() weirdness in Python 3 I know this has been discussed a number of times before, but there was never an explanation of what's going on "under the hood". Can anyone provide a detailed explanation as to why commenting-in the last line of code causes an error to be raised? I know that that object.__init__ doesn...
super() weirdness in Python 3
I know this has been discussed a number of times before, but there was never an explanation of what's going on "under the hood". Can anyone provide a detailed explanation as to why commenting-in the last line of code causes an error to be raised? I know that that object.__init__ doesn't take any arguments, but why does...
[ "In Python 3 every method becomes a closure with a hidden value added for the \"current class\" being defined. This is accessed by super() (with no arguments).\nSuper returns an object which uses the class's Method Resolution Order (MRO), and for C instances this has B after A.\nWithout finding B in the MRO, super...
[ 6 ]
[]
[]
[ "python", "python_3.x", "super" ]
stackoverflow_0002060475_python_python_3.x_super.txt
Q: Is there anything out there that can take screenshots of website content and crop out the layout? Other ideas are also welcome. I am trying to take an excel file, using python to generate an xml for a javascript html webpage that will essentially display a gallery (or some sort of directory structure). The excel f...
Is there anything out there that can take screenshots of website content and crop out the layout?
Other ideas are also welcome. I am trying to take an excel file, using python to generate an xml for a javascript html webpage that will essentially display a gallery (or some sort of directory structure). The excel file would be pretty massive, but let us assume time isn't so crucial. So far I can convert the tab del...
[ "You could probably use pywebkitgtk to render the HTML and then PIL to manipulate the image.\n" ]
[ 1 ]
[]
[]
[ "automation", "crop", "image", "python", "screenshot" ]
stackoverflow_0002060865_automation_crop_image_python_screenshot.txt
Q: Copy Table data from one DB to another For development I find myself needing to copy table information from one table to another quite often. I am just curious what are the easiest solutions to do this for Postgres. I have PGAdminIII but it looks like it really only support the long drawn out Backup/Restore. Is ...
Copy Table data from one DB to another
For development I find myself needing to copy table information from one table to another quite often. I am just curious what are the easiest solutions to do this for Postgres. I have PGAdminIII but it looks like it really only support the long drawn out Backup/Restore. Is there a python or bash script somewhere or s...
[ "Kettle, aka pentaho data integration can do this for you. \nhttp://sourceforge.net/projects/pentaho/files/Data%20Integration/\n\nDownload kettle and unzip. \nMake sure you have a java runtime environment (1.5 and 1.6 will both work for the 3.2 stable version). \nRun spoon.sh\nCreate a new job (file/new/job)\nDefin...
[ 7, 3 ]
[]
[]
[ "linux", "macos", "postgresql", "python" ]
stackoverflow_0002060823_linux_macos_postgresql_python.txt
Q: Opening multiple windows from a list in WxPython I have a little program that goes to news aggregater's, gets the hrefs, and returns in a window. I want to have multiple windows open if multiple sites are choosen, right now, it will only go to the first one in a list, and completes perfectly. I assume I am not pas...
Opening multiple windows from a list in WxPython
I have a little program that goes to news aggregater's, gets the hrefs, and returns in a window. I want to have multiple windows open if multiple sites are choosen, right now, it will only go to the first one in a list, and completes perfectly. I assume I am not passing the the contents of the list properly to the next...
[ "Eeek! You're defining your MyHTMLFrame class -inside- an event handler function (not a good idea). \nI can't run the script as I don't have the module PyParsing (always make samples that have as little dependencies as possible...)\nTherefore, I'm not sure if this code runs, but it should give you the general idea....
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002059786_python_wxpython.txt
Q: Yahoo OAuth question I'm keep getting oauth_problem=consumer_key_unknown error when trying oauth https://api.login.yahoo.com/oauth/v2/get_request_token I'm pretty sure my consumer key is correct because it works locally (Runs via 127.0.0.1). Just keep giving me oauth_problem=consumer_key_unknown when I try it on m...
Yahoo OAuth question
I'm keep getting oauth_problem=consumer_key_unknown error when trying oauth https://api.login.yahoo.com/oauth/v2/get_request_token I'm pretty sure my consumer key is correct because it works locally (Runs via 127.0.0.1). Just keep giving me oauth_problem=consumer_key_unknown when I try it on my server. Any ideas?
[ "is it sending the right domain in requireSession (4th argument should be something like 'http://mydomain.com/' which should match exactly what you used to sign up...\n" ]
[ 0 ]
[]
[]
[ "oauth", "python", "yahoo" ]
stackoverflow_0002061124_oauth_python_yahoo.txt
Q: Subclassing Decimal in Python I want to use Decimal class in my Python program for doing financial calculations. Decimals to not work with floats - they need explicit conversion to strings first. So i decided to subclass Decimal to be able to work with floats without explicit conversions. m_Decimal.py: # -*- codin...
Subclassing Decimal in Python
I want to use Decimal class in my Python program for doing financial calculations. Decimals to not work with floats - they need explicit conversion to strings first. So i decided to subclass Decimal to be able to work with floats without explicit conversions. m_Decimal.py: # -*- coding: utf-8 -*- import decimal Decima...
[ "Currently, it won't do what you want at all. You can't multiply your m_decimal by anything: it will always return None, due to a missing return statement:\n def __mul__ ( self, other ) :\n print (type(other))\n return Decimal.__mul__ ( self, other )\n\nEven with the return added in, you still c...
[ 4, 1, 0 ]
[]
[]
[ "decimal", "python", "subclassing" ]
stackoverflow_0002044427_decimal_python_subclassing.txt
Q: Downgrading to pyobjc 2.0 from pyobjc 2.2 I accidentally installed pyobjc 2.2 with easy-install pyobjc, and it's causing problems: When I try to import it I get the error Incompatible library version: _objc.so requires version 10.0.0 or later, but libxml2.2.dylib provides version 9.0.0 I'm not interested in fixi...
Downgrading to pyobjc 2.0 from pyobjc 2.2
I accidentally installed pyobjc 2.2 with easy-install pyobjc, and it's causing problems: When I try to import it I get the error Incompatible library version: _objc.so requires version 10.0.0 or later, but libxml2.2.dylib provides version 9.0.0 I'm not interested in fixing that though, all I want is my pyobjc 2.0 bac...
[ "If you are using the Apple-supplied Python 2.5 on 10.5 Leopard, which comes with PyObjC 2.0 built-in, probably the easiest way to downgrade is to remove the 2.2 version from its site-packages directory, /Library/Python/2.5/site-packages. First, though, run the command:\neasy_install -m pyobjc==2.2\n\nwhich will e...
[ 2, 1 ]
[]
[]
[ "downgrade", "macos", "pyobjc", "python" ]
stackoverflow_0002052013_downgrade_macos_pyobjc_python.txt
Q: machine readable language for writing notes I'd like to write notes for class in plain text. I was wondering if there was a markup language for doing this, where I could parse the notes for key terms, titles, page #s etc programmatically with a language such as Ruby or Python. A: In the Python world, reStructure...
machine readable language for writing notes
I'd like to write notes for class in plain text. I was wondering if there was a markup language for doing this, where I could parse the notes for key terms, titles, page #s etc programmatically with a language such as Ruby or Python.
[ "In the Python world, reStructuredText is probably the most widely used markup language, and it's the result of a long-term and fairly rigorous design and development. It's the markup underlying the Sphinx documentation tool which, among other things, is used for the Python docs and many Python projects.\nI also h...
[ 4, 2 ]
[]
[]
[ "markup", "python", "ruby" ]
stackoverflow_0002061806_markup_python_ruby.txt
Q: About 20 models in 1 django app I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python. There's one problem: I have at least 20 models and each will have many func...
About 20 models in 1 django app
I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python. There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to cre...
[ "This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)\nYou can split up the models.py file (and views.py too) into a pacakge. In this case, your project tree will look like:\n/my_proj\n /myapp\n /models\n __init__.py\n person.py...
[ 76, 31, 16, 5, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000859192_django_django_models_python.txt
Q: Filter array to show rows with a specific value in a specific column Let's say i have a multidimensional list l: l = [['a', 1],['b', 2],['c', 3],['a', 4]] and I want to return another list consisting only of the rows that has 'a' in their first list element: m = [['a', 1],['a', 4]] What's a good and efficient wa...
Filter array to show rows with a specific value in a specific column
Let's say i have a multidimensional list l: l = [['a', 1],['b', 2],['c', 3],['a', 4]] and I want to return another list consisting only of the rows that has 'a' in their first list element: m = [['a', 1],['a', 4]] What's a good and efficient way of doing this?
[ "Definitely a case for a list comprehension:\nm = [row for row in l if 'a' in row[0]]\n\nHere I'm taking your \"having 'a' in the first element\" literally, whence the use of the in operator. If you want to restrict this to \"having 'a' as the first element\" (a very different thing from what you actually wrote!-)...
[ 19, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002062368_list_python.txt
Q: After doing a SQLAlchemy update(), is there a way to get the changed values? After calling update(), I know that the return value has a .rowcount attribute that will reveal how many rows were changed. Is there a way to get the actual new values that they were changed to? For example, if I do the SQLAlchemy equival...
After doing a SQLAlchemy update(), is there a way to get the changed values?
After calling update(), I know that the return value has a .rowcount attribute that will reveal how many rows were changed. Is there a way to get the actual new values that they were changed to? For example, if I do the SQLAlchemy equivalent of: UPDATE t SET x=x+1 WHERE y=z ...is there a way to get the new value for x...
[ "The ResultProxy has two methods, last_updated_params() which returns a dictionary of every bind parameter value sent with the statement execution, as well as a collection postfetch_cols(), a list of columns for which an inline SQL expression was embedded in the UPDATE (for which you'd have to post-SELECT the value...
[ 3 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002059315_python_sql_sqlalchemy.txt
Q: How to use "class" the word as parameter function calls in python I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer. The result XML require attributes named "class". e.g. <Node class="oops"></Node> As the official t...
How to use "class" the word as parameter function calls in python
I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer. The result XML require attributes named "class". e.g. <Node class="oops"></Node> As the official tutorial suggested, to write an XML node just use this method: w.element...
[ "I guess SimpleXMLWriter developers meant this solution:\nw.element(\"Node\", None, {'class': 'oops'})\n\nor \nw.element(\"Node\", attrib={'class': 'oops'})\n\n", "What steveha has written is true. As in any language, keywords can't be used for different purposes.\nWhat you can do, if you must use \"class\" is th...
[ 7, 5, 3 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0002062683_elementtree_python.txt
Q: if there any better way to read bb function souce code.i was very faint in python ,if a.py from b import bb bb() b.py from c import cc def bb(): do someting else cc() c.py from d import dd def cc(): do someting else dd() d.py from e import ee def dd(): do someting else ee() e.py from f import ff...
if there any better way to read bb function souce code.i was very faint
in python ,if a.py from b import bb bb() b.py from c import cc def bb(): do someting else cc() c.py from d import dd def cc(): do someting else dd() d.py from e import ee def dd(): do someting else ee() e.py from f import ff def ee(): do someting else ff() to Understood bb function,i must open 5...
[ "The best way to import the ff function from the f module would be to use an import statement in your program:\nfrom f import ff\nff(...)\n\nOr you could use the form:\nimport f\nf.ff(...)\n\nEDIT:\nIf you are looking for tools to better read/navigate through the source code, I recommend creating a tags file for yo...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002048163_python.txt
Q: Why scipy.io.wavfile.read does not return a tuple? I am trying to read a *.wav file using scipy. I do the following: import scipy x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') As a result of this code I get: Traceback (most recent call last): File "test3.py", line 2, in <module> x = scip...
Why scipy.io.wavfile.read does not return a tuple?
I am trying to read a *.wav file using scipy. I do the following: import scipy x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') As a result of this code I get: Traceback (most recent call last): File "test3.py", line 2, in <module> x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav'...
[ "As the error says, scipy module does not have 'io'.\nio.wavfile is a submodule, you need to from scipy.io import wavfile and then do wavfile.read(\"/usr/share/sounds/purple/receive.wav\")\nThis gives me an error with the file you are using as an example, however...\n" ]
[ 8 ]
[]
[]
[ "python", "scipy", "wav" ]
stackoverflow_0002063046_python_scipy_wav.txt
Q: python windows vista/7 uac and copying (only reading) files? permissions/interaction of UAC? I'm currently making a program for a lan center that scans a users hard drive, and copies/archives certain save game files into a zip and uploads them to a FTP server. But I've created a lot of the program at this point a...
python windows vista/7 uac and copying (only reading) files? permissions/interaction of UAC?
I'm currently making a program for a lan center that scans a users hard drive, and copies/archives certain save game files into a zip and uploads them to a FTP server. But I've created a lot of the program at this point and just had a major issue that I had not tested for spring to mind: How does Vista/7's UAC permiss...
[ "If your program is running as elevated admin, then it will not redirect to c:\\users folder. \nYou can run the program as elevated admin by embedding a manifest to the file.\nsee http://en.wikipedia.org/wiki/User_Account_Control\nfor details on tasks that trigger the UAC prompt.\nAlso note that 64 bit Windows 7 do...
[ 0 ]
[]
[]
[ "python", "uac", "windows_7", "windows_vista" ]
stackoverflow_0002060672_python_uac_windows_7_windows_vista.txt
Q: Cambodian keyboard for Windows and Linux? Before I created http://khmerlc.org/khmerkeyweb/ with javascript that allow user input cambodia unicode user can switch from English to khmer(cambodia) I am going to build an application called khmerkey for desktop (both can run window,linux). I will use python. the User ...
Cambodian keyboard for Windows and Linux?
Before I created http://khmerlc.org/khmerkeyweb/ with javascript that allow user input cambodia unicode user can switch from English to khmer(cambodia) I am going to build an application called khmerkey for desktop (both can run window,linux). I will use python. the User interface it's very simple, just: With two opt...
[ "Hooking keys and sendkeys is different way for Windows and Linux, so you have to do it seperately.\nIn Windows, you can use combination of PyHook and SendKeys\nFor Linux, I have no idea now, I will update this when I found something.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002063412_python.txt
Q: python lotus notes: odbc connect error I am developing a client server application for a cross-database system. I am using Eclipse IDE with Python 2.5 and PyODBC2.5; need to read content from a Lotus Notes database, so run some basic query like - SELECT peronname FROM tablename. 'import pyodbc' is ok - python see ...
python lotus notes: odbc connect error
I am developing a client server application for a cross-database system. I am using Eclipse IDE with Python 2.5 and PyODBC2.5; need to read content from a Lotus Notes database, so run some basic query like - SELECT peronname FROM tablename. 'import pyodbc' is ok - python see it! But when I try to run conn = pyodbc.conn...
[ "I think it's odd that you want to try accessing Lotus Notes data vie SQL. When I have interfaced Notes and Python in the past, I always used the Lotus Note COM object to access data. After all, Notes is a document database like CouchDB, not a relational database.\n", "I almost forgot to post the solution here......
[ 0, 0 ]
[]
[]
[ "connect", "lotus", "lotus_notes", "odbc", "python" ]
stackoverflow_0001610781_connect_lotus_lotus_notes_odbc_python.txt
Q: Accessing XML comment located before the root element Please help me to resolve my problem with lxml. How can I get "Comment 1" from this file? <?xml version="1.0" encoding="windows-1251" standalone="yes" ?> <!--Comment 1--> <a> <!--Comment 2--> </a> A: Docs: the lxml tutorial, and search for "Comments" Code:...
Accessing XML comment located before the root element
Please help me to resolve my problem with lxml. How can I get "Comment 1" from this file? <?xml version="1.0" encoding="windows-1251" standalone="yes" ?> <!--Comment 1--> <a> <!--Comment 2--> </a>
[ "Docs: the lxml tutorial, and search for \"Comments\"\nCode:\nimport lxml.etree as et\n\ntext = \"\"\"\\\n<?xml version=\"1.0\" encoding=\"windows-1251\" standalone=\"yes\" ?>\n<!--Comment 1a-->\n<!--Comment 1b-->\n<a> waffle\n <!--Comment 2-->\n blah blah\n</a>\n<!--Comment 3a-->\n<!--Comment 3b-->\n\"\"\"\npr...
[ 11, 6 ]
[]
[]
[ "comments", "lxml", "python", "xml" ]
stackoverflow_0002063274_comments_lxml_python_xml.txt
Q: Qt Python: QTextEdit - display input I have a QTextEdit... it works with 'clear()' when a pushbutton calls 'CleanComments' to clean the input done by the user. Here is the code: def CleanComments(self): self.textEditInput.clear() def showInput(self): print "show input: %s" % self.textEditInput.show() def...
Qt Python: QTextEdit - display input
I have a QTextEdit... it works with 'clear()' when a pushbutton calls 'CleanComments' to clean the input done by the user. Here is the code: def CleanComments(self): self.textEditInput.clear() def showInput(self): print "show input: %s" % self.textEditInput.show() def buildEditInput(self): self.textEditIn...
[ "To get the contents of a QTextEdit as a simple string, use the toPlainText() method.\nprint \"show input: %s\" % self.textEditInput.toPlainText()\n\nThere is also the toHtml() method. For even more options, you can work directly with the QTextDocument from QTextEdit.document().\n", "Your showInput method is prin...
[ 5, 0, 0 ]
[]
[]
[ "python", "qt", "qtextedit" ]
stackoverflow_0002063633_python_qt_qtextedit.txt
Q: "Parseltongue": get Ruby to Speak a bit of Python? Just for interest really - community wiki - how much Python can we get Ruby to understand ? [ Probably be just as interesting to do the reverse as well]. The experiment (such as it is) perhaps to see how much can be written in Ruby-Cross-Python scripts that will r...
"Parseltongue": get Ruby to Speak a bit of Python?
Just for interest really - community wiki - how much Python can we get Ruby to understand ? [ Probably be just as interesting to do the reverse as well]. The experiment (such as it is) perhaps to see how much can be written in Ruby-Cross-Python scripts that will result in identical outputs. The only 'cheat' I guess bei...
[ "To answer the question fully would probably need a bit of analysis. The control structures in both languages are defined to make our lives easier and the codes more readable when we program, but they could be realised with methods like it was in smalltalk. Iterations and conditionals (except the \"case\" statement...
[ 1 ]
[]
[]
[ "multilingual", "python", "ruby" ]
stackoverflow_0002063962_multilingual_python_ruby.txt
Q: Executing python code from script and getting interpreter-style output I need to execute code from my python script and take interpreter-style output like it's done here. I am creating website on GAE using django, it must run user-entered code and print interpreter-style output as text. A: there is code.Interac...
Executing python code from script and getting interpreter-style output
I need to execute code from my python script and take interpreter-style output like it's done here. I am creating website on GAE using django, it must run user-entered code and print interpreter-style output as text.
[ "there is code.InteractiveInterpreter available, but I think you can take an inspiration in the following simpler example:\nimport code\n\nexprs = [\n 'd = {}',\n 'd',\n 'd[\"x\"] = 1',\n 'd',\n ]\n\nfor e in exprs:\n print '>>> %s' % e\n cmd = code.compile_command(e)\n r = eval(cmd)\n if ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002064491_python.txt
Q: Python not all in operation How do I check if a list is a subset of a bigger list. i.e. a = [1,2,3] is a subset of b = [1,2,3,4,5,6] Can I do something like if a all in b A: http://docs.python.org/library/stdtypes.html#set.issubset set(a).issubset(set(b)) A: >>> a = set([1, 2, 3]) >>> b = set([1, 2, 3, 4, 5,...
Python not all in operation
How do I check if a list is a subset of a bigger list. i.e. a = [1,2,3] is a subset of b = [1,2,3,4,5,6] Can I do something like if a all in b
[ "http://docs.python.org/library/stdtypes.html#set.issubset\nset(a).issubset(set(b))\n\n", ">>> a = set([1, 2, 3])\n>>> b = set([1, 2, 3, 4, 5, 6])\n>>> a.issubset(b)\nTrue\n\nor\n>>> a = [1, 2, 3]\n>>> b = [1, 2, 3, 4, 5, 6]\n>>> all(map(lambda x: x in b, a))\nTrue\n>>> a = [1, 2, 3, 9]\n>>> all(map(lambda x: x i...
[ 12, 5, 2 ]
[]
[]
[ "python", "set" ]
stackoverflow_0002064389_python_set.txt
Q: multiprocessing.Process subclass works on Linux but not Windows I'm trying to get python-gasp working on Windows, but when I do import gasp; gasp.begin_graphics() I get the following traceback: File "C:\Python26\lib\site-packages\gasp\backend.py", line 142, in create_screen screen.updater.start() File "C...
multiprocessing.Process subclass works on Linux but not Windows
I'm trying to get python-gasp working on Windows, but when I do import gasp; gasp.begin_graphics() I get the following traceback: File "C:\Python26\lib\site-packages\gasp\backend.py", line 142, in create_screen screen.updater.start() File "C:\Python26\lib\multiprocessing\process.py", line 104, in start s...
[ "Your Updater class has a member screen, which itself has a member process which receives the value of multiprocessing.current_process().\nWhen you call updater.start(), it tries to pickle the updater. This only happens on Windows because Linux uses fork() instead of pickling. However, the current-process object ca...
[ 2 ]
[]
[]
[ "gasp", "multiprocessing", "pickle", "python", "windows" ]
stackoverflow_0002064533_gasp_multiprocessing_pickle_python_windows.txt
Q: Using wget with subprocess I'm trying to use wget with subprocess. my attempts worked until I tried to download the page to a specified directory with this code: url = 'google.com' location = '/home/patrick/downloads' args = ['wget', 'r', 'l 1' 'p' 'P %s' % location, url] output = Popen(args, stdout=PIPE) if I r...
Using wget with subprocess
I'm trying to use wget with subprocess. my attempts worked until I tried to download the page to a specified directory with this code: url = 'google.com' location = '/home/patrick/downloads' args = ['wget', 'r', 'l 1' 'p' 'P %s' % location, url] output = Popen(args, stdout=PIPE) if I run this code in /home/patrick I ...
[ "You need to have hyphens and location should be just another argument:\nargs = ['wget', '-r', '-l', '1', '-p', '-P', location, url]\n\n", "Edit: popen from os intends to replace os.popen module. Hence, using os.popen is not recommended\nInitially I thought it was popen from os.\nIf you are using popen from os\n#...
[ 4, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002065060_python_subprocess.txt
Q: UDP packet encryption This appears to be reasonably trivial if using the ssl module for TCP communication, but how would encrypted communication be done via UDP? Can the ssl module still be used? if so, what steps would need to be performed for the client and server to be in a position where data can be sent to-a...
UDP packet encryption
This appears to be reasonably trivial if using the ssl module for TCP communication, but how would encrypted communication be done via UDP? Can the ssl module still be used? if so, what steps would need to be performed for the client and server to be in a position where data can be sent to-and-fro as normal?
[ "DTLS is a TLS (aka SSL) derivative designed for use over datagram transports, like UDP.\nOpenSSL supports DTLS starting in 0.9.8, using DTLSv1_METHOD instead of SSLv23_METHOD or TLSv1_METHOD or similar.\n", "You could use pyCrypto or ezPyCrypto to manually encrypt/decrypt the packets.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "ssl", "udp" ]
stackoverflow_0002065218_python_ssl_udp.txt
Q: How should Django Apps bundle static media? Background: I'm starting to use Django for the first time, which is also my first foray into web development. I just got stuck on the whole "serving static media" problem. After spending a while looking at all the documentation and StackOverflow questions, I think I und...
How should Django Apps bundle static media?
Background: I'm starting to use Django for the first time, which is also my first foray into web development. I just got stuck on the whole "serving static media" problem. After spending a while looking at all the documentation and StackOverflow questions, I think I understand how it's supposed to work (i.e. MEDIA_ROO...
[ "Convention is to put static media in either media/appname/ or static/appname/ within the app (similar to templates).\nFor using apps in your project that come with media, I strongly recommend using django-staticfiles. It will automatically serve media (including media within apps) in development through a view tha...
[ 9, 2, 2 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0002063923_django_python_web_applications.txt
Q: Parsing, securing python expression before passing it to eval() I want to take an input from the user may be like foo() > 90 and boo() == 9 or do() > 100 and use eval on the server side to to evaluate this expression. For security I want to restrict user to add limited functions and operators by keeping a check (a...
Parsing, securing python expression before passing it to eval()
I want to take an input from the user may be like foo() > 90 and boo() == 9 or do() > 100 and use eval on the server side to to evaluate this expression. For security I want to restrict user to add limited functions and operators by keeping a check (against some data-structure) before I pass it to eval function. PS: In...
[ "Basically the only way to do this is to parse it yourself. You navigate the parse tree to guarantee that each part is in a whitelist of perfectly benign and safe operations, making the entire expression safe by construction. Ned Batchelder's answer is actually a (simple) form of this. You could pass it to eval() a...
[ 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002065331_python.txt
Q: how to avoid storing different type of objects in the same place when they represent the same but with a different data structure This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I w...
how to avoid storing different type of objects in the same place when they represent the same but with a different data structure
This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible. I'm creating some classes to simplify some tasks for some specific requirements we have in some proj...
[ "I'm not sure I understand your question, but maybe Visitor pattern is what you are looking for?\n", "Sounds like composite pattern to me. Composite will provide an interface for treating containers of objects and leaf objects (those that are not containers) the same.\n", "This is the Polymorphism problem.\n\"s...
[ 1, 1, 1 ]
[]
[]
[ "algorithm", "asp.net", "design_patterns", "ironpython", "python" ]
stackoverflow_0002064284_algorithm_asp.net_design_patterns_ironpython_python.txt
Q: wxFrame with title bar but non resizable hai guyz I need to create a login window for that window i need a title bar for dragging but it should not be a resized I need a fixed size for this window A: frame = wx.Frame(self, title="something", size=(480, 320), style=wx.CAPTION) You can "mix and match" styles, w...
wxFrame with title bar but non resizable
hai guyz I need to create a login window for that window i need a title bar for dragging but it should not be a resized I need a fixed size for this window
[ "frame = wx.Frame(self, title=\"something\", size=(480, 320), style=wx.CAPTION)\n\nYou can \"mix and match\" styles, which can be seen here: http://docs.wxwidgets.org/2.6/wx_wxframe.html\ne.g. in my example, no \"close box\" is shown, so:\nframe = wx.Frame(self, title=\"something\", size=(480, 320), style=wx.CAPTIO...
[ 4 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002064856_python_wxpython.txt
Q: Linear Fit to Planet Positions An astounding alignment occurs 2048/5/28 with the inner 5 planets having heliocentric longitudes (in degrees): 248.229, 66.631, 246.967, 249.605, 67.684. The planets are at most 0.875 degrees from the line (through Sol) with slope 67.823 degrees. In this case, the method sought (P...
Linear Fit to Planet Positions
An astounding alignment occurs 2048/5/28 with the inner 5 planets having heliocentric longitudes (in degrees): 248.229, 66.631, 246.967, 249.605, 67.684. The planets are at most 0.875 degrees from the line (through Sol) with slope 67.823 degrees. In this case, the method sought (PA) would give: PA(248.229, 66.631...
[ "Dumb as dirt method didn't work for reasons that should have been obvious: your data can be pathological for any choice of half-plane to map to. I'm going to recommend a least squares approach, but you do need to deal with the radial ambiguity.\nThat means the function that you are looking to minimize is:\n\\sum (...
[ 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002065550_javascript_python.txt
Q: Does Pythoncard have an on change event? I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though. A: Pythoncard is built on wxPython, and wxPython has a text change event. I know nothing about Pythoncard, but in wxPython one w...
Does Pythoncard have an on change event?
I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though.
[ "Pythoncard is built on wxPython, and wxPython has a text change event. I know nothing about Pythoncard, but in wxPython one would use:\n t1 = wx.TextCtrl(self, -1, \"some text\", size=(125, -1)) # to make the text control\n self.Bind(wx.EVT_TEXT, self.OnText, t1) # your OnText method handles the event\n\n...
[ 1, 1 ]
[]
[]
[ "event_handling", "events", "pycard", "python", "pythoncard" ]
stackoverflow_0000984263_event_handling_events_pycard_python_pythoncard.txt
Q: How to capture keystrokes with a Python daemon? I'm trying to write a POS-style application for a Sheevaplug that does the following: Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that) Doesn't require X Runs in the background...
How to capture keystrokes with a Python daemon?
I'm trying to write a POS-style application for a Sheevaplug that does the following: Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that) Doesn't require X Runs in the background (daemon) I've seen examples of code that will wait ...
[ "Section 5 of the Linux kernel input documentation describes what each of the values in the event interface means.\n", "the format is explained in the kernel documentation in section 5. Event Interface.\n" ]
[ 2, 1 ]
[]
[]
[ "capture", "keyboard", "linux", "python" ]
stackoverflow_0002066049_capture_keyboard_linux_python.txt
Q: Assigning one of multiple values based on what exists In Perl, if I want to assign $myVar a value of $var1, $var2, or $var3, based on which one evaluates to true, I would code the following: $myVar = $var1 || $var2 || $var3; I am working on separate projects in both Python and PHP, and I have not figured out how ...
Assigning one of multiple values based on what exists
In Perl, if I want to assign $myVar a value of $var1, $var2, or $var3, based on which one evaluates to true, I would code the following: $myVar = $var1 || $var2 || $var3; I am working on separate projects in both Python and PHP, and I have not figured out how to code this situation as concisely in either language. Wha...
[ "Perl 'autovivifies' variables upon first reference (as far as I remember). Python will raise a NameError if a variable doesn't exist. However, you can do something like this. \nvar1 = var2 = var3 = None\n# code that might change the value of three variables mentioned above\nmyvar = var1 or var2 or var3\n\nGenerall...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "perl", "php", "python" ]
stackoverflow_0002058544_perl_php_python.txt
Q: Complex Django query over foreign keys I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category". class Category(models.Model): name = models.CharField(_("Name"), max_length=100) slug = models.SlugField(_("Slug"), max_le...
Complex Django query over foreign keys
I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category". class Category(models.Model): name = models.CharField(_("Name"), max_length=100) slug = models.SlugField(_("Slug"), max_length=100, unique=True) class Article(models...
[ "Article.objects.filter(archived=True).order_by('category')\n\ni am editing this to get more info to try and help out. \ngiven:\n\ncat1\n\n\nart1\nart2-archived\nart3\n\ncat2\n\n\nart4\nart5\nart6-archived\n\ncat3\n\n\nart7-archived\nart8-archived\nart9\n\n\nwhat would you want your queryset to contain?\n", "\n\n...
[ 3, 3, 2 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0002028440_django_django_orm_python.txt
Q: Dynamic form field generation in Django templates I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. I am sending a hash to a template that contains the following values {'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.84403299999999...
Dynamic form field generation in Django templates
I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. I am sending a hash to a template that contains the following values {'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.844032999999996, u'place': u'1053 Bowring Cres, Milton, ON L9T, CA', ...
[ "if info['user'] == username:\n locations = (json.loads(info['locations']) +\n [{'place': '', 'description': ''}] * 5)[:5]\n\n return {'date': info['date'], 'locations': locations}\n\n", "(a)\nid=\"id_location_{{ forloop.counter }}\"\n\n" ]
[ 2, 2 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002066181_django_python_templates.txt
Q: how to concatenate lists in python? I'm trying to insert a String into a list. I got this error: TypeError: can only concatenate list (not "tuple") to list because I tried this: var1 = 'ThisIsAString' # My string I want to insert in the following list file_content = open('myfile.txt').readlines() new_line_insert ...
how to concatenate lists in python?
I'm trying to insert a String into a list. I got this error: TypeError: can only concatenate list (not "tuple") to list because I tried this: var1 = 'ThisIsAString' # My string I want to insert in the following list file_content = open('myfile.txt').readlines() new_line_insert = file_content[:10] + list(var1) + rss_xm...
[ "try\nfile_content[:10] + [var1] + rss_xml[11:]\n\n", "Lists have an insert method, so you could just use that:\nfile_content.insert(10, var1)\n\n", "It's important to note the \"list(var1)\" is trying to convert var1 to a list. Since var1 is a string, it will be something like:\n\n>>> list('this')\n['t', 'h',...
[ 9, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002066213_python.txt
Q: Python syntax and legibility for sequential steps that are sub-items I like Python's whitespace formatting and legibility. But can you, or is there a common/standard way of delimiting blocks of code that are not to be indented, ie do not belong in nested loops? I have two parts of a procedure that belong inside a ...
Python syntax and legibility for sequential steps that are sub-items
I like Python's whitespace formatting and legibility. But can you, or is there a common/standard way of delimiting blocks of code that are not to be indented, ie do not belong in nested loops? I have two parts of a procedure that belong inside a main header. Something like step 2 has parts 2.1 and parts 2.2. Commenting...
[ "Put them in separate functions.\n", "You should not have long functions in Python. Take whitespace dilemmas as a hint.\n", "What's wrong with function definitions?\ndef section1( ... ):\n\ndef section2( ... ):\n\ndef overall( ... ):\n section1()\n section2()\n\nIf it's so huge that indentation is require...
[ 5, 4, 3, 1, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002066595_python_syntax.txt
Q: Unknown Authn provider: wsgi ... fail! I have working wsgi authentication on another server, however a second server is not accepting the same configuration and errors upon reload with the message: Syntax error on line 12 of /etc/apache2/sites-enabled/mydomain.com Unknown Authn provider: wsgi ... fail Here is...
Unknown Authn provider: wsgi ... fail!
I have working wsgi authentication on another server, however a second server is not accepting the same configuration and errors upon reload with the message: Syntax error on line 12 of /etc/apache2/sites-enabled/mydomain.com Unknown Authn provider: wsgi ... fail Here is the relevant portion of the config file (li...
[ "It turned out to be a wsgi version difference.\n" ]
[ 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0002065761_apache_mod_wsgi_python_wsgi.txt
Q: Accessing parallel arrays in Django templates? My view code looks basically like this: context = Context() context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f'] context['other_values'] = [4, 8, 15, 16, 23, 42] I would like my template code to look like this: {% for some in some_values %} {% with index as fo...
Accessing parallel arrays in Django templates?
My view code looks basically like this: context = Context() context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f'] context['other_values'] = [4, 8, 15, 16, 23, 42] I would like my template code to look like this: {% for some in some_values %} {% with index as forloop.counter0 %} {{ some }} : {{ other_values....
[ "zip(some_values, other_values), then use it in template\nfrom itertools import izip\nsome_values = ['a', 'b', 'c', 'd', 'e', 'f']\nother_values = [4, 8, 15, 16, 23, 42]\ncontext['zipped_values'] = izip(some_values, other_values)\n\n{% for some, other in zipped_values %}\n {{ some }}: {{ other }} <br/>\n{% endf...
[ 8 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002067036_django_django_templates_python.txt
Q: Does Django logs usernames internally All.. I have a Django site and to access it all the users have to go through the login page. My question is when a user is given a access through the login page to enter the site.Does Django logs the username in any of the Django internal tables.... Thanks....... A: Yes, the...
Does Django logs usernames internally
All.. I have a Django site and to access it all the users have to go through the login page. My question is when a user is given a access through the login page to enter the site.Does Django logs the username in any of the Django internal tables.... Thanks.......
[ "Yes, the last_login column of the user's record in table auth_user is updated with the date/time of the successful login.\n" ]
[ 2 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002067185_django_logging_python.txt
Q: django select query--how do I make this? class Content(models.Model): .....stuff here class Score(models.Model): content = models.OneToOneField(Content, primary_key=True) real_score = models.IntegerField(default=0) This is my database schema. As you can see, each Content has a score. How do I do thi...
django select query--how do I make this?
class Content(models.Model): .....stuff here class Score(models.Model): content = models.OneToOneField(Content, primary_key=True) real_score = models.IntegerField(default=0) This is my database schema. As you can see, each Content has a score. How do I do this: Select all from Content where Content's Sco...
[ "Content.objects.filter(score__real_score=1)\n" ]
[ 5 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002067268_database_django_mysql_python.txt
Q: PYTHONPATH issue on a Production server and Namespace challenge I'm really confused by some errors I'm getting as I'm trying to put an App into production. Everything works fine on the development machine, but I can't syncdb or enter the Django shell on the Production server. I'm getting an error when forum.models...
PYTHONPATH issue on a Production server and Namespace challenge
I'm really confused by some errors I'm getting as I'm trying to put an App into production. Everything works fine on the development machine, but I can't syncdb or enter the Django shell on the Production server. I'm getting an error when forum.models.py is attempts to import forum.managers.py because the models aren't...
[ "Your problem is you do:\nfrom forum.managers import * (at line 18 models.py)\nfrom forum.models import * (at line 6 managers.py)\nHow can that ever work? Try flattening this out (do the imports by hand copying and pasting into a new file) and you'll see why, by the time it executes the line \"objects = TagManager(...
[ 1 ]
[]
[]
[ "django", "production", "python", "pythonpath" ]
stackoverflow_0002066426_django_production_python_pythonpath.txt
Q: Django: iterating over the options in a custom select field I'm using a custom MM/YY field and widget based on this example. I want to iterate over the individual month and year options defined in the widget class in order to apply "selected='selected'" to the MM/YY value that corresponds with the MM/YY value sto...
Django: iterating over the options in a custom select field
I'm using a custom MM/YY field and widget based on this example. I want to iterate over the individual month and year options defined in the widget class in order to apply "selected='selected'" to the MM/YY value that corresponds with the MM/YY value stored in the database. This seems like such a messy way of doing t...
[ "The magic of django forms is that you don't need to do all that. By calling the form's select field by name, it will render it and select the right option as based on initial/instance data passed into the form on instantation.\n{{form.working_month}}\n\nIf you're still having troubles, can you post the form class ...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0001975411_django_django_forms_django_templates_python.txt
Q: Get a C reference to an embedded python function by name? Assuming I have some embedded python code containing a function foo, what is the best way to get a reference to that function (for use with PyObject_CallObject)? One way is to have some function register each function along with the function name either man...
Get a C reference to an embedded python function by name?
Assuming I have some embedded python code containing a function foo, what is the best way to get a reference to that function (for use with PyObject_CallObject)? One way is to have some function register each function along with the function name either manually or through use of reflection. This seems like overkill. A...
[ "Read the section in the documentation about embedding Python. I guess you have a reference to the module containing the function.\nAt the end there is an example which shows how to get a function reference out of an object.\npFunc = PyObject_GetAttrString(pModule, argv[2]);\n/* pFunc is a new reference */\n\nif (p...
[ 1 ]
[]
[]
[ "c", "embedded_language", "python" ]
stackoverflow_0002067496_c_embedded_language_python.txt
Q: Utilities or libraries for finding most closely matched binary file I would like to be able to compare a binary file X to a directory of other binary files and find which other file is most similar to X. The nature of the data is such that identical chunks will exist between files, but possibly shifted in locati...
Utilities or libraries for finding most closely matched binary file
I would like to be able to compare a binary file X to a directory of other binary files and find which other file is most similar to X. The nature of the data is such that identical chunks will exist between files, but possibly shifted in location. The files are all 1MB in size, and there are about 200 of them. I w...
[ "Here's a simple perl script which more or less tries to do exactly that.\nEdit: Also have a look at the following stackoverflow thread.\n" ]
[ 0 ]
[]
[]
[ "diff", "python", "utility" ]
stackoverflow_0002067628_diff_python_utility.txt
Q: deploying django to UserDir I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D I come from PHP background and I deploy my PHP scripts by uploading them to my public_html dir and everything shows ...
deploying django to UserDir
I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D I come from PHP background and I deploy my PHP scripts by uploading them to my public_html dir and everything shows up on http://ourserver.com/~myuse...
[ "If mod_python installed, first see if you can actually use it without needing administrator to do anything. Read:\nhttp://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking\nUnless you are a trusted user or administrators don't know what they are doing, they shouldn't be allowing you to use mod_pytho...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0001491102_apache_django_python.txt
Q: How to fetch some data conditionally with Python and Beautiful Soup Sorry if you feel like this has been asked but I have read the related questions and being quite new to Python I could not find how to write this request in a clean manner. For now I have this minimal Python code: from mechanize import Browser fr...
How to fetch some data conditionally with Python and Beautiful Soup
Sorry if you feel like this has been asked but I have read the related questions and being quite new to Python I could not find how to write this request in a clean manner. For now I have this minimal Python code: from mechanize import Browser from BeautifulSoup import BeautifulSoup import re import urllib2 br = Br...
[ "Searching for the players using your method will work, but will return 3 results per player. Easier to search for the table itself, and then iterate over the rows (except the header):\ntable=soup.find('table', 'bioTableAlt')\nfor row in table.findAll('tr')[1:]:\n cells = row.findAll('td')\n #retreieve data f...
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002067710_beautifulsoup_python.txt
Q: Efficient method to store Python dictionary on disk? What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the pickle module. Edit: Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain...
Efficient method to store Python dictionary on disk?
What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the pickle module. Edit: Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain mutable objects that will hold information to be parsed a...
[ "shelve is pretty nice as well\nor this persistent dictionary recipe\nfor a convenient method that keeps your objects synchronized with storage, there's the ORM SQLAlchemy for python\nif you just need a way to store string values by some key, theres the dbm.ndbm and dbm.gnu modules.\nif you need a hyper efficient, ...
[ 9, 2 ]
[]
[]
[ "dictionary", "disk", "pickle", "python" ]
stackoverflow_0002067749_dictionary_disk_pickle_python.txt
Q: python list of dicts how to merge key:value where values are same? Python newb here looking for some assistance... For a variable number of dicts in a python list like: list_dicts = [ {'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'}, {'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'}, {'id':'00...
python list of dicts how to merge key:value where values are same?
Python newb here looking for some assistance... For a variable number of dicts in a python list like: list_dicts = [ {'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'}, {'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'}, {'id':'002', 'name':'mary', 'item':'tape', 'price':'7.99'}, {'id':'003', 'name':'...
[ "Try to avoid complex nested data structures. I believe people tend to\ngrok them only while they are intensively using the data structure. After the\nprogram is finished, or is set aside for a while, the data structure quickly\nbecomes mystifying.\nObjects can be used to retain or even add richness to the data st...
[ 10, 0, 0 ]
[]
[]
[ "dictionary", "list", "merge", "python" ]
stackoverflow_0002067627_dictionary_list_merge_python.txt
Q: Broken Pipe from subprocess.Popen.communciate() with stdin I'm having a strange issue when using subprocess.Popen.communicate(). For background, I want to execute an application from my python script. When I run the program from the command line, I do it like this (UNIX): $ echo "input text" | /path/to/myapp F...
Broken Pipe from subprocess.Popen.communciate() with stdin
I'm having a strange issue when using subprocess.Popen.communicate(). For background, I want to execute an application from my python script. When I run the program from the command line, I do it like this (UNIX): $ echo "input text" | /path/to/myapp From my script, I also want to pipe the input into the applicatio...
[ "Your observation suggests that myapp is terminating without reading (all of the) input. Not knowing anything about myapp, that's hard to confirm, but consider for example\n$ echo 'hello world' | tr 'l' 'L'\nheLLo worLd\n\nnow...:\n>>> cmd = ['/usr/bin/tr']\n>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, st...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002067852_python.txt
Q: Passing arguments into SUDS client statement I am using SUDS (Like SOAP) to test WSDL files. The methods contain types that are linked to further functions. I am not sure how to access the variables stored in the types that are displayed. Some sample code is below: from suds.client import Client client=Client('htt...
Passing arguments into SUDS client statement
I am using SUDS (Like SOAP) to test WSDL files. The methods contain types that are linked to further functions. I am not sure how to access the variables stored in the types that are displayed. Some sample code is below: from suds.client import Client client=Client('http://eample.wsdl') print client response is: Port...
[ "Try to invoke the method on the service:\nfrom suds.client import Client\nclient=Client('http://eample.wsdl')\nres = client.service.AbsoluteMove(profile_token, destination, speed)\nprint res\n\nYou'll need to determine what values to put in for those arguments to the AbsoluteMove method.\n", "Client.factory.crea...
[ 3, 1 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0002065088_python_soap_suds.txt
Q: time complexity of variable loops i want to try to calculate the O(n) of my program (in python). there are two problems: 1: i have a very basic knowledge of O(n) [aka: i know O(n) has to do with time and calculations] and 2: all of the loops in my program are not set to any particular value. they are based on the...
time complexity of variable loops
i want to try to calculate the O(n) of my program (in python). there are two problems: 1: i have a very basic knowledge of O(n) [aka: i know O(n) has to do with time and calculations] and 2: all of the loops in my program are not set to any particular value. they are based on the input data.
[ "The n in O(n) means precisely the input size. So, if I have this code:\ndef findmax(l):\n maybemax = 0\n for i in l:\n if i > maybemax:\n maybemax = i\n return maybemax\n\nThen I'd say that the complexity is O(n) -- how long it takes is proportional to the input size (since the loop loop...
[ 4, 1 ]
[]
[]
[ "algorithm", "big_o", "python" ]
stackoverflow_0002068591_algorithm_big_o_python.txt
Q: mysqldb pulls whole query result in one chunk always even if I just do a fetchone? So if I do import MySQLdb conn = MySQLdb.connect(...) cur = conn.cursor() cur.execute("SELECT * FROM HUGE_TABLE") print "hello?" print cur.fetchone() It looks to me that MySQLdb gets the entire huge table before it gets to t...
mysqldb pulls whole query result in one chunk always even if I just do a fetchone?
So if I do import MySQLdb conn = MySQLdb.connect(...) cur = conn.cursor() cur.execute("SELECT * FROM HUGE_TABLE") print "hello?" print cur.fetchone() It looks to me that MySQLdb gets the entire huge table before it gets to the "print". I previously assumed it did some sort of "cursor/state" lazy retrieval in th...
[ "In the _mysql module, use the following call:\nconn.use_result()\n\nThat tells the connection you want to fetch rows one by one, leaving the remainder on the server (but leaving the cursor open).\nThe alternative (and the default) is:\nconn.store_result()\n\nThis tells the connection to fetch the entire result set...
[ 4, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002067529_mysql_python.txt
Q: Python Function Reference There're tons of apps/widgets for PHP function reference and even for Ruby but I'm shocked to find there is nothing available for a popular language like Python (besides the official online documentation ofcourse). Is there really not a single handy reference widget/app available for Pyt...
Python Function Reference
There're tons of apps/widgets for PHP function reference and even for Ruby but I'm shocked to find there is nothing available for a popular language like Python (besides the official online documentation ofcourse). Is there really not a single handy reference widget/app available for Python? I have 'Pocket Reference' ...
[ "Python libraries have (or should have) built in documentation through docstrings. Also, python code is (mostly) very readable, and reading the source (.py or even .c) is actually the preferred way for many developers to get the information they're looking for, especially since some corner cases may not even be doc...
[ 1, 0, 0 ]
[ "I develop on Mac OS.\nI have all the Python documentation directly available through a desktop app.\nThe app is called Safari. I bookmark http://docs.python.org/index.html\nIt's available as a desktop app.\n" ]
[ -1 ]
[ "documentation", "macos", "python", "reference", "widget" ]
stackoverflow_0002068486_documentation_macos_python_reference_widget.txt
Q: Serving up snippets of html and using urlfetch I'm trying to "modularize" a section of an appengine website where a profile is requested as a small hunk of pre-rendered html Sending a request to /userInfo?id=4992 sends down some html like: <div> (image of john) John Information about this user </d...
Serving up snippets of html and using urlfetch
I'm trying to "modularize" a section of an appengine website where a profile is requested as a small hunk of pre-rendered html Sending a request to /userInfo?id=4992 sends down some html like: <div> (image of john) John Information about this user </div> So, from my google appengine code, I need to be...
[ "You're currently serializing urlfetch requests, which ends up summing their wait times and may easily push you beyond your latency deadline. I'm afraid that you'll need to switch to async urlfetch requests -- an advanced technique which may suit your architecture better!\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0002069465_google_app_engine_python_urlfetch.txt
Q: read multiple files using multiprocessing I need to read some very huge text files (100+ Mb), process every lines with regex and store the data into a structure. My structure inherits from defaultdict, it has a read(self) method that read self.file_name file. Look at this very simple (but not real) example, I'm no...
read multiple files using multiprocessing
I need to read some very huge text files (100+ Mb), process every lines with regex and store the data into a structure. My structure inherits from defaultdict, it has a read(self) method that read self.file_name file. Look at this very simple (but not real) example, I'm not using regex, but I'm splitting lines: import...
[ "You're probably hitting two problems.\nOne of them was mentioned: you're reading multiple files at once. Those reads will end up being interleaved, causing disk thrashing. You want to read whole files at once, and then only multithread the computation on the data.\nSecond, you're hitting the overhead of Python's...
[ 5, 0, 0 ]
[]
[]
[ "multiprocessing", "performance", "python" ]
stackoverflow_0002068645_multiprocessing_performance_python.txt
Q: Help in Converting Small Python Code to PHP please i need some help in converting a python code to a php syntax the code is for generating an alphanumeric code using alpha encoding the code : def mkcpl(x): x = ord(x) set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" for c in...
Help in Converting Small Python Code to PHP
please i need some help in converting a python code to a php syntax the code is for generating an alphanumeric code using alpha encoding the code : def mkcpl(x): x = ord(x) set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" for c in set: d = ord(c)^x if chr(d) ...
[ "i will help you a little. For the rest of it, please read up on the documentation.\nfunction mkcpl($x){\n $x=ord($x);\n $set=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n $set=str_split($set);\n foreach($set as $c){\n $d=ord($c)^$x;\n if( in_array( chr($d) ,$set ) ...
[ 4, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002069352_php_python.txt
Q: 'Invalid Key' error from Paramiko I'm trying to set up Fabric for deploying my Python web application and Paramiko is barfing on my private RSA key. I had been using my key successfully for 6 months, so I know it's good. In case having a passphrase was the problem, I just made a new key with no passphrase and st...
'Invalid Key' error from Paramiko
I'm trying to set up Fabric for deploying my Python web application and Paramiko is barfing on my private RSA key. I had been using my key successfully for 6 months, so I know it's good. In case having a passphrase was the problem, I just made a new key with no passphrase and still get the error. Help?
[ "I don't know if this helps you but here's how I set my SSH user/key in fabric.\nenv.user = \"username\"\nenv.key_filename = \"/path/to/ssh/keyfile\"\n\nAnd it seems to work fine.\n" ]
[ 1 ]
[]
[]
[ "fabric", "paramiko", "python", "ssh" ]
stackoverflow_0002045880_fabric_paramiko_python_ssh.txt
Q: ImportError: cannot import name NumpyTest I am trying to read a *.wav file using scipy. I do it in the following way: import scipy.io x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') As a result I get the following error message: Traceback (most recent call last): File "test3.py", line 1, in <m...
ImportError: cannot import name NumpyTest
I am trying to read a *.wav file using scipy. I do it in the following way: import scipy.io x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') As a result I get the following error message: Traceback (most recent call last): File "test3.py", line 1, in <module> import scipy.io File "/usr/lib/pyt...
[ "Looks like you have upgraded your numpy version but haven't installed a corresponding scipy version.\n", "Do you have numpy installed? The package is most likely called numpy or python-numpy if you are running Linux\nIf your OS package manager does not have numpy package, download it from here\n" ]
[ 1, 0 ]
[]
[]
[ "importerror", "numpy", "python", "scipy", "wav" ]
stackoverflow_0002063124_importerror_numpy_python_scipy_wav.txt
Q: In optparse module - command line option parser, how to confirm if an option was not provided? From Python docs: "Option.dest : If the option’s action implies writing or modifying a value somewhere, this tells optparse where to write it: dest names an attribute of the options object that optparse builds as it pars...
In optparse module - command line option parser, how to confirm if an option was not provided?
From Python docs: "Option.dest : If the option’s action implies writing or modifying a value somewhere, this tells optparse where to write it: dest names an attribute of the options object that optparse builds as it parses the command line." Can we put some check on the name of the attribute (dest) to check if it's val...
[ "You could use a default value of None for such options, which cannot be entered on the command line. Then you can check like\nif opts.optional_value is None:\n # action for option not given\nelse:\n # use value from command line\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002069998_python.txt
Q: Python parallel processing libraries Python seems to have many different packages available to assist one in parallel processing on an SMP based system or across a cluster. I'm interested in building a client server system in which a server maintains a queue of jobs and clients (local or remote) connect and run j...
Python parallel processing libraries
Python seems to have many different packages available to assist one in parallel processing on an SMP based system or across a cluster. I'm interested in building a client server system in which a server maintains a queue of jobs and clients (local or remote) connect and run jobs until the queue is empty. Of the pack...
[ "Have a go with ParallelPython. Seems easy to use, and should provide the jobs and queues interface that you want.\n", "There are also now two different Python wrappers around the map/reduce framework Hadoop:\nhttp://code.google.com/p/happy/\nhttp://wiki.github.com/klbostee/dumbo\nMap/Reduce is a nice development...
[ 2, 1, 0, 0 ]
[]
[]
[ "cluster_computing", "python", "scientific_computing" ]
stackoverflow_0002051984_cluster_computing_python_scientific_computing.txt
Q: python app to exe not working on WinSRV2003 I created little app for sending out emails when something is wrong with server. Used py2exe to create exe file. While it is works absolutely fine on Win7 i have problems with running it on WinSRV2003. I do not believe that it has something to do with code itself. Pleas...
python app to exe not working on WinSRV2003
I created little app for sending out emails when something is wrong with server. Used py2exe to create exe file. While it is works absolutely fine on Win7 i have problems with running it on WinSRV2003. I do not believe that it has something to do with code itself. Please see imports below import pyodbc, sys, smtplib, ...
[ "I'd say this is a missing DLL's problem. You should check and see the DLL's your application bundles ( or presumes to exist on the target computer ). I think you can do that with the depends.exe that comes with Visual Studio.\nEDIT: I just remembered. Make sure you run py2exe with a Python 2.5 installation. The 2....
[ 1, 1, 1, 1 ]
[]
[]
[ "py2exe", "python", "windows", "windows_server_2003" ]
stackoverflow_0001707323_py2exe_python_windows_windows_server_2003.txt
Q: A clean algorithm for sorting a objects according to defined dependencies? Given a list of classes inheriting from this base: class Plugin(object): run_after_plugins = () run_before_plugins = () ...and the following rules: Plugins can provide a list of plugins that they must run after. Plugins can provid...
A clean algorithm for sorting a objects according to defined dependencies?
Given a list of classes inheriting from this base: class Plugin(object): run_after_plugins = () run_before_plugins = () ...and the following rules: Plugins can provide a list of plugins that they must run after. Plugins can provide a list of plugins that they must run before. The list of plugins may or may no...
[ "This is called topological sorting.\n\nThe canonical application of\n topological sorting (topological\n order) is in scheduling a sequence of\n jobs or tasks; topological sorting\n algorithms were first studied in the\n early 1960s in the context of the PERT\n technique for scheduling in project\n manageme...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0002065897_algorithm_python.txt
Q: How do I pass a python list in the post query? I want to send some strings in a list in a POST call. eg: www.example.com/?post_data = A list of strings The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings? A: There's no such thing as a "...
How do I pass a python list in the post query?
I want to send some strings in a list in a POST call. eg: www.example.com/?post_data = A list of strings The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?
[ "There's no such thing as a \"list of strings\" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated...
[ 8, 5, 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0000349369_python_web_services.txt
Q: How can I make my Python code stay under 80 characters a line? I have written some Python in which some lines exceed 80 characters in length, which is a threshold I need to stay under. How can I adapt my code to reduce line lengths? A: My current editor (Kate) has been configured to introduce a line break on wor...
How can I make my Python code stay under 80 characters a line?
I have written some Python in which some lines exceed 80 characters in length, which is a threshold I need to stay under. How can I adapt my code to reduce line lengths?
[ "My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of w...
[ 62, 23, 22, 19 ]
[]
[]
[ "pep8", "python" ]
stackoverflow_0002070684_pep8_python.txt
Q: Example for using Python Twisted with File Descriptors I'm looking to use twisted to control communication across Linux pipes (os.pipe()) and fifos (os.mkfifo()) between a master process and a set of slave processes. While I'm positive tat it's possible to use twisted for these types of file descriptors (after all...
Example for using Python Twisted with File Descriptors
I'm looking to use twisted to control communication across Linux pipes (os.pipe()) and fifos (os.mkfifo()) between a master process and a set of slave processes. While I'm positive tat it's possible to use twisted for these types of file descriptors (after all, twisted is great for tcp sockets which *nix abstracts away...
[ "You can use reactor.spawnProcess to set up arbitrary file descriptor mappings between a parent process and a child process it spawns. For example, to run a program and give it two extra output descriptors (in addition to stdin, stdout, and stderr) with which it can send bytes back to the parent process, you would...
[ 12, -3 ]
[]
[]
[ "file_descriptor", "mkfifo", "pipe", "python", "twisted" ]
stackoverflow_0002069262_file_descriptor_mkfifo_pipe_python_twisted.txt
Q: why i get this traceback? This is part of my code: if ind_1<>0: rbrcol=[] brdod1=[] for i in range(27): if Add_Cyc_1[1,i]!=0: rbrcol.append(Add_Cyc_1[0,i]) brdod1.append(Add_Cyc_1[1,i]) Probrani_1=vstack((rbrcol,brdod1)) pok=0 for i in (rbrcol): pok+=1 broj1=...
why i get this traceback?
This is part of my code: if ind_1<>0: rbrcol=[] brdod1=[] for i in range(27): if Add_Cyc_1[1,i]!=0: rbrcol.append(Add_Cyc_1[0,i]) brdod1.append(Add_Cyc_1[1,i]) Probrani_1=vstack((rbrcol,brdod1)) pok=0 for i in (rbrcol): pok+=1 broj1=0 for j in range(21): if...
[ "I think the real problem is the if at the very top. Your indenting is incorrect - the code as written won't run because the line after the if is not indented.\nAssuming it is indented in the original code, then rbrcol is not initialized if ind_1 is 0 and as ghostdog says if the if statement never fires, then rbrco...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002071895_python.txt
Q: Access models in other project in a Django view cause "table doesn't exist" error Base project structure baseproject baseapp models.py class BaseModel(models.Model) ... Other project structure: project app views.py urls.py project.app.views.py import os os....
Access models in other project in a Django view cause "table doesn't exist" error
Base project structure baseproject baseapp models.py class BaseModel(models.Model) ... Other project structure: project app views.py urls.py project.app.views.py import os os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' from django.conf import settings...
[ "You are fighting against the framework here, and you'll be better off if you rethink your architecture. Django is built around the assumption that a project = a given set of INSTALLED_APPS, and the project settings name a database to which those apps are synced. It's not clear here what problem you have with just ...
[ 8 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0002069254_django_model_python.txt