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: does someone know how to show content on screen (covering up any window) using Ruby or Python? using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen ...
does someone know how to show content on screen (covering up any window) using Ruby or Python?
using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like ...
[ "You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby.\nAlternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure...
[ 4, 2, 1 ]
[]
[]
[ "python", "ruby", "user_interface" ]
stackoverflow_0000872737_python_ruby_user_interface.txt
Q: Python list of objects with random attributes (Edit: randrange is just random.randrange, I didn't write my own RNG) I'm trying to create a list of instances of a class I defined. Here's the entire class (by request): from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 ...
Python list of objects with random attributes
(Edit: randrange is just random.randrange, I didn't write my own RNG) I'm trying to create a list of instances of a class I defined. Here's the entire class (by request): from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 def __init__(self, width=100, height=100): ...
[ "Move the creation of the array into the __init__ method.\nYou're working with a shared array among all objects.\nThe reason the first shows different is that you print the contents of that array before you construct a new Poly object and thus trample over the array contents. If you had kept them around and inspect...
[ 6, 4, 2 ]
[ "ok here is the culprit\npoints = [[0]] * 8\nit assigns same list ([0]) 8 times instead you should do something like\npoints = []\nfor i in range(8):\n points.append([])\n\n" ]
[ -1 ]
[ "python", "random" ]
stackoverflow_0000874121_python_random.txt
Q: Print space after each word what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in ...
Print space after each word
what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in Java, Python, or Ruby.
[ "Well, in Python it will be straightforward using join:\nvalues = [\"this\", \"is\", \"your\", \"array\"]\nresult = \" \".join(values)\n\n", "Yes, this is what join was made for. Here is the Ruby version:\n[\"word\", \"another\", \"word\"].join(\" \")\n\n<flamebait> As you can see, Ruby makes join a method on Arr...
[ 13, 7, 1, 1, 1, 1, 0, 0 ]
[ "Let's not forget the good old-fashioned\n for s in strArray do\n print s\n print \" \"\n\n" ]
[ -3 ]
[ "java", "python", "ruby", "string" ]
stackoverflow_0000873790_java_python_ruby_string.txt
Q: List of non-datastore types in AppEngine? I'm building an AppEngine model class. I need a simple list of tuples: class MyTuple(object): field1 = "string" field2 = 3 class MyModel(db.Model): the_list = db.ListProperty(MyTuple) This does not work, since AppEngine does not accept MyTuple as a valid field. Sol...
List of non-datastore types in AppEngine?
I'm building an AppEngine model class. I need a simple list of tuples: class MyTuple(object): field1 = "string" field2 = 3 class MyModel(db.Model): the_list = db.ListProperty(MyTuple) This does not work, since AppEngine does not accept MyTuple as a valid field. Solutions I can think of: Make MyTuple extend db....
[ "In app-engine-patch there's a FakeModelListProperty and FakeModel (import both from ragendja.dbutils). Derive MyTuple from FakeModel and set fields = ('field1', 'field2'). Those fields will automatically get converted to JSON when stored in the list, so you could manually edit them in a textarea. Of course, this o...
[ 1 ]
[]
[]
[ "google_app_engine", "orm", "python" ]
stackoverflow_0000874122_google_app_engine_orm_python.txt
Q: Python ctypes and function pointers This is related to my other question, but I felt like I should ask it in a new question. Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use CFUNCTYPE to prototype them, and then you use the prototype() function to create them. T...
Python ctypes and function pointers
This is related to my other question, but I felt like I should ask it in a new question. Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use CFUNCTYPE to prototype them, and then you use the prototype() function to create them. The problem I have with this is that I fig...
[ "According to the ctypes callback docs you can define python function\ndef my_callback(a, p, frame, p1, p2)\n pass\n\nand then create a pointer to a C callable function like this:\ncallback = write_callback_prototype(my_callback)\n\nThis function pointer can then be passed into FLAC\n", "\nThe problem that I h...
[ 7, 1 ]
[]
[]
[ "ctypes", "function_pointers", "python" ]
stackoverflow_0000874245_ctypes_function_pointers_python.txt
Q: Python: load words from file into a set I have a simple text file with several thousands of words, each in its own line, e.g. aardvark hello piper I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): my_set = set(open('filename....
Python: load words from file into a set
I have a simple text file with several thousands of words, each in its own line, e.g. aardvark hello piper I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): my_set = set(open('filename.txt')) The above code produces a set with th...
[ "The strip() method of strings removes whitespace from both ends.\nset(line.strip() for line in open('filename.txt'))\n\n", "Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your fi...
[ 75, 16, 4, 2, 1, 1 ]
[]
[]
[ "python", "text_files" ]
stackoverflow_0000874017_python_text_files.txt
Q: How do I put a scrollbar inside of a gtk.ComboBoxEntry? I have a Combobox with over a hundred of entries and it is very awkward to skim through with out a scrollbar. alt text http://img211.imageshack.us/img211/6972/screenshotprubapy.png I want to do exactly what is in the picture. With the scrollbar on the right s...
How do I put a scrollbar inside of a gtk.ComboBoxEntry?
I have a Combobox with over a hundred of entries and it is very awkward to skim through with out a scrollbar. alt text http://img211.imageshack.us/img211/6972/screenshotprubapy.png I want to do exactly what is in the picture. With the scrollbar on the right so It'd be easier to move through the entries. I used gtk.Comb...
[ "import pygtk\nimport gtk\nimport gobject\n\ndef window_delete_event(*args):\n return False\n\ndef window_destroy(*args):\n gtk.main_quit()\n\nif __name__ == '__main__':\n win = gtk.Window()\n\n # combo's model\n model = gtk.ListStore(gobject.TYPE_STRING)\n for n in xrange(100):\n model.app...
[ 2 ]
[]
[]
[ "pygtk", "python", "user_interface" ]
stackoverflow_0000873328_pygtk_python_user_interface.txt
Q: wxPython: Path problems when exporting a bitmap I have a module which starts a wxPython app, which loads a wx.Bitmap from file for use as a toolbar button. It looks like this: wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY). All works well when I run that module by itself, but when I try to import and run it from...
wxPython: Path problems when exporting a bitmap
I have a module which starts a wxPython app, which loads a wx.Bitmap from file for use as a toolbar button. It looks like this: wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY). All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory...
[ "\"images\\new.png\" is a relative path, so when bitmap gets loaded it will depened what is the cur dir\nso either you set cur dir\nos.chdir(\"location to images folder\")\n\nor \nhave a function which loads relative to your program e.g.\ndef getProgramFolder():\n moduleFile = __file__\n moduleDir = os.path.s...
[ 2, 1 ]
[]
[]
[ "path", "python", "wxpython" ]
stackoverflow_0000874625_path_python_wxpython.txt
Q: wxPython launches my app twice when importing a sub-package I'm sorry for the verbal description. I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file r...
wxPython launches my app twice when importing a sub-package
I'm sorry for the verbal description. I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file rundemo.py in a folder which contains the garlicsimwx package, whi...
[ "I think you have code in one of your modules that looks like this:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(...):\n ...\n\nframe = MyFrame(...)\n\nThe frame will be created when this module is first imported. To prevent that, use the common Python idiom:\nimport wx\n\nclass MyFrame(wx.Frame):...
[ 4, 0, 0 ]
[]
[]
[ "import", "python", "wxpython" ]
stackoverflow_0000874856_import_python_wxpython.txt
Q: Receiving 16-bit integers in Python I'm reading 16-bit integers from a piece of hardware over the serial port. Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data? A: Try using the struct module: import...
Receiving 16-bit integers in Python
I'm reading 16-bit integers from a piece of hardware over the serial port. Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data?
[ "Try using the struct module:\nimport struct\n# read 2 bytes from hardware as a string\ns = hardware.readbytes(2)\n# h means signed short\n# < means \"little-endian, standard size (16 bit)\"\n# > means \"big-endian, standard size (16 bit)\"\nvalue = struct.unpack(\"<h\", s) # hardware returns little-endian\nvalue =...
[ 24 ]
[]
[]
[ "integer", "python" ]
stackoverflow_0000875046_integer_python.txt
Q: How to print a list, dict or collection of objects, in Python I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implemen...
How to print a list, dict or collection of objects, in Python
I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print functio...
[ "Yes, you need to use __repr__. A quick example of its behavior:\n>>> class Foo:\n... def __str__(self):\n... return '__str__'\n... def __repr__(self):\n... return '__repr__'\n...\n>>> bar = Foo()\n>>> bar \n__repr__\n>>> print bar \n__str__\n>>> repr(bar)\n'__repr__'\n>>> str(bar)\n...
[ 24, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000875074_list_python.txt
Q: Timesheet Program to Track Days/Hours worked? Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Lang...
Timesheet Program to Track Days/Hours worked?
Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)
[ "A dictionary is a good way to store the data while your program is running.\nThere are a number of ways to add some data permanence (so it's around after you close the program). The Python modules pickle and shelve are useful and easy to use. One issue with these is that you can't easily inspect the data outside...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000873564_python.txt
Q: Admin privileges for script how can i check admin-privileges for my script during running? A: The concept of "admin-privileges" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with "traditional" access control model, getting the effective user id (available in ...
Admin privileges for script
how can i check admin-privileges for my script during running?
[ "The concept of \"admin-privileges\" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with \"traditional\" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know...
[ 7, 5, 3 ]
[]
[]
[ "python", "root", "sudo", "unix" ]
stackoverflow_0000874476_python_root_sudo_unix.txt
Q: Daemon python wrapper "subprocess I/O timed out", need some directions I am not very familiar with the way of creating a daemon in Python, therefore wheb trying to install and run a third party open source TeX Python Wrapper i got bite by an error i do nor really understand. I added some print to help debugging. T...
Daemon python wrapper "subprocess I/O timed out", need some directions
I am not very familiar with the way of creating a daemon in Python, therefore wheb trying to install and run a third party open source TeX Python Wrapper i got bite by an error i do nor really understand. I added some print to help debugging. The faulty one is called texdp.py When i run mathrand which calls texdp serve...
[ "The timeout is based on the select call \nreadable, writable = select(output_fds, input_fds, [], 0.1)[0:2]\n\nThe timeout is 0.1 seconds. Is this appropriate? \nThe variable names are murky (\"pointer\" makes little sense in Python). However, it appears that if nothing happens on 0.1 seconds, a \"timeout\" is r...
[ 2 ]
[]
[]
[ "daemon", "python", "tex" ]
stackoverflow_0000875190_daemon_python_tex.txt
Q: PyQt: splash screen while loading "heavy" libraries My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows). I'm wondering whether it's feasible to show a splash screen while t...
PyQt: splash screen while loading "heavy" libraries
My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows). I'm wondering whether it's feasible to show a splash screen while the matplotlib library is being loaded. Where does the act...
[ "Yes, loading the module takes place at the line where the import statement is. If you create your QApplication and show your splash screen before that, you should be able to do what you want -- also you need to call QApplication.processEvents() whenever you need the splash screen to update with a new message.\n" ...
[ 4 ]
[]
[]
[ "matplotlib", "performance", "pyqt", "python" ]
stackoverflow_0000876107_matplotlib_performance_pyqt_python.txt
Q: is there any AES encryption python library that will work well with python 3.0? I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data?? A: I suggest my open-source project slowaes, http://code.google.com/p/slowaes/ -- should be trivial to adapt if it doesn'...
is there any AES encryption python library that will work well with python 3.0?
I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data??
[ "I suggest my open-source project slowaes, http://code.google.com/p/slowaes/ -- should be trivial to adapt if it doesn't work out of the box, as it's pure-Python (and for 128 bits of data, the \"slow\" part shouldn't matter).\n", "To properly encrypt data, you need more than just an encryption algorithm. It's pro...
[ 3, 0 ]
[]
[]
[ "aes", "encryption", "python" ]
stackoverflow_0000876258_aes_encryption_python.txt
Q: How to remove symbols from a string with Python? I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: how much for the maple syrup? $20.99? That's ricidulous!!! into: how much for the maple syrup ...
How to remove symbols from a string with Python?
I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: how much for the maple syrup? $20.99? That's ricidulous!!! into: how much for the maple syrup 20 99 That s ridiculous
[ "One way, using regular expressions:\n>>> s = \"how much for the maple syrup? $20.99? That's ridiculous!!!\"\n>>> re.sub(r'[^\\w]', ' ', s)\n'how much for the maple syrup 20 99 That s ridiculous '\n\n\n\\w will match alphanumeric characters and underscores\n[^\\w] will match anything that's not alphanumeric or...
[ 196, 36, 12 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0000875968_python_regex_string.txt
Q: Django reusable app for like functionality as in friendfeed I am looking to implement "like" functionallity a bit similar as they do in friendfeed. Is there a django reusable app that already does this? Thanks! Nick. A: This sort of thing you should just write yourself from scratch. A 'like' in its most basic fo...
Django reusable app for like functionality as in friendfeed
I am looking to implement "like" functionallity a bit similar as they do in friendfeed. Is there a django reusable app that already does this? Thanks! Nick.
[ "This sort of thing you should just write yourself from scratch. A 'like' in its most basic form is going to be an object with relations to a user and some other object. Look at the contenttypes framework docs to see how to use generic foreign keys for this. The only other thing you need to worry about is to make t...
[ 4, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000876898_django_python.txt
Q: Scripts to documents (Matlab's publish functionality in python) Matlab has this great tool called publish. This tool converts a regular matlab script with minimal formatting stuff into structured, nice looking reports (HTML, LateX, RTF). It is capable of handling graphics, mathematical formulae etc. Is there a sim...
Scripts to documents (Matlab's publish functionality in python)
Matlab has this great tool called publish. This tool converts a regular matlab script with minimal formatting stuff into structured, nice looking reports (HTML, LateX, RTF). It is capable of handling graphics, mathematical formulae etc. Is there a similar tool for Python?
[ "There's pyreport. It captures the \"captures its output, compiling it to a pretty report in a pdf or an html file\". With this, you can write scripts that print out your source, getting a nice report in the end.\n" ]
[ 5 ]
[]
[]
[ "matlab", "python", "report", "reporting" ]
stackoverflow_0000877145_matlab_python_report_reporting.txt
Q: try... except... except... : how to avoid repeating code I'd like to avoid writting errorCount += 1 in more than one place. I'm looking for a better way than success = False try: ... else: success = True finally: if success: storage.store.commit() else: ...
try... except... except... : how to avoid repeating code
I'd like to avoid writting errorCount += 1 in more than one place. I'm looking for a better way than success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() I'm trying to avoid s...
[ "This look like a possible application of Python's new with statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had.\nRead about it in PEP 343\n", "My suggestion would to write an logError() method that increments errorCount (make it a member variable...
[ 8, 3, 2, 0, 0 ]
[]
[]
[ "dry", "python", "try_catch" ]
stackoverflow_0000877440_dry_python_try_catch.txt
Q: Find the number of 1s in the same position in two arrays I have two lists: A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] I want to find the number of 1s in the same position in both lists. The answer for these arrays would be 2. A: A little shorter and hopefully more pythonic way: >>> A=[0,0,0,1,0,1] >>> B=[0,0,1,1,1,1] ...
Find the number of 1s in the same position in two arrays
I have two lists: A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] I want to find the number of 1s in the same position in both lists. The answer for these arrays would be 2.
[ "A little shorter and hopefully more pythonic way:\n>>> A=[0,0,0,1,0,1]\n>>> B=[0,0,1,1,1,1]\n\nx = sum(1 for a,b in zip(A,B) if (a==b==1))\n>>> x\n2\n\n", "I'm not an expert of Python, but what is wrong with a simple loop from start to end of first array? \nIn C# I would do something like:\nint match=0;\n\nfor (...
[ 19, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000877059_list_python.txt
Q: How should I return interesting values from a with-statement? Is there a better way than using globals to get interesting values from a context manager? @contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() error...
How should I return interesting values from a with-statement?
Is there a better way than using globals to get interesting values from a context manager? @contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() success...
[ "See http://docs.python.org/reference/datamodel.html#context-managers\nCreate a class which holds the success and error counts, and which implements the __enter__ and __exit__ methods.\n", "I still think you should be creating a class to hold you error/success counts, as I said in you last question. I'm guessing...
[ 9, 5, 0 ]
[]
[]
[ "contextmanager", "python", "with_statement" ]
stackoverflow_0000877709_contextmanager_python_with_statement.txt
Q: python-fastcgi extension There's not much documentation surrounding the python-fastcgi C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great. A: Edit: I misread the question. Ooops. Jon's Python modules is a co...
python-fastcgi extension
There's not much documentation surrounding the python-fastcgi C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great.
[ "Edit: I misread the question. Ooops.\nJon's Python modules is a collection of useful modules and includes a great FastCGI module: http://jonpy.sourceforge.net/fcgi.html\nHere's the example from the page:\nimport jon.cgi as cgi \nimport jon.fcgi as fcgi\n\nclass Handler(cgi.Handler):\n def process(self, req):\n ...
[ 4, 3 ]
[]
[]
[ "fastcgi", "python" ]
stackoverflow_0000875713_fastcgi_python.txt
Q: Letting users upload Python scripts for execution I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with ...
Letting users upload Python scripts for execution
I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I e...
[ "I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is code pad.\nAccording to the about page it is ran under geordi and traps all sys calls with ptrace. In addition to be chroot'ed they are on a virtual machine with...
[ 8, 8, 4, 3, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000818402_cgi_python.txt
Q: Learning threading concepts I have started threading in C and also Python recently and would like to know any good tutorials available for it. A: C - Recommended Books Unix: Butenhof, David R. - Programming with POSIX(R) Threads (Addison-Wesley Professional Computing Series) Windows: Hart, Johnson M. - Windows ...
Learning threading concepts
I have started threading in C and also Python recently and would like to know any good tutorials available for it.
[ "C - Recommended Books\nUnix: Butenhof, David R. - Programming with POSIX(R) Threads (Addison-Wesley Professional Computing Series)\nWindows: Hart, Johnson M. - Windows System Programming (3rd Edition)\nPython - Online\nTutorial on Threads Programming with Python (PDF)\n", "You could write the threading yourself,...
[ 2, 1, 0 ]
[]
[]
[ "c", "multithreading", "python" ]
stackoverflow_0000877068_c_multithreading_python.txt
Q: Zlib in database - Django When I try to put a zlibbed string in models.TextField >>> f = VCFile(head = 'blahblah'.encode('zlib')) >>> f.save() it fails: ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed ...
Zlib in database - Django
When I try to put a zlibbed string in models.TextField >>> f = VCFile(head = 'blahblah'.encode('zlib')) >>> f.save() it fails: ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed in 'x\x9cK\xcaI\xccH\x02b\x00\x...
[ "Like Marcus says, you'll have to use BLOB if you want to keep it in binary format. If you're OK with encoding it, you can use base64 encoding:\nfrom base64 import binascii\n\nf = VCFile(head = binascii.b2a_base64('blahblah'.encode('zlib')))\n\nIn my very basic tests with 33k characters, the zlib string was 28% the...
[ 2, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "zlib" ]
stackoverflow_0000875122_database_django_django_models_python_zlib.txt
Q: PyImport_Import vs import I've tried to replace PyRun_SimpleString("import Pootle"); with PyObject *obj = PyString_FromString("Pootle"); PyImport_Import(obj); Py_DECREF(obj); after initialising the module Pootle in some C code. The first seems to make the name Pootle available to subsequent PyRun_SimpleString c...
PyImport_Import vs import
I've tried to replace PyRun_SimpleString("import Pootle"); with PyObject *obj = PyString_FromString("Pootle"); PyImport_Import(obj); Py_DECREF(obj); after initialising the module Pootle in some C code. The first seems to make the name Pootle available to subsequent PyRun_SimpleString calls, but the second doesn't. C...
[ "All the PyImport_Import call does is return a reference to the module -- it doesn't make such a reference available to other parts of the program. So, if you want PyRun_SimpleString to see your new imported module, you need to add it manually.\nPyRun_SimpleString works automatically in the __main__ module namespac...
[ 4 ]
[]
[]
[ "c", "import", "python" ]
stackoverflow_0000878439_c_import_python.txt
Q: What is the Python equivalent to JDBC DatabaseMetaData? What is the Python equivalent to DatabaseMetaData A: This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help. The ANSI SQL-92 and SQL-99 Standard requires the INFORMATION_SCH...
What is the Python equivalent to JDBC DatabaseMetaData?
What is the Python equivalent to DatabaseMetaData
[ "This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help. \nThe ANSI SQL-92 and SQL-99 Standard requires the INFORMATION_SCHEMA schema, which stores information regarding the tables in a catalog. \nThe metadata you seek can be retrie...
[ 7, 0 ]
[]
[]
[ "database_metadata", "jdbc", "python" ]
stackoverflow_0000878737_database_metadata_jdbc_python.txt
Q: Is there a value in using map() vs for? Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: for item in items: item.my_func() If it makes sense, I would like to make it map(). Is that possible? What is an example like? A: You...
Is there a value in using map() vs for?
Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: for item in items: item.my_func() If it makes sense, I would like to make it map(). Is that possible? What is an example like?
[ "You could use map instead of the for loop you've shown, but since you do not appear to use the result of item.my_func(), this is not recommended. map should be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop.\nAlso, as of Python...
[ 24, 5, 2, 2, 2, 1, 0 ]
[ "map(lambda item: item.my_func(), items)\n\n" ]
[ -3 ]
[ "for_loop", "map_function", "python" ]
stackoverflow_0000875337_for_loop_map_function_python.txt
Q: Python Django: Handling URL with Google App Engine - Post then Get I have something like this set up: class CategoryPage (webapp.RequestHandler): def get(self): ** DO SOMETHING HERE ** def post(self): ** DO SOMETHING HERE ** ** RENDER THE SAME AS get(self) The question is, after I process the posted d...
Python Django: Handling URL with Google App Engine - Post then Get
I have something like this set up: class CategoryPage (webapp.RequestHandler): def get(self): ** DO SOMETHING HERE ** def post(self): ** DO SOMETHING HERE ** ** RENDER THE SAME AS get(self) The question is, after I process the posted data, how would I be able to display the same information as the get(self...
[ "A redirect, as others suggest, does have some advantage, but it's something of a \"heavy\" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method def _Render(self): and just ending both the get and post methods with a call to self.Render().\n", "Call self.redirect(...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000873966_google_app_engine_python.txt
Q: How can I color certain things in Emacs? I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange. How can I set up some colors for important Django template tags? A: You could use dedicated modes like django-mode or MuMaMo. If you want something very basic...
How can I color certain things in Emacs?
I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange. How can I set up some colors for important Django template tags?
[ "You could use dedicated modes like django-mode or MuMaMo.\nIf you want something very basic, and assuming you're editing in html-mode, you could try the following:\n(defun django-highlight-comments ()\n (interactive \"p\")\n (highlight-regexp \"{%.*?%}\" 'hi-orange))\n(add-hook 'html-mode-hook 'django-highlight-...
[ 6, 3, 1 ]
[]
[]
[ "django", "emacs", "python", "syntax_highlighting" ]
stackoverflow_0000875543_django_emacs_python_syntax_highlighting.txt
Q: Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases....
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I hav...
[ "Have you tried lxml? BeautifulSoup is good but not super-fast, and I believe lxml can offer the same quality but often better performance.\n", "BeautifulSoup uses regex internally (it's what separates it from other XML parsers) so you'll likely find yourself just repeating what it does. If you want a faster opt...
[ 3, 3, 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0000880687_beautifulsoup_python_regex.txt
Q: Applications of Python What are some applications for Python that relative amateur programmers can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python? Thanks. A: Google App Engine has excellent support for developing -- and especially for deploying -- w...
Applications of Python
What are some applications for Python that relative amateur programmers can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python? Thanks.
[ "Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for \"relative amateurs\"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involvin...
[ 15, 5, 5, 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000880917_python.txt
Q: Google App Engine self.redirect post I have a form that POSTs information to one of my handlers. My handler verifies the information and then needs to POST this information to a third party AND redirect the user to that page. Example of the class ExampleHandler(BaseRequestHandler): """DocString here... ""...
Google App Engine self.redirect post
I have a form that POSTs information to one of my handlers. My handler verifies the information and then needs to POST this information to a third party AND redirect the user to that page. Example of the class ExampleHandler(BaseRequestHandler): """DocString here... """ def post(self): day = int(self.req...
[ "You can POST the form and redirect the user to a page, but they'll have to be separate operations.\nThe urlfetch.fetch() method lets you set the method to POST like so:\nimport urllib\n\nform_fields = {\n \"first_name\": \"Albert\",\n \"last_name\": \"Johnson\",\n \"email_address\": \"Albert.Johnson@example.com...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000881086_google_app_engine_python.txt
Q: Pythonic URL Parsing There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/fir...
Pythonic URL Parsing
There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/second/third/fourth/foo...
[ "Since your requirements on what parts you want are different from what urlparse gives you, that's as good as it's going to get. You could, however, replace this:\npartCount = len(pathParts) - 1\n\npath = \"/\"\nfor i in range(2, partCount):\n path += pathParts[i] + \"/\"\n\nWith this:\npath = '/'.join(pathParts...
[ 6, 2 ]
[]
[]
[ "python", "url" ]
stackoverflow_0000880988_python_url.txt
Q: how to send email in python import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() This is giving the error: '**The debugge...
how to send email in python
import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() This is giving the error: '**The debugged program raised the exception un...
[ "Rename your file to something other than email.py. Also get rid of any email.pyc file left over. Problem solved.\n", "This happens because email is a built-in library that comes standard with python. If you rename your program to something else (as suggested above), that should do the trick.\n" ]
[ 12, 5 ]
[]
[]
[ "python" ]
stackoverflow_0000881184_python.txt
Q: "OSERROR -10000 Apple event handler failed" when trying to change desktop wallpaper on Mac I have written the following really simple python script to change the desktop wallpaper on my mac (based on this thread): from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_pictu...
"OSERROR -10000 Apple event handler failed" when trying to change desktop wallpaper on Mac
I have written the following really simple python script to change the desktop wallpaper on my mac (based on this thread): from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_picture.set(mactypes.File(fileName)) However when I run it I get the following output: Traceback (m...
[ "fileName = sys.argv[1]\ninstead of\nfileName = sys.argv[1:]\nmactypes.File(u\"/Users/Daniel/Pictures/['test.jpg']\")\nSee the square brackets and quotes around the filename?\n" ]
[ 2 ]
[]
[]
[ "debugging", "macos", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0000881041_debugging_macos_py_appscript_python_sourceforge_appscript.txt
Q: Error occurs when I connect with socket in Python Nice to meet you. A socket makes a program in Python by Linux (the transmission of a message) ⇒ Windows (the reception), b ut the following errors occur and cannot connect now. Linux, Windows are network connection together, and there is the authority to cut. socke...
Error occurs when I connect with socket in Python
Nice to meet you. A socket makes a program in Python by Linux (the transmission of a message) ⇒ Windows (the reception), b ut the following errors occur and cannot connect now. Linux, Windows are network connection together, and there is the authority to cut. socket.error: (111, 'Connection refused') Could you help me!...
[ "111 means the listener is down/not accepting connections - restart the Windows app that should be listening for connections, or disconnect any already-bound clients.\n" ]
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0000881332_python_sockets.txt
Q: In print statements, what determines whether python shell prints null character or waits for input Recently I was trying some practice programs in python and I came across this small problem. when I typed print "" in IDLE, the python shell printed a null character. If I typed print """""" in IDLE, the python sh...
In print statements, what determines whether python shell prints null character or waits for input
Recently I was trying some practice programs in python and I came across this small problem. when I typed print "" in IDLE, the python shell printed a null character. If I typed print """""" in IDLE, the python shell printed a null character. but the python shell waits for input if I type print """" Why is this beh...
[ "In python you can have strings enclosed with either 1 or 3 quotes.\nprint \"a\"\nprint \"\"\"a\"\"\"\n\nIn your case, the interpreter is waiting for the last triple quote.\n", "I suspect you mean that python printed an empty line -- this is not the same as a null character.\nWhen you print \"\"\"\"\"\", python f...
[ 11, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000881564_python.txt
Q: Cross-platform gui toolkit for deploying Python applications Building on: http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/ Merits: 1 - ease of design / integration - learning curve 2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobi...
Cross-platform gui toolkit for deploying Python applications
Building on: http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/ Merits: 1 - ease of design / integration - learning curve 2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web 3 - pythonic API 4 - quality of documentation - I want t...
[ "Please don't hesitate to expand this answer.\nTkinter\nTkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program.\nTki...
[ 50, 7, 6, 5, 0 ]
[]
[]
[ "cross_platform", "python", "user_interface" ]
stackoverflow_0000520015_cross_platform_python_user_interface.txt
Q: How to tell if a class is descended from another class I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not...
How to tell if a class is descended from another class
I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party li...
[ "\nissubclass only works for instances, not class objects themselves.\n\nIt works fine for me:\n>>> class test(object):pass\n...\n>>> issubclass(test,object)\nTrue\n\n" ]
[ 30 ]
[]
[]
[ "python" ]
stackoverflow_0000881676_python.txt
Q: How to use dynamic foreignkey in Django? I want to connect a single ForeignKey to two different models. For example: I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic? class Articles(models.Model): title = mode...
How to use dynamic foreignkey in Django?
I want to connect a single ForeignKey to two different models. For example: I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic? class Articles(models.Model): title = models.CharField(max_length=100) body = models...
[ "Here is how I do it:\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import fields\n\n\nclass Photo(models.Model):\n picture = models.ImageField(null=True, upload_to='./images/')\n caption = models.CharField(_(\"Optional caption\"),max_length=100,null=True, blank...
[ 64, 22 ]
[]
[]
[ "django", "foreign_keys", "python" ]
stackoverflow_0000881792_django_foreign_keys_python.txt
Q: How to hide "cgi-bin", ".py", etc from my URLs? Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for ...
How to hide "cgi-bin", ".py", etc from my URLs?
Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar neve...
[ "The python way of writing web applications is not cgi-bin. It is by using WSGI.\nWSGI is a standard interface between web servers and Python web applications or frameworks. The PEP 0333 defines it.\nThere are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat...
[ 14, 5, 4, 4, 4, 3 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000882430_cgi_python.txt
Q: Where to keep Python unit tests? Possible Duplicate: Where do the Python unit tests go? Are unit tests kept in the same file as the code, a separate file in the same directory, or in an entirely different directory? A: I always place my unit tests in a subdirectory to the related code called test. For example:...
Where to keep Python unit tests?
Possible Duplicate: Where do the Python unit tests go? Are unit tests kept in the same file as the code, a separate file in the same directory, or in an entirely different directory?
[ "I always place my unit tests in a subdirectory to the related code called test.\nFor example: /libs/authentication, the tests would be placed in /libs/authentication/tests\n", "I prefer to keep them in a seperate directory, usually called either \"unittests\" or just \"tests\". I then play games in the Makefile ...
[ 15, 5, 3, 0, 0 ]
[ "for each project there is a test project\nExample naming\nmain project\n\nCompany.Project.Area\n\nmain project testing\n\nCompany.Project.Area.Test\n\n" ]
[ -1 ]
[ "code_organization", "python", "unit_testing" ]
stackoverflow_0000882399_code_organization_python_unit_testing.txt
Q: Is there a way to poll a file handle returned from subprocess.Popen? Say I write this: from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) Now if I do line = p.stdout.readline() my program waits until the subprocess outputs the next line. Is there any magic I can do t...
Is there a way to poll a file handle returned from subprocess.Popen?
Say I write this: from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) Now if I do line = p.stdout.readline() my program waits until the subprocess outputs the next line. Is there any magic I can do to p.stdout so that I could read the output if it's there, but just continu...
[ "Use p.stdout.read(1) this will read character by character\nAnd here is a full example:\nimport subprocess\nimport sys\n\nprocess = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n)\n\nwhile True:\n out = process.stdout.read(1)\n if out == '' and process.poll() != None:\n b...
[ 8, 5 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0000883152_pipe_python_subprocess.txt
Q: Python unittest: how do I test the argument in an Exceptions? I am testing for Exceptions using unittest, for example: self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) and my code raises: raise UnrecognizedAirportError('From') Which works well. How do I test that the argument in the exception is wha...
Python unittest: how do I test the argument in an Exceptions?
I am testing for Exceptions using unittest, for example: self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) and my code raises: raise UnrecognizedAirportError('From') Which works well. How do I test that the argument in the exception is what I expect it to be? I wish to somehow assert that capturedExceptio...
[ "Like this.\n>>> try:\n... raise UnrecognizedAirportError(\"func\",\"arg1\",\"arg2\")\n... except UnrecognizedAirportError, e:\n... print e.args\n...\n('func', 'arg1', 'arg2')\n>>>\n\nYour arguments are in args, if you simply subclass Exception. \nSee http://docs.python.org/library/exceptions.html#module-ex...
[ 11, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000883357_python_unit_testing.txt
Q: wxPython + multiprocessing: Checking if a color string is legitimate I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. However, there is something I would like to do from the seconda...
wxPython + multiprocessing: Checking if a color string is legitimate
I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. However, there is something I would like to do from the secondary process: Given a string that describes a color, to check whether this w...
[ "You could make two Queues between the two processes and have the second one delegate wx-related functionality to the first one (by pushing on the first queue the parameters of the task to perform, and waiting for the result on the second one).\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "wxpython" ]
stackoverflow_0000883348_multiprocessing_python_wxpython.txt
Q: Calling python from python - persistence of module imports? So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py). The question is this: are there any special rules about imports? One script needs...
Calling python from python - persistence of module imports?
So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py). The question is this: are there any special rules about imports? One script needs to run just once, and it would be good to keep the objects it cr...
[ "The documentation for the execfile method is here. Since no particular version of python was specified, I'm going to assume we're talking about 2.6.2.\nThe documentation for execfile specifies it takes three arguments: the filename, a dictionary (to act as the local variables), and a second dictionary (to act as t...
[ 2, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0000883211_import_module_python.txt
Q: Custom implementation of "tail -f" functionality in C EDIT: I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, inotail. Original question text: I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes ...
Custom implementation of "tail -f" functionality in C
EDIT: I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, inotail. Original question text: I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow: # A forever loop, ...
[ "Once a FILE * has seen an error or eof, it has its internal status set so that it continues to return error or eof on subsequent calls. You need to call clearerr(f); after the sleep returns to clear the eof setting and get it to try to read more data from the file.\n", "EDIT:\nSeems like inotify is the thing to...
[ 3, 3, 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000883784_c_python.txt
Q: How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods? I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the...
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his D...
[ "Instead of: \"print hasattr(d1,each)\", try: \"print each, type(getattr(d1,each))\". You should find the results informative. \nAlso, in place of dir() try help(), which I think you're really looking for.\n", "Consider using the standard library's inspect module -- it's often the handiest approach to introspecti...
[ 8, 4, 2, 2, 1, 1 ]
[]
[]
[ "attributes", "methods", "python", "python_datamodel" ]
stackoverflow_0000880160_attributes_methods_python_python_datamodel.txt
Q: How to return a function value with decorator and thread have this code import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator...
How to return a function value with decorator and thread
have this code import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): return a+b print(add...
[ "The reason None is returned, is because there is nothing to return (besides the fact that decorator doesn't have a return statement). join() always returns None, as per the documentation.\nFor an example of how to communicate with a thread, see this email.\nIf I may ask though: since join() blocks the calling thre...
[ 4, 2 ]
[]
[]
[ "decorator", "multithreading", "python" ]
stackoverflow_0000884410_decorator_multithreading_python.txt
Q: How can I create a RSA public key in PEM format from an RSA modulus? I have the modulus of an RSA public key. I want to use this public key with the Python library "M2Crypto", but it requires a public key in PEM format. Thus, I have to convert the RSA modulus to a PEM file. The modulus can be found here. Any ide...
How can I create a RSA public key in PEM format from an RSA modulus?
I have the modulus of an RSA public key. I want to use this public key with the Python library "M2Crypto", but it requires a public key in PEM format. Thus, I have to convert the RSA modulus to a PEM file. The modulus can be found here. Any ideas?
[ "The M2Crypto library has a way to reconstruct a public key. You need to know the public exponent, e (often 65337 for RSA keys, but other numbers such as 3 or 17 have been used), and the modulus, n (which is the 512-bit number provided in the question). Note that the docs describe the length-encoded format used for...
[ 4 ]
[]
[]
[ "cryptography", "m2crypto", "python", "rsa" ]
stackoverflow_0000884207_cryptography_m2crypto_python_rsa.txt
Q: wxPython: Drawing a vector-based image from file How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend. A: You can do this with using cairo & librsvg python bindings. There is a small example here. A: I have done something similar, I ...
wxPython: Drawing a vector-based image from file
How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.
[ "You can do this with using cairo & librsvg python bindings. There is a small example here.\n", "I have done something similar, I had a custom vector image format that I needed to render in a wxPython window. In order to accomplish this I used the GDI interface for drawing commands and I wrote my own parser modu...
[ 3, 1 ]
[]
[]
[ "python", "vector_graphics", "wxpython" ]
stackoverflow_0000844110_python_vector_graphics_wxpython.txt
Q: Django Admin & Model Deletion I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its delete method. class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, ...
Django Admin & Model Deletion
I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its delete method. class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, self).delete() When I call delete ...
[ "According to this documentation bug report (Document that the admin bulk delete doesn't call Model.delete()), the admin's bulk delete does NOT call the model's delete function. If you're using bulk delete from the admin, this would explain your problem.\nFrom the added documentation on this ticket, the advice is t...
[ 9 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000885103_django_django_admin_python.txt
Q: Problems eagerloading a set of object using SQLAlchemy I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's. Unfortunately the query below fails because table O2 is aliased...
Problems eagerloading a set of object using SQLAlchemy
I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's. Unfortunately the query below fails because table O2 is aliased in the query and the column referenced by the order_by phra...
[ "Use a lambda of clause elements to achieve late binding of the order by, like this:\nones = relation('O1', order_by=lambda:[O1.value])\n\nOr as an another option, make the whole order_by a string, like this:\nones = relation('O1', order_by='O1.value, O1.something_else')\n\n" ]
[ 3 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0000885235_orm_python_sqlalchemy.txt
Q: What is an exotic function signature in Python? I recently saw a reference to "exotic signatures" and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is def exotic_signature((x, y)=(1,2)): return x+y What makes this an "exotic" signature? A: What's exotic is that x and y represe...
What is an exotic function signature in Python?
I recently saw a reference to "exotic signatures" and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is def exotic_signature((x, y)=(1,2)): return x+y What makes this an "exotic" signature?
[ "What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to:\ndef func(n):\n x, y = n\n ...\n\nBoth functions require a single argument (list or tuple) that contains two elements.\n", "More information about tuple parameter unpacking (...
[ 6, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000884068_python.txt
Q: wxPython dialogs: "Enter" keyboard button would not "ok" the dialog I am creating a custom wxPython dialog by subclassing wx.Dialog. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button. Ho...
wxPython dialogs: "Enter" keyboard button would not "ok" the dialog
I am creating a custom wxPython dialog by subclassing wx.Dialog. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button. How do I solve this?
[ "That should happen automatically if the button has the wx.ID_OK id. If that's impossible then the wx.StdDialogButtonSizer.SetAffirmativeButton() method could be a solution (using the StdDialogButtonSizer class will help with correct button placement and positioning on the different platforms), and there is also wx...
[ 5 ]
[]
[]
[ "keyboard", "python", "wxpython" ]
stackoverflow_0000885294_keyboard_python_wxpython.txt
Q: Wrapping a Python Object I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects: def __init__(self, anObject): self.theObject = anObject and provides a "write" method: def write(self, pathOrFile):...
Wrapping a Python Object
I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects: def __init__(self, anObject): self.theObject = anObject and provides a "write" method: def write(self, pathOrFile): plistlib.writeToPlist(sel...
[ "Unless I'm missing something, this will work just fine:\ndef __getattr__(self, name):\n return getattr(self.theObject, name)\n\n\nEdit: for those thinking that the lookup of self.theObject will result in an infinite recursive call to __getattr__, let me show you:\n>>> class Test:\n... a = \"a\"\n... def...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000884594_python.txt
Q: Error when trying to migrate django application with south I am getting this error when running "./manage.py migrate app_name" While loading migration 'whatever.0001_initial': Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) ...tons of other stuff.. raise Ke...
Error when trying to migrate django application with south
I am getting this error when running "./manage.py migrate app_name" While loading migration 'whatever.0001_initial': Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) ...tons of other stuff.. raise KeyError("The model '%s' from the app '%s' is not available in thi...
[ "The problem seemed to be with the order of models in the 0001_initial.py file. There was a class which derived from AppUser. When I re-created the migration on Mac OS with\nmanage.py startmigration app --initial\n\nand compared that to one generated on Ubuntu the order of models was different. So when I changed th...
[ 2 ]
[]
[]
[ "database", "django", "migration", "python" ]
stackoverflow_0000880989_database_django_migration_python.txt
Q: python orm This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to p...
python orm
This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a convers...
[ "As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic \"schema migration\". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself.\nThere are some tools on the horizon for Django schema migration. (I'm watc...
[ 5, 4, 0 ]
[]
[]
[ "database", "django", "django_models", "python" ]
stackoverflow_0000885172_database_django_django_models_python.txt
Q: How does MySQL's RENAME TABLE statment work/perform? MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. The manual mentions The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running The manual does n...
How does MySQL's RENAME TABLE statment work/perform?
MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. The manual mentions The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running The manual does not (to my knowedge) state how this renaming is accomplishe...
[ "I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant.\n", "In addition to altering the metadata, it also renames the associated .FRM file. While they can claim it being an \"atomic\" operation, this is...
[ 6, 1 ]
[]
[]
[ "migration", "mysql", "php", "python", "ruby" ]
stackoverflow_0000885771_migration_mysql_php_python_ruby.txt
Q: dnspython and python objects I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html: import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'ha...
dnspython and python objects
I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html: import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference I...
[ "In the example code, answers is an iterable object containing zero or more items, which are each assigned to rdata in turn. To see the properties of the individual responses, try:\ndir(answers[0])\n\n", "answers is an iterable as indicated by its \"__iter__\" method. Think of answers as a list of rdatas.\nYou c...
[ 1, 1, 1, 0 ]
[]
[]
[ "dns", "dnspython", "python" ]
stackoverflow_0000885634_dns_dnspython_python.txt
Q: Can I use re.sub (or regexobject.sub) to replace text in a subgroup? I need to parse a configuration file which looks like this (simplified): <config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> <...
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
I need to parse a configuration file which looks like this (simplified): <config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> My goal is to be able to change paramete...
[ "I have to give you the obligatory: \"don't use regular expressions to do this.\"\nCheck out how very easily awesome it is to do this with BeautifulSoup, for example:\n>>> from BeautifulSoup import BeautifulStoneSoup\n>>> html = \"\"\"\n... <config>\n... <links>\n... <link name=\"Link1\" id=\"1\">\n... <encapsulat...
[ 6, 2, 1, 0 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0000886111_python_regex_regex_group.txt
Q: Django without shell access Is it possible to run django without shell access? My hoster supports the following for 5€/month: python (I assume via mod_python) mysql There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it. I know that Google Apps also work without shell...
Django without shell access
Is it possible to run django without shell access? My hoster supports the following for 5€/month: python (I assume via mod_python) mysql There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it. I know that Google Apps also work without shell access, but I assume that is pos...
[ "It's possible but not desirable. Having shell access makes it possible to centralise things properly using symlinks. \nGet a better host would be my first suggestion. WebFaction is the most recommended shared host for using with Django.\nIf that's out of your price range, there are plenty of hosts that give you a ...
[ 4, 1 ]
[]
[]
[ "django", "python", "shell" ]
stackoverflow_0000886526_django_python_shell.txt
Q: How to use counter in for loop python my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter...
How to use counter in for loop python
my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: ...
[ "The counter is getting out of step with the sequences you're iterating over. But more than that, the counter is totally unnecessary.\nYou've got several manual iterations of things that could be automated, and they're causing you to trip over. Especially, you hardly ever need to manually track a counter while iter...
[ 8, 4, 2, 2, 2, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0000886629_iterator_python.txt
Q: How to perform a query in django that selects all projects where I am a team member of? I have the concept of a team in my django app. class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) I would like to fetch all teams the currently logge...
How to perform a query in django that selects all projects where I am a team member of?
I have the concept of a team in my django app. class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) I would like to fetch all teams the currently logged in user is member of. Something along the lines of Team.objects.all().filter(request.user....
[ "You don't need in here, Django handles that automatically in a ManyToMany lookup.\nAlso, you need to understand that the database fields must always be on the left of the lookup, as they are actually handled as parameters to a function.\nWhat you actually want is very simple:\nTeam.objects.filter(team_members=requ...
[ 4 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0000886624_django_pinax_python.txt
Q: Making a python cgi script to finish gracefully I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, t...
Making a python cgi script to finish gracefully
I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and a...
[ "You can trap the exit signal with the signal module. Haven't tried this with mod_python though.\nhttp://docs.python.org/library/signal.html\nNote in the docs:\n\nWhen a signal arrives during an I/O operation, it is possible that the I/O operation raises an exception after the signal handler returns. This is depend...
[ 1, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000886653_cgi_python.txt
Q: Controlling bars width in matplotlib with per-month data When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month. I tried to set the minor ticks locator to Month...
Controlling bars width in matplotlib with per-month data
When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month. I tried to set the minor ticks locator to MonthLocator() without effect. [edit] Maybe an example will be more...
[ "Just use the width keyword argument:\nbar(x, y, width=30)\n\nOr, since different months have different numbers of days, to make it look good you can use a sequence:\nbar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30])\n\n" ]
[ 59 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0000886716_matplotlib_python.txt
Q: Make Emacs use UTF-8 with Python Interactive Mode When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8: $ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information...
Make Emacs use UTF-8 with Python Interactive Mode
When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8: $ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' This ...
[ "check your environment variables:\n$ LANG=\"en_US.UTF8\" python -c \"import sys; print sys.stdout.encoding\"\nUTF-8\n$ LANG=\"en_US\" python -c \"import sys; print sys.stdout.encoding\" \nANSI_X3.4-1968\n\nin your python hook, try:\n(setenv \"LANG\" \"en_US.UTF8\")\n\n" ]
[ 7 ]
[]
[]
[ "emacs", "encoding", "python", "terminal", "utf_8" ]
stackoverflow_0000888406_emacs_encoding_python_terminal_utf_8.txt
Q: Problem using py2app with the lxml package I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still w...
Problem using py2app with the lxml package
I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ins...
[ "Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this:\nfrom setuptools import setup\n\nDATA_FILES = []\nOPTIONS = {'argv_emulation': True,\n 'packages' : ['lxml'],\n 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2....
[ 14, 1, 1, 1 ]
[]
[]
[ "lxml", "py2app", "python" ]
stackoverflow_0000868510_lxml_py2app_python.txt
Q: ManyToOneField in Django I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: class User(models.Model): name = models.CharField() class Group(models.Model): name = models...
ManyToOneField in Django
I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: class User(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() # This is wha...
[ "A ManyToOne field, as you've guessed, is called ForeignKey in Django. You will have to define it on your User class for the logic to work properly, but Django will make a reverse property available on the Groups model automatically:\nclass Group(models.Model):\n name = models.CharField(max_length=64)\n\nclass U...
[ 10, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000888550_django_python.txt
Q: Function Decorators I like being able to measure performance of the python functions I code, so very often I do something similar to this... import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux ...
Function Decorators
I like being able to measure performance of the python functions I code, so very often I do something similar to this... import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux # Function code goes...
[ "Though inspect may get you a bit on the way, what you want is in general not possible:\ndef f(*args):\n pass\n\nNow how many arguments does f take? Since *args and **kwargs allow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cas...
[ 9, 8, 0 ]
[]
[]
[ "argument_passing", "decorator", "python" ]
stackoverflow_0000889088_argument_passing_decorator_python.txt
Q: How can I read()/write() against a python HTTPConnection? I've got python code of the form: (o,i) = os.popen2 ("/usr/bin/ssh host executable") ios = IOSource(i,o) Library code then uses this IOSource, doing writes() and read()s against inputstream i and outputstream o. Yes, there is IPC going on here.. Think...
How can I read()/write() against a python HTTPConnection?
I've got python code of the form: (o,i) = os.popen2 ("/usr/bin/ssh host executable") ios = IOSource(i,o) Library code then uses this IOSource, doing writes() and read()s against inputstream i and outputstream o. Yes, there is IPC going on here.. Think RPC. I want to do this, but in an HTTP fashion rather than spa...
[ "for output:\noutput = response.read()\n\nhttp://docs.python.org/library/httplib.html#httpresponse-objects\nfor input:\npass your data in the POST body of your request\n" ]
[ 1 ]
[]
[]
[ "http", "python", "rpc" ]
stackoverflow_0000889528_http_python_rpc.txt
Q: Dividing in an if statement In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement. a = range(20) for i in a: if i / 3 == True: print i A: Yes, but. Please, please, please. Never say if some expression == True. It's redu...
Dividing in an if statement
In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement. a = range(20) for i in a: if i / 3 == True: print i
[ "Yes, but.\nPlease, please, please. Never say if some expression == True. It's redundant and causes many people to wonder what you're thinking.\nMore importantly. \ni/3 is the quotient.\ni%3 is the remainder. If i is a multiple of 3, i%3 == 0.\n", "Everyone here has done a good job explaining how to do it righ...
[ 7, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000889446_python.txt
Q: Closing and Opening Frames in wxPython I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. The login frame is a subclass of wx.Frame, and ...
Closing and Opening Frames in wxPython
I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. The login frame is a subclass of wx.Frame, and basically I just want to close it and open t...
[ "I would make your main frame appear, then show a modal login dialog over top instead.\nIf you don't want to do that, I suggest you create two separate Frames and have your application listen for a close event on the login frame. Handle the login in that event handler, then have it show the main window. Basically...
[ 2, 0 ]
[]
[]
[ "network_programming", "python", "user_interface", "wxpython" ]
stackoverflow_0000885453_network_programming_python_user_interface_wxpython.txt
Q: No reverse error in Google App Engine Django patch? I am using Google App Engine patch Django. When I try to go to the admin site, http://127.0.0.1:8080/admin/ , I keep getting this error: TemplateSyntaxError at /admin/ Caught an exception while rendering: Reverse for 'settings.django.contrib.auth.views.log...
No reverse error in Google App Engine Django patch?
I am using Google App Engine patch Django. When I try to go to the admin site, http://127.0.0.1:8080/admin/ , I keep getting this error: TemplateSyntaxError at /admin/ Caught an exception while rendering: Reverse for 'settings.django.contrib.auth.views.logout' with arguments '()' and keyword arguments '{}' not...
[ "I could not find a proper answer to my question. Anyways I solved the problem temporarily by reinstalling the Django framework and the app engine SDK.\n" ]
[ 1 ]
[]
[]
[ "django", "django_urls", "google_app_engine", "python" ]
stackoverflow_0000872100_django_django_urls_google_app_engine_python.txt
Q: SQLAlchemy - MappedCollection problem I have some problems with setting up the dictionary collection in Python's SQLAlchemy: I am using declarative definition of tables. I have Item table in 1:N relation with Record table. I set up the relation using the following code: _Base = declarative_base() class Record(_Ba...
SQLAlchemy - MappedCollection problem
I have some problems with setting up the dictionary collection in Python's SQLAlchemy: I am using declarative definition of tables. I have Item table in 1:N relation with Record table. I set up the relation using the following code: _Base = declarative_base() class Record(_Base): __tablename__ = 'records' ite...
[ "You want something like this:\nfrom sqlalchemy.orm import validates\n\nclass Item(_Base):\n [...]\n\n @validates('records')\n def validate_record(self, key, record):\n assert record.name is not None, \"Record fails validation, must have a name\"\n return record\n\nWith this, you get the desired ...
[ 2, 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000793848_python_sqlalchemy.txt
Q: SQLAlchemy - Database hits on every request? I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the r...
SQLAlchemy - Database hits on every request?
I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to ...
[ "\"hitting the database for something like this on every request isn't efficient.\"\nFalse. And, you've assumed that there's no caching, which is also false.\nMost ORM layers are perfectly capable of caching rows, saving some DB queries.\nMost RDBMS's have extensive caching, resulting in remarkably fast responses ...
[ 3, 3, 2, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000881517_python_sqlalchemy.txt
Q: How do I detect when my window is minimized with wxPython? I am writing a small wxPython utility. I would like to use some event to detect when a user minimizes the application/window. I have looked around but did not find an event like wx.EVT_MINIMIZE that I could bind to. Anyone know of a way that can be used to...
How do I detect when my window is minimized with wxPython?
I am writing a small wxPython utility. I would like to use some event to detect when a user minimizes the application/window. I have looked around but did not find an event like wx.EVT_MINIMIZE that I could bind to. Anyone know of a way that can be used to detect this?
[ "Add a handler for the wx.EVT_ICONIZE event.\n" ]
[ 3 ]
[]
[]
[ "minimize", "python", "wxpython" ]
stackoverflow_0000890170_minimize_python_wxpython.txt
Q: What is "wua" mode when opening a file in python? I have recently been going through some of our windows python 2.4 code and come across this: self.logfile = open(self.logfile_name, "wua") I know what w, u and a do on their own, but what happens when you combine them? A: The a is superfluous. wua is the same as...
What is "wua" mode when opening a file in python?
I have recently been going through some of our windows python 2.4 code and come across this: self.logfile = open(self.logfile_name, "wua") I know what w, u and a do on their own, but what happens when you combine them?
[ "The a is superfluous. wua is the same as wu since w comes first and will thus truncate the file. If you would reverse the order, that is, auw, that would be the same as au. Visualized:\n>>> f = open('test.txt', 'r')\n>>> f.read()\n'Initial contents\\n'\n>>> f.close()\n>>> f = open('test.txt', 'wua')\n>>> print >> ...
[ 5, 3, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0000886238_file_python.txt
Q: Substituting a regex only when it doesn't match another regex (Python) Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*...
Substituting a regex only when it doesn't match another regex (Python)
Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced, bu...
[ "Using negative look-ahead/behind assertion\npattern = re.compile( \"(?<!\\{)\\{(?!\\{).*?(?<!\\})\\}(?!\\})\" )\npattern.sub( \"hello\", input_string )\n\nNegative look-ahead/behind assertion allows you to compare against more of the string, but is not considered as using up part of the string for the match. There...
[ 7, 4, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000889045_python_regex.txt
Q: Google App Engine Python Code: User Service What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)? from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.web...
Google App Engine Python Code: User Service
What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)? from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(weba...
[ "self refers to the webapp.RequestHandler class. Here is its documentation: http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html, which tells you what response means.\n", "self is a python convention which means 'this' in other languages like Java, C#, C++, etc...I've found it bizarr...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000890857_google_app_engine_python.txt
Q: Dynamic generation of .doc files How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file contai...
Dynamic generation of .doc files
How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file containing the user input for the webpage. A...
[ "The problem with the *.doc MS word format is, that it isn't documented enough, therefor it can't have a very good support like, for example, PDF, which is a standard.\nExcept of the problems with generating the doc, you're users might have problems reading the doc files. For example users on linux machines.\nYou s...
[ 2, 0 ]
[]
[]
[ "air", "ajax", "dynamic_data", "python" ]
stackoverflow_0000891315_air_ajax_dynamic_data_python.txt
Q: Why would one choose Iron Python instead of Boo? Possible Duplicates: BOO Vs IronPython Boo vs. IronPython Say you want to embed a scripting language into a .NET application. Boo is modelled on Python syntax, but also includes type inference, and just in general seems to be a better, more modern language to embe...
Why would one choose Iron Python instead of Boo?
Possible Duplicates: BOO Vs IronPython Boo vs. IronPython Say you want to embed a scripting language into a .NET application. Boo is modelled on Python syntax, but also includes type inference, and just in general seems to be a better, more modern language to embed as a scripting language. Why, then, is there so muc...
[ "2 words: User Base.\nI already know so many languages that I have to keep references handy so I can remember if it's \"else if\", \"elsif\" or \"elif\" in whatever I'm currently working in. Unless there's a compelling reason to use another language (more than just a few small differences) I'm going to stick with o...
[ 2, 1, 0 ]
[]
[]
[ ".net", "boo", "ironpython", "python" ]
stackoverflow_0000890420_.net_boo_ironpython_python.txt
Q: Install older versions of Python for testing on Mac OS X I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python? A: You ha...
Install older versions of Python for testing on Mac OS X
I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?
[ "You have two main options, install the python 2.3 from macports (easy) or install from source.\nFor macports, run port install python23\nFor the 2nd, you'll have to go to http://www.python.org/download/releases/2.3.7/ to download the source tarball. Once you have that open a terminal and run ./configure --prefix /...
[ 6, 1, 0, 0 ]
[]
[]
[ "installation", "python", "version" ]
stackoverflow_0000890827_installation_python_version.txt
Q: GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user). That splash screen, once entered a valid code, will tell that to the service a...
GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus
I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user). That splash screen, once entered a valid code, will tell that to the service and the service goes to sleep for an x amount of time (depending of the code). The splash scree...
[ "Have you tried launching another processes than your own from the service to see if it gets focus? Like notepad and see if it steals focus from your browser? If so perhaps its the program that can take back the focus when it starts.\nI otherwise beilive it's the wShowWindow attribute from the STARTUPINFO struct th...
[ 2, 0 ]
[]
[]
[ "python", "pywin32", "tkinter", "windows_services" ]
stackoverflow_0000860428_python_pywin32_tkinter_windows_services.txt
Q: Strings and file Suppose this is my list of languages. aList = ['Python','C','C++','Java'] How can i write to a file like : Python : ... C : ... C++ : ... Java : ... I have used rjust() to achieve this. Without it how can i do ? Here i have done manually. I want to avoid that,ie; it...
Strings and file
Suppose this is my list of languages. aList = ['Python','C','C++','Java'] How can i write to a file like : Python : ... C : ... C++ : ... Java : ... I have used rjust() to achieve this. Without it how can i do ? Here i have done manually. I want to avoid that,ie; it shuould be ordered au...
[ "You can do this with string formatting operators\nf=open('filename.txt','w')\nfor item in aList:\n print >>f, \"%-20s : ...\" % item\n\nThe 20 is the field width, while the \"-\" indicates to left justify it.\n", "Do you mean this?\n>>> languages = ['Python','C','C++','Java']\n>>> f = open('myfile.txt', 'w')\...
[ 5, 5, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000891895_python_string.txt
Q: Python regular expression to match # followed by 0-7 followed by ## I would like to intercept string starting with \*#\* followed by a number between 0 and 7 and ending with: ## so something like \*#\*0## but I could not find a regex for this A: Assuming you want to allow only one # before and two after, I'd do ...
Python regular expression to match # followed by 0-7 followed by ##
I would like to intercept string starting with \*#\* followed by a number between 0 and 7 and ending with: ## so something like \*#\*0## but I could not find a regex for this
[ "Assuming you want to allow only one # before and two after, I'd do it like this:\nr'^(\\#{1}([0-7])\\#{2})'\n\nIt's important to note that Alex's regex will also match things like\n###7######\n########1###\n\nwhich may or may not matter.\nMy regex above matches a string starting with #[0-7]## and ignores the end o...
[ 7, 4, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000889143_python_regex.txt
Q: How would one build an smtp client in python? buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !! A: Create mail messages (possibly with multipart attachments) with email. The email package is a library for managing ema...
How would one build an smtp client in python?
buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!
[ "Create mail messages (possibly with multipart attachments) with email.\n\nThe email package is a library for managing email messages, including MIME and other RFC 2822-based message documents.\n\nSend mail using smtplib\n\nThe smtplib module defines an SMTP client session object that can be used to send mail to an...
[ 2, 1, 0 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0000892196_python_smtp.txt
Q: filter with string return nothing I run into follow problem. Did I miss anything? Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.al...
filter with string return nothing
I run into follow problem. Did I miss anything? Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.all().filter('server_url =', 'server-url'...
[ "What kind of property is \"server_url\"?\nIf it is a TextProperty, then it cannot be used in filters.\n\nUnlike StringProperty, a TextProperty\n value can be more than 500 bytes long.\n However, TextProperty values are not\n indexed, and cannot be used in filters\n or sort orders.\n\nhttp://code.google.com/app...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000891935_google_app_engine_python.txt
Q: Python: Plugging wx.py.shell.Shell into a separate process I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How? EDIT: I have already achieved a way to send commands to the secondary process: I created a code.InteractiveConsole in that p...
Python: Plugging wx.py.shell.Shell into a separate process
I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How? EDIT: I have already achieved a way to send commands to the secondary process: I created a code.InteractiveConsole in that process, and attached it to an input queue and an output queue, s...
[ "\nFirst create the shell \nDecouple the shell from your app by making its locals empty\nCreate your code string\nCompile the code string and get a code object\nExecute the code object in the shell\n\n\n from wx.py.shell import Shell\n\n frm = wx.Frame(None)\n sh = Shell(frm)\n frm.Show() \n sh.in...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "shell", "wxpython" ]
stackoverflow_0000865082_multiprocessing_python_shell_wxpython.txt
Q: How to make a dynamic array with different values in Python I have rows in file like : 20040701 0 20040701 0 1 52.965366 61.777687 57.540783 I want to put that in a dynamic array if it's possible ? Something like try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Lo...
How to make a dynamic array with different values in Python
I have rows in file like : 20040701 0 20040701 0 1 52.965366 61.777687 57.540783 I want to put that in a dynamic array if it's possible ? Something like try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] ...
[ "You can easily make a list of numbers from a string like your first example, just [float(x) for x in thestring.split()] -- but the \"Something like\" is nothing like the first example and appears to have nothing to do with the question's Subject.\n", "In [1]: s = \"20040701 0 20040701 0 1 52.965366 61.777687 57....
[ 2, 2, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0000893143_python_sqlite.txt
Q: Python doctest fails on 0.0 != -0.0--what gives? Given the following code: def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) y...
Python doctest fails on 0.0 != -0.0--what gives?
Given the following code: def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ya = float (y1) yb = float (y2) return (ya-yb)/...
[ "It fails because doctest does string comparison. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter:\n>>> 0 / -2\n-0.0\n\nEdit:: The link referenced by Daniel Lew below gives some more hints about how this works, an...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0000893398_python.txt
Q: Dynamically specifying tags while using replaceWith in Beautiful Soup Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with. >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="...
Dynamically specifying tags while using replaceWith in Beautiful Soup
Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with. >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="Link1" id="1"> ... <encapsulation> ... <mode>ipsec</mode> ... </encapsu...
[ "Try getattr(soup.find('link', id=1), sometag) where you now have a hardcoded tag in soup.find('link', id=1).mode -- getattr is the Python way to get an attribute whose name is held as a string variable, after all!\n", "No need to use getattr:\nsometag = 'mode'\nresult = soup.find('link', id=1).find(sometag)\npri...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "xml" ]
stackoverflow_0000891434_beautifulsoup_python_xml.txt
Q: How to define a system-wide alias for a Python script? I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 Since the location of the script mi...
How to define a system-wide alias for a Python script?
I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 Since the location of the script might change, I want to decouple other scripts and the launchd...
[ "I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)\n(In a terminal. You may have to use sudo ln -s depending on the permissions.\nln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py\n\nIf you take Rory's advice and put the #!/usr/bin/python at the beginn...
[ 6, 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0000893543_macos_python.txt
Q: Replacing Microsoft Word Newline Character in Python This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the CTRL ENTER character that shows up as a return arrow in Word. I've tried chr(10), chr(13), \...
Replacing Microsoft Word Newline Character in Python
This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the CTRL ENTER character that shows up as a return arrow in Word. I've tried chr(10), chr(13), \u000D, \u000A and a few others, but I can't match it in a ...
[ "Run this:\nprint repr(mystringobject)\n\nThat will give a hint of which character you want to remove.\nIf still no clue, paste the result of the command above in the question, and I'll edit my answer.\n", "you can get the ASCII value of the character like this:\nfor c in 'string':\n print ord(c), hex(ord(c))\...
[ 4, 2 ]
[]
[]
[ "ms_word", "python", "sanitize" ]
stackoverflow_0000893514_ms_word_python_sanitize.txt
Q: Python PySerial readline function wrong use I'm using a script importing PySerial to read from COM4 messages I would like to intercept end with a couple of # so I tried to use bus.readline(eol='##') where bus is my connection. I expected to read like: *#*3## *#*3## *#*3## Unfortunalyy I found also *#*1##*1*1*...
Python PySerial readline function wrong use
I'm using a script importing PySerial to read from COM4 messages I would like to intercept end with a couple of # so I tried to use bus.readline(eol='##') where bus is my connection. I expected to read like: *#*3## *#*3## *#*3## Unfortunalyy I found also *#*1##*1*1*99## that I expected to read spleetted into 2 li...
[ "The readline() method in pyserial reads one character at a time and compares it to the EOL character. You cannot specify multiple characters as the EOL. You'll have to read in and then split later using string.split() or re.split()\n" ]
[ 3 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0000893747_pyserial_python.txt
Q: Programmatically make HTTP requests through proxies with Python How do I use Python to make an HTTP request through a proxy? What do I need to do to the following code? urllib.urlopen('http://www.google.com') A: The urlopen function supports proxies. Try something like this: urllib.urlopen(your_url, proxies = {...
Programmatically make HTTP requests through proxies with Python
How do I use Python to make an HTTP request through a proxy? What do I need to do to the following code? urllib.urlopen('http://www.google.com')
[ "The urlopen function supports proxies. Try something like this:\nurllib.urlopen(your_url, proxies = {\"http\" : \"http://192.168.0.1:80\"})\n\n", "You could look at PycURL. I use cURL a lot in PHP and i love it. Though there is probably a neat way to do this currently in Python.\n" ]
[ 6, 1 ]
[]
[]
[ "http", "proxy", "python" ]
stackoverflow_0000894168_http_proxy_python.txt
Q: Send emails from Google App Engine I have a web server with Django, hosted with Apache server. I would like to configure Google App Engine for the email server. My web server should be able to use Google App Engine, when it makes any email send using EmailMessage or sendmail infrastructure of Google Mail API. I l...
Send emails from Google App Engine
I have a web server with Django, hosted with Apache server. I would like to configure Google App Engine for the email server. My web server should be able to use Google App Engine, when it makes any email send using EmailMessage or sendmail infrastructure of Google Mail API. I learnt that by using Remote API, I can ac...
[ "The example code for the remote APi gives you an interactive console from which you can access any of the modules in your application. I see no requirement that they be only datastore operations.\n", "You may want to use a third-party SMTP relaying service. Here's a list.\nMost of them have a simple API that let...
[ 2, 0 ]
[]
[]
[ "django", "google_app_engine", "mail_server", "python" ]
stackoverflow_0000892266_django_google_app_engine_mail_server_python.txt
Q: Is there free wiki source code that will run on the Google App Engine? I found the sample code cccwiki which is good, but I would like a wiki that keeps tracks of all revisions to the pages and lets users show diffs and revert to previous versions. A: You can start with http://code.google.com/p/google-app-engine...
Is there free wiki source code that will run on the Google App Engine?
I found the sample code cccwiki which is good, but I would like a wiki that keeps tracks of all revisions to the pages and lets users show diffs and revert to previous versions.
[ "You can start with http://code.google.com/p/google-app-engine-samples/downloads/detail?name=cccwiki_20080409.tar.gz&can=2&q= which is exactly \"A simple Google App Engine wiki application\" for you to download, try, and modify as you want. You can also browse its sources online at http://code.google.com/p/google-a...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "open_source", "python", "wiki" ]
stackoverflow_0000882454_google_app_engine_open_source_python_wiki.txt