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: Understanding Lambda X = 5 L = list(map(lambda x: 2**X, range(7))) print (L) ... I'm expecting this to return: [1, 2, 4, 8, 16, 32, 64] ...instead, it returns: [32, 32, 32, 32, 32, 32, 32] What am I doing wrong? A: Python is case-sensitive, so lambda x: 2**X means: take an argument, call it (lowercase) x, ign...
Understanding Lambda
X = 5 L = list(map(lambda x: 2**X, range(7))) print (L) ... I'm expecting this to return: [1, 2, 4, 8, 16, 32, 64] ...instead, it returns: [32, 32, 32, 32, 32, 32, 32] What am I doing wrong?
[ "Python is case-sensitive, so lambda x: 2**X means: take an argument, call it (lowercase) x, ignore it completely, and return 2 to the power of global variable (uppercase) X.\n", "Python is case-sensitive. x and X are different variables.\nBy the way, perhaps an easier way to construct L would be \nL=[2**x for x ...
[ 10, 4, 2, 0 ]
[]
[]
[ "lambda", "map", "python" ]
stackoverflow_0001938189_lambda_map_python.txt
Q: Checking if A is superclass of B in Python class p1(object): pass class p2(p1): pass So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ? A: using <class>.__bases__ seems to be what you're looking for... >>> class p1(object): pass >>> class p2(...
Checking if A is superclass of B in Python
class p1(object): pass class p2(p1): pass So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ?
[ "using <class>.__bases__ seems to be what you're looking for...\n>>> class p1(object): pass\n>>> class p2(p1): pass\n>>> p2.__bases__\n(<class '__main__.p1'>,)\n\n", "Yes, there is way. You can use a issubclass function.\nAs follows:\nclass p1(object):pass\nclass p2(p1):pass\n\nissubclass(p2, p1)\n\n", "Dependi...
[ 46, 41, 6, 5 ]
[]
[]
[ "python", "reflection", "superclass" ]
stackoverflow_0001938755_python_reflection_superclass.txt
Q: Merging multiple line segments My program uses PyOpenGL (so it's Python) with psyco. I have around 21,000 line segments which I need to render in each frame of my render (unless the user zooms in, in which case line segments are culled and not sent to the card at all). This is currently taking around 1.5 seconds e...
Merging multiple line segments
My program uses PyOpenGL (so it's Python) with psyco. I have around 21,000 line segments which I need to render in each frame of my render (unless the user zooms in, in which case line segments are culled and not sent to the card at all). This is currently taking around 1.5 seconds each frame to complete. That's just n...
[ "It's almost certainly the overhead of all the immediate mode function calls that's killing your performance. I would do the following.\nDon't use GL_LINE_STRIPS, use a single list of GL_LINES instead so they can be rendered in one go.\nUse glDrawArrays instead of immediate mode rendering:\nfloat* coordinates = {.....
[ 4, 0, 0 ]
[]
[]
[ "line_segment", "merge", "opengl", "pyopengl", "python" ]
stackoverflow_0001938831_line_segment_merge_opengl_pyopengl_python.txt
Q: Is there any libraries could import contacts from hotmail/live/aol account? I've import contacts from gmail by using gdata api, and is there any apis like that for hotmail/live/Aol ? A: There is Windows Live Contact API for Hotmail/Live mail. Yahoo Contact API for Yahoo also exists, but to this date, no AOL con...
Is there any libraries could import contacts from hotmail/live/aol account?
I've import contacts from gmail by using gdata api, and is there any apis like that for hotmail/live/Aol ?
[ "There is Windows Live Contact API for Hotmail/Live mail.\nYahoo Contact API for Yahoo also exists, but to this date, no AOL contact api. \nI would suggest you try openinviter (openinviter.com) to import contacts. Unfortunately, you will not have OAuth capabilities, but it is the best class out there and works with...
[ 2, 1, 1 ]
[]
[]
[ "api", "python" ]
stackoverflow_0001938945_api_python.txt
Q: changing image resolution in Python for a .bmp file I want to change the resolution of the .bmp image in python. ( i.e. the pixel/inch information) . Using PIL, for jpg image, for instance, the following code works fine import Image im = Image.open("myImg.jpg) im.save("output.jpg", dpi = (75, 75) ) If you view t...
changing image resolution in Python for a .bmp file
I want to change the resolution of the .bmp image in python. ( i.e. the pixel/inch information) . Using PIL, for jpg image, for instance, the following code works fine import Image im = Image.open("myImg.jpg) im.save("output.jpg", dpi = (75, 75) ) If you view this in some image editing software like GIMP, it shows th...
[ "I suspect that there aren't many programs out there that respect bmp resolution. Windows bitmaps are all 96 dpi.\nAlso, It looks as though PIL doesn't support a resolution parameter for bitmaps. My PIL/BmpImagePlugin.py just writes in $01000000 for the x & y resolution (i'm not sure what that translates to, but I'...
[ 2, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001938959_python_python_imaging_library.txt
Q: csv to sparse matrix in python I have a big csv file which lists connections between nodes in a graph. example: 0001,95784 0001,98743 0002,00082 0002,00091 So this means that node id 0001 is connected to node 95784 and 98743 and so on. I need to read this into a sparse matrix in numpy. How can i do this? I am ne...
csv to sparse matrix in python
I have a big csv file which lists connections between nodes in a graph. example: 0001,95784 0001,98743 0002,00082 0002,00091 So this means that node id 0001 is connected to node 95784 and 98743 and so on. I need to read this into a sparse matrix in numpy. How can i do this? I am new to python so tutorials on this wou...
[ "Example using lil_matrix (list of list matrix) of scipy.\n\nRow-based linked list matrix.\nThis contains a list (self.rows) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (self.data) of lists of these elements.\n\n$ cat 1938894-simplified.csv\n0,32\n1,21\n1,...
[ 12, 2, 2 ]
[]
[]
[ "data_structures", "python", "sparse_matrix" ]
stackoverflow_0001938894_data_structures_python_sparse_matrix.txt
Q: django + mysql + UTF-8 - Chars are not displayed I have both, django and mysql set to work with UTF-8. My base.html set utf-8 in head. row on my db : +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+...
django + mysql + UTF-8 - Chars are not displayed
I have both, django and mysql set to work with UTF-8. My base.html set utf-8 in head. row on my db : +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ | id | psn_id | name ...
[ "That source code, when placed into an otherwise empty HTML document, looks like this for me in Google Chrome, IE and Firefox:\n\nまいにけいっしょ\n\nWhich appears to be what you want.\nMy only thought is that that is not really the source code, and you've in fact got source code that looks like this:\n&amp;#12414;&amp;#12...
[ 3, 0, 0 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0001928087_django_python_unicode.txt
Q: Most used Python module for video processing? I need to: Open a video file Iterate over the frames of the file as images Do some analysis in this image frame of the video Draw in this image of the video Create a new video with these changes OpenCV isn't working for my webcam, but python-gst is working. Is this p...
Most used Python module for video processing?
I need to: Open a video file Iterate over the frames of the file as images Do some analysis in this image frame of the video Draw in this image of the video Create a new video with these changes OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst? Thank you!
[ "Do you mean opencv can't connect to your webcam or can't read video files recorded by it?\nHave you tried saving the video in an other format?\nOpenCV is probably the best supported python image processing tool \n", "I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've a...
[ 7, 3, 3, 0 ]
[]
[]
[ "image_processing", "python", "video_processing" ]
stackoverflow_0001480431_image_processing_python_video_processing.txt
Q: Python for Sony Ericsson Is it possible to install python on Sony Ericsson mobile phones? A: The Sony Ericsson Xperia x10 since Android phones can run python. Not sure about other Sony Ericsson phones A: Nokia Symbian S60 have Python: http://opensource.nokia.com/projects/pythonfors60/
Python for Sony Ericsson
Is it possible to install python on Sony Ericsson mobile phones?
[ "The Sony Ericsson Xperia x10 since Android phones can run python. Not sure about other Sony Ericsson phones\n", "Nokia Symbian S60 have Python: \nhttp://opensource.nokia.com/projects/pythonfors60/\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001939181_python.txt
Q: Django Sessions I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? A: The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you...
Django Sessions
I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?
[ "The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.\nThe memcache backend is much quicker than the database backend, but you run the risk of a session being purg...
[ 25, 19, 10, 3, 1 ]
[]
[]
[ "caching", "django", "mongodb", "python", "session" ]
stackoverflow_0000050568_caching_django_mongodb_python_session.txt
Q: Variables in python os.path I am new to python and I'm trying to create a program that creates a directory with todays date, create a sandbox into that directory and run the make file in the sandbox. I am having trouble getting the variables to be picked up in the os.path lines. The code is posted below: #!/usr/bi...
Variables in python os.path
I am new to python and I'm trying to create a program that creates a directory with todays date, create a sandbox into that directory and run the make file in the sandbox. I am having trouble getting the variables to be picked up in the os.path lines. The code is posted below: #!/usr/bin/python import mks_function ...
[ "a couple of notes: \n#!/usr/bin/env python \n# import mks_function .. you won't need this ...\n\nfrom mks_function import mks_create_sandbox \nimport os, datetime \n\n# import time, sys .. these aren't used in this snippet \n# import os.path .. just refer to os.path, since os is already imported\n\n# get today'...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001939496_python.txt
Q: Dynamically import class by name for static access I am generating class names dynamically and then want to import that class by its name to access a static method. This is the class to import in "the_module.py": class ToImport(object): @classmethod def initialize(cls, parameter): print parameter ...
Dynamically import class by name for static access
I am generating class names dynamically and then want to import that class by its name to access a static method. This is the class to import in "the_module.py": class ToImport(object): @classmethod def initialize(cls, parameter): print parameter According to a Blog post this is as far as I came: theM...
[ "I have done exactly what you did and I retrieved the class.\nIn [1]: theModule = __import__(\"the_module\")\n\nIn [2]: toImport = getattr(theModule, \"ToImport\")\n\nIn [3]: toImport.initialize(\"parameter\")\nparameter\n\nI am using Python 2.6.4. Could you explain further, what exactly doesn't work for you?\n" ]
[ 2 ]
[]
[]
[ "class", "import", "python" ]
stackoverflow_0001939622_class_import_python.txt
Q: Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this? I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 When I'm asking Python >>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav" True That's fine. When I ask >>> "u11-Phrase 100.wav" < ...
Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this?
I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 When I'm asking Python >>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav" True That's fine. When I ask >>> "u11-Phrase 100.wav" < "u11-Phrase 1000.wav" True That's fine, too. But when I ask >>> "u11-Phrase 101.wav" < "u1...
[ "You are looking for human sorting.\nThe reason 101.wav is not less than 1000.wav is that computers (not just Python) sort strings character by character, and the first difference between these two strings is where the first string has a '1' and the second string has a '0'. '1' is not less than '0', so the strings...
[ 16, 9 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001940056_python_sorting.txt
Q: Run XBMC plugins in a .net application Is there any way to use xbmc plugins in .net? im thinking about those plugins that provide access to media content like GameTrailers and stuff like that.. A: I believe the plugin system is based on Python. You may be able to use IronPython to run some of the plugins in XBM...
Run XBMC plugins in a .net application
Is there any way to use xbmc plugins in .net? im thinking about those plugins that provide access to media content like GameTrailers and stuff like that..
[ "I believe the plugin system is based on Python. You may be able to use IronPython to run some of the plugins in XBMC, although it may not be 100% compatible. You could also take the Python code and create a COM server object in which you could use .NET interop to interface with it.\n" ]
[ 1 ]
[]
[]
[ ".net", "python", "xbmc" ]
stackoverflow_0001940150_.net_python_xbmc.txt
Q: Python tell when an ftp transfer sits on completion I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes. How can I handle this gracefully using ftplib in pytho...
Python tell when an ftp transfer sits on completion
I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes. How can I handle this gracefully using ftplib in python? Sample python code: from ftplib import FTP ... ftp =...
[ "I've never used ftplib, but perhaps you could do:\n\nGet the name and size of the file you want.\nStart a new daemonic thread to download the file.\nIn the main thread, check every few seconds whether the file size on disk equals the target size.\nWhen it does, wait a few seconds to give the connection a chance to...
[ 0, 0 ]
[]
[]
[ "ftp", "network_programming", "python" ]
stackoverflow_0001105014_ftp_network_programming_python.txt
Q: Python: Synchronize Input and Output Between Threads Currently, I am trying to do a small project with sockets in Python, a two-user chatting system. import socket import threading #Callback. Print doesn't work across threads def data_recieved(data): print data #Thread class to gather input class socket_read...
Python: Synchronize Input and Output Between Threads
Currently, I am trying to do a small project with sockets in Python, a two-user chatting system. import socket import threading #Callback. Print doesn't work across threads def data_recieved(data): print data #Thread class to gather input class socket_read(threading.Thread): sock = object def __init__(sel...
[ "What you have here is not so much a synchronization issue as it is a presentation/UI issue. I would suggest making your life easier and picking some UI toolkit (curses, wxPython, pyqt) to handle interaction with the user. Using input() is very handy for quick-and-dirty one-off code, but it is not very sophisticate...
[ 1, 1 ]
[]
[]
[ "input", "multithreading", "python" ]
stackoverflow_0001940423_input_multithreading_python.txt
Q: Django index page best/most common practice I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this. I have seen folks creating apps to serv...
Django index page best/most common practice
I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this. I have seen folks creating apps to serve this purpose named various things (main, home, ...
[ "If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the direct to template view:\nurlpatterns = patterns('django.views.generic.simple',\n (r'^$', 'direct_to_template', {'te...
[ 19, 3 ]
[]
[]
[ "django", "indexing", "python" ]
stackoverflow_0001940528_django_indexing_python.txt
Q: Send a file with webpy and urllib2 I need to send a file to another server using oauth and webpy. For now I'll ignore the oauth part as sending the file itself is already a challenge. Here's my partial code: class create_video: def POST(self): x = web.input(video_original={}) At this point I want to send th...
Send a file with webpy and urllib2
I need to send a file to another server using oauth and webpy. For now I'll ignore the oauth part as sending the file itself is already a challenge. Here's my partial code: class create_video: def POST(self): x = web.input(video_original={}) At this point I want to send the file over the network using urllib2. N...
[ "You're coming from here, I guess.\nThe POST method defines how to receive data via POST requests, rather than send any data. In your code, the data from an incoming POST request is saved in x. How do you want to proceed now? If you want to send the data to another url, use urllib(2) as described here.\n" ]
[ 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0001939048_python_web.py.txt
Q: Interactive mode in matplotlib I want to dynamically update the scatter plot based on the y-axis data received from a socket connection. I used python matplot lib in interactive mode to do this, but during dynamic updation if i move the window to a different location or minimize the window then the plot updation s...
Interactive mode in matplotlib
I want to dynamically update the scatter plot based on the y-axis data received from a socket connection. I used python matplot lib in interactive mode to do this, but during dynamic updation if i move the window to a different location or minimize the window then the plot updation stops abruptly. How to do this? I hav...
[ "This page contains a couple of examples of dynamic plots with matplotlib and wxPython. And here is a version with PyQt.\n", "For this to work, you need to have a main loop for event handling, and your own event handler to redraw the plot when the window is resized or refreshed.\nYou'll find many examples for thi...
[ 4, 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001940387_matplotlib_python.txt
Q: Syntax quirks or why is that valid python In python 2.6, why is the following line valid? my_line = 'foo' 'bar' and if that is valid, why isn't the following: my_list = 1 2 The first example is string concatenation, however, the following isn't valid either (thanks god): foo = 'foo' bar = 'bar' foo_bar = foo ba...
Syntax quirks or why is that valid python
In python 2.6, why is the following line valid? my_line = 'foo' 'bar' and if that is valid, why isn't the following: my_list = 1 2 The first example is string concatenation, however, the following isn't valid either (thanks god): foo = 'foo' bar = 'bar' foo_bar = foo bar
[ "This is doing string literal concatenation. As noted in the documentation, advantages include the following:\n\nThis feature can be used to reduce the\n number of backslashes needed, to split\n long strings conveniently across long\n lines, or even to add comments to\n parts of strings...\n\nIt goes on to not...
[ 20, 8, 6, 5 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001940710_python_syntax.txt
Q: Redirect with additional variables I have view which in some cases redirects user to another addres. How can I redirect user, with additional variables (not GET, beacause that variable can be long text)? Currently I'm using HttpResponseRedirect. Cheers. A: You can't force a POST on redirect. Perhaps your best op...
Redirect with additional variables
I have view which in some cases redirects user to another addres. How can I redirect user, with additional variables (not GET, beacause that variable can be long text)? Currently I'm using HttpResponseRedirect. Cheers.
[ "You can't force a POST on redirect. Perhaps your best option is to store the variables in request.session, and then check for the presence of these variables in the view handler for the redirected URL.\nHere's some more info on sessions.\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001941362_django_python.txt
Q: How does/should global data in modules across packages be managed in Python/other languages? I am trying to design the package and module system for a programming language (Heron) which can be both compiled and interpreted, and from what I have seen I really like the Python approach. Python has a rich choice of mo...
How does/should global data in modules across packages be managed in Python/other languages?
I am trying to design the package and module system for a programming language (Heron) which can be both compiled and interpreted, and from what I have seen I really like the Python approach. Python has a rich choice of modules, which seems to contribute largely to its success. What I don`t know is what happens in Pyth...
[ "Well, you asked a lot of questions. Here are some hints to get a bit further:\n\na. Python code is lexed and compiled into Python specific instructions, but not compiled to machine executable code. The \".pyc\" file is automatically created whenever you run python code that does not match the existing .pyc tim...
[ 3, 3, 1 ]
[]
[]
[ "language_design", "module", "namespaces", "package", "python" ]
stackoverflow_0001940934_language_design_module_namespaces_package_python.txt
Q: Using multiprocessing pool of workers I have the following code written to make my lazy second CPU core working. What the code does basically is first find the desired "sea" files in the directory hierarchy and later execute set of external scripts to process these binary "sea" files to produce 50 to 100 text and ...
Using multiprocessing pool of workers
I have the following code written to make my lazy second CPU core working. What the code does basically is first find the desired "sea" files in the directory hierarchy and later execute set of external scripts to process these binary "sea" files to produce 50 to 100 text and binary files in number. As the title of the...
[ "I would start with getting a better feeling for what is going on with the worker process. The multiprocessing module comes with logging for its subprocesses if you need. Since you have simplified the code to narrow down the problem, I would just debug with a few print statements, like so (or you can PrettyPrint ...
[ 6, 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001586754_multiprocessing_python.txt
Q: calling an outside function in python I am trying to return (execute) a function from another file in an if statement. I have read that the return statement will not work, I was hoping someone would know what statement would allow me to call an outside function. The function creates a sandbox but if one exists I w...
calling an outside function in python
I am trying to return (execute) a function from another file in an if statement. I have read that the return statement will not work, I was hoping someone would know what statement would allow me to call an outside function. The function creates a sandbox but if one exists I want to pass the if statement. This is a sma...
[ "Say your function bar is in a file called foo.py on your Python path.\nIf foo.py contains this:\ndef bar():\n return True\n\nThen you can do this:\nfrom foo import bar\n\nif bar():\n print \"bar() is True!\"\n\n", "let's see what docs say:\n\nreturn may only occur syntactically nested in a function definition,...
[ 5, 2, 2, 1, 1, 0, 0 ]
[ "file1.py (comment out 2 of the versions)\n#version 1\nfrom file2 import outsidefunction\nprint (outsidefunction(3))\n\n#version 2\nimport file2\nprint (file2.outsidefunction(3))\n\n#version 3\nfrom file2 import *\nprint (outsidefunction(3))\n\nfile2.py\ndef outsidefunction(num):\n return num * 2\n\nCommand-Line...
[ -1 ]
[ "python", "return" ]
stackoverflow_0001928718_python_return.txt
Q: Python: Defining a class with only Integers Defined I am defining a class where only a set of integers is used. I cannot use the following datatypes in defining my class: set, frozenset and dictionaries. i need help defining: remove(self,i): Integer i is removed from the set. An exception is raised if i is not i...
Python: Defining a class with only Integers Defined
I am defining a class where only a set of integers is used. I cannot use the following datatypes in defining my class: set, frozenset and dictionaries. i need help defining: remove(self,i): Integer i is removed from the set. An exception is raised if i is not in self. discard(self, i): integer i is removed from the s...
[ "Assuming you are using an internal list based on what you've said, you could do it like so:\nclass Example(object):\n def __init__(self):\n self._list = list()\n\n # all your other methods here...\n\n def remove(self, i):\n try:\n self._list.remove(i)\n except ValueError:\n...
[ 2, 1, 1, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001930896_class_python.txt
Q: Creating a new virtualenv results in an error I'm trying to get virtualenv to work on my machine. I'm using python2.6, and after installing pip, and using pip to install virtualenv, running "virtualenv --no-site-packages cyclesg" results in the following: New python executable in cyclesg/bin/python Installing setu...
Creating a new virtualenv results in an error
I'm trying to get virtualenv to work on my machine. I'm using python2.6, and after installing pip, and using pip to install virtualenv, running "virtualenv --no-site-packages cyclesg" results in the following: New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /home/nub...
[ "Are you on mandriva?\nIn order to support multilib (mixing x86/x86_64) Mandriva messes up your python installation. They patched python, which breaks virtualenv; instead of fixing python, they then proceeded to patch virtualenv. This is useless if you are using your own virtualenv installed from pip.\nHere is the ...
[ 2, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0001941894_python_virtualenv.txt
Q: Add a member variable / method to a Python generator? Can I add a member variable / method to a Python generator? I want something along the following lines, so that I can "peek" at member variable j: def foo(): for i in range(10): self.j = 10 - i yield i gen = foo() for k in gen: print ge...
Add a member variable / method to a Python generator?
Can I add a member variable / method to a Python generator? I want something along the following lines, so that I can "peek" at member variable j: def foo(): for i in range(10): self.j = 10 - i yield i gen = foo() for k in gen: print gen.j print k Yes, I know that I can return i AND j ever...
[ "You could create an object and manipulate the __iter__ interface:\nclass Foo(object):\n def __init__(self):\n self.j = None\n def __iter__(self):\n for i in range(10):\n self.j = 10 - i\n yield i\n\nmy_generator = Foo()\n\nfor k in my_generator:\n print 'j is',my_genera...
[ 9, 2 ]
[]
[]
[ "generator", "local", "python" ]
stackoverflow_0001942328_generator_local_python.txt
Q: Why does ctypes WriteProcessMemory() fail? I have been trying to get this function working for some time now with no luck. def write_memory(self, address, data): PROCESS_ALL_ACCESS = 0x001F0FFF count = c_ulong(0) length = len(data) c_data = c_char_p(data[count.value:]) null = c_int(0) windl...
Why does ctypes WriteProcessMemory() fail?
I have been trying to get this function working for some time now with no luck. def write_memory(self, address, data): PROCESS_ALL_ACCESS = 0x001F0FFF count = c_ulong(0) length = len(data) c_data = c_char_p(data[count.value:]) null = c_int(0) windll.kernel32.SetLastError(10000) if not windll...
[ "There's nothing obviously wrong with the call. Most likely there just aren't any pages at 0x00050000 or the pages there aren't writable. \nWhy don't you try doing a VirtualQuery on the bytes you are trying to write to and see if it's actually writable? Most random addresses aren't.\n" ]
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001942322_ctypes_python.txt
Q: How properly bundle&install python to windows users I need to redistribute Python 2.6 for my users. Currently, I execute the silent instalation for the msi installer from http://www.python.org/download/, but I have some problems, like if other version of python is installed this not get the default. In the other h...
How properly bundle&install python to windows users
I need to redistribute Python 2.6 for my users. Currently, I execute the silent instalation for the msi installer from http://www.python.org/download/, but I have some problems, like if other version of python is installed this not get the default. In the other hand, despite this could be rare, if a user have already p...
[ "I haven't used it, beyond some initial research, but ActiveState's ActivePython generally does what you want, if you're looking for a commercial pre-built solution.\nI have worked on software that included its own bundled Python, and there were never any problems with conflicts. In our case, it was installed alon...
[ 2 ]
[]
[]
[ "deployment", "installation", "python", "windows" ]
stackoverflow_0001942399_deployment_installation_python_windows.txt
Q: DOM to use with SpiderMonkey? I'm trying to use the GoogleMaps JavaScript library from inside of SpiderMonkey using the python wrapper, but I can't because of the lack of a DOM. Is there some way I can integrate a DOM into this so that I can get this to work? A: env.js implements the DOM. I know it at least work...
DOM to use with SpiderMonkey?
I'm trying to use the GoogleMaps JavaScript library from inside of SpiderMonkey using the python wrapper, but I can't because of the lack of a DOM. Is there some way I can integrate a DOM into this so that I can get this to work?
[ "env.js implements the DOM. I know it at least works in SpiderMonkey and Rhino but SpiderMonkey may have issues with things like XMLHttpRequest.\n" ]
[ 4 ]
[]
[]
[ "dom", "javascript", "python", "spidermonkey" ]
stackoverflow_0001942344_dom_javascript_python_spidermonkey.txt
Q: Python GUI (glade) to display output of shell process I'm writing a python application that runs several subprocesses using subprocess.Popen objects. I have a glade GUI and want to display the output of these commands (running in subprocess.Popen) in the gui in real time. Can anyone suggest a way to do this? What ...
Python GUI (glade) to display output of shell process
I'm writing a python application that runs several subprocesses using subprocess.Popen objects. I have a glade GUI and want to display the output of these commands (running in subprocess.Popen) in the gui in real time. Can anyone suggest a way to do this? What glade object do I need to use and how to redirect the outpu...
[ "After lots of reading and not getting the results I wanted, I found another method that works.\nIt goes like this\n#!/usr/bine/env python\nimport subprocess\nimport gtk\n\n### Of course, you should have the gui built and know which widgets to use for this.\nviewer = self.builder.get_object('txtview')\nproc = subpr...
[ 2, 2, 1 ]
[]
[]
[ "glade", "python", "user_interface" ]
stackoverflow_0001929018_glade_python_user_interface.txt
Q: anyone have example python code that sends mail using sendmail and subprocess? I'm kind of confused about how subprocess.Popen works. If anyone has example code that sends email using the subprocess module and sendmail that'd be great. A: This doesn't directly answer the question, but given your response to a co...
anyone have example python code that sends mail using sendmail and subprocess?
I'm kind of confused about how subprocess.Popen works. If anyone has example code that sends email using the subprocess module and sendmail that'd be great.
[ "This doesn't directly answer the question, but given your response to a comment by \"DNS\", it might solve your problem.\nWhen sending SMTP mail, you need to understand that the \"from\" and \"to\" addresses that you pass to the smtplib.sendmail() routine as arguments are not the same thing as what you see in the ...
[ 2, 0 ]
[]
[]
[ "python", "sendmail", "subprocess" ]
stackoverflow_0001942305_python_sendmail_subprocess.txt
Q: how to properly destroy gtk.Dialog objects/widgets Noob @ programming with python and pygtk. I'm creating an application which includes a couple of dialogs for user interaction. #!usr/bin/env python import gtk info = gtk.MessageDialog(type=gtk.DIALOG_INFO, buttons=gtk.BUTTONS_OK) info.set_property('title', 'Test i...
how to properly destroy gtk.Dialog objects/widgets
Noob @ programming with python and pygtk. I'm creating an application which includes a couple of dialogs for user interaction. #!usr/bin/env python import gtk info = gtk.MessageDialog(type=gtk.DIALOG_INFO, buttons=gtk.BUTTONS_OK) info.set_property('title', 'Test info message') info.set_property('text', 'Message to be d...
[ "@mg\nMy bad. Your code is correct (and I guess my initial code was too)\nThe reason my dialog was remaining on the screen is because my gtk.main loop is running on a separate thread.\nSo all I had to was enclose your code (corrected version of mine) in between a\ngtk.gdk.threads_enter()\n\nand a \ngtk.gdk.threads_...
[ 3, 2 ]
[]
[]
[ "dialog", "pygtk", "python" ]
stackoverflow_0001942295_dialog_pygtk_python.txt
Q: Simple code but can't find the error (PyS60 but not specific) I'm a Python beginner and now it's freakin me out: L = [] file = urllib.urlopen("http://someurl.com/someText.txt") line = file.readline() while line != "" : L.append(line) line = file.readline() appuifw.selection_list(choices=L) and I get this erro...
Simple code but can't find the error (PyS60 but not specific)
I'm a Python beginner and now it's freakin me out: L = [] file = urllib.urlopen("http://someurl.com/someText.txt") line = file.readline() while line != "" : L.append(line) line = file.readline() appuifw.selection_list(choices=L) and I get this error: line = file.readline() ^ SyntaxError: invalid syntax Does any...
[ "Rewriting to\nfile = urllib.urlopen(\"http://blabla.com/bla.txt\")\nlines1 = file.readlines()\nfor li in lines1:\n L.append(li)\nindex = appuifw.selection_list(choices=L)\n\nit seems to work now.\n(Still problems left but I think it's the URL)\n", "Show the invisibles. I bet there is an illegal character (nul...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "pys60", "python" ]
stackoverflow_0001942559_pys60_python.txt
Q: String class internals - caching character offset to byte relationship if using UTF-8 When writing a custom string class that stores UTF-8 internally (to save memory) rather than UTF-16 from scratch is it feasible to some extent cache the relationship between byte offset and character offset to increase performanc...
String class internals - caching character offset to byte relationship if using UTF-8
When writing a custom string class that stores UTF-8 internally (to save memory) rather than UTF-16 from scratch is it feasible to some extent cache the relationship between byte offset and character offset to increase performance when applications use the class with random access? Does Perl do this kind of caching of ...
[ "Perl distinguishes between Unicode and non-Unicode strings. Unicode strings are implemented using UTF-8 internally. Non-Unicode does not necessarily mean 7-bit ASCII, though, it could be any character that can be represented in the current locale as a single byte. \n", "I think the answer is: in general, it's no...
[ 2, 1, 1 ]
[]
[]
[ "java", "objective_c", "perl", "python", "utf_8" ]
stackoverflow_0001942282_java_objective_c_perl_python_utf_8.txt
Q: How to generate an audio stream using gst-python? I'm looking to generate a stream in gstreamer, and I'd prefer to do it from python if possible. This points towards using gst-python, but I don't see a clear way to do it. It looks like creating a new stream would require making a gstreamer plugin, which gst-python...
How to generate an audio stream using gst-python?
I'm looking to generate a stream in gstreamer, and I'd prefer to do it from python if possible. This points towards using gst-python, but I don't see a clear way to do it. It looks like creating a new stream would require making a gstreamer plugin, which gst-python doesn't seem to be able to do. To clarify, I'd like to...
[ "Take a look at appsrc (gst-inspect appsrc). I used its counterpart appsink to get data out of a gstreamer pipeline.\nAnd here's an (almost)-working example. http://gstreamer-devel.966125.n4.nabble.com/appsrc-random-crash-td973529.html\n" ]
[ 3 ]
[]
[]
[ "audio", "gstreamer", "python" ]
stackoverflow_0001932120_audio_gstreamer_python.txt
Q: Using paver and nose together with an atypical directory structure I'm trying to write a task for Paver that will run nosetests on my files. My directory structure looks like this: project/ file1.py file2.py file3.py build/ pavement.py subproject/ file4.py test/ file5.py f...
Using paver and nose together with an atypical directory structure
I'm trying to write a task for Paver that will run nosetests on my files. My directory structure looks like this: project/ file1.py file2.py file3.py build/ pavement.py subproject/ file4.py test/ file5.py file6.py Doctests (using the --with_doctest option) should be run on all...
[ "Is this at all close to what you're trying to get at?\nfrom paver.easy import sh, path\n__path__ = path(__file__).abspath().dirname()\n\n@task\ndef setup_nose_plugin():\n # ... do your plugin setup here.\n\n@task\n@needs('setup_nose_plugin')\ndef nosetests():\n nose_options = '--with-doctest' # Put your comm...
[ 2 ]
[]
[]
[ "nose", "paver", "python" ]
stackoverflow_0000722992_nose_paver_python.txt
Q: A little misunderstanding timers in python can somebody tell me how to use this class timers from python in my code more than one time. import MOD class timer: def __init__(self, seconds): self.start(seconds) def start(self, seconds): self.startTime = MOD.secCounter() self.expir...
A little misunderstanding timers in python
can somebody tell me how to use this class timers from python in my code more than one time. import MOD class timer: def __init__(self, seconds): self.start(seconds) def start(self, seconds): self.startTime = MOD.secCounter() self.expirationTime = self.startTime + seconds if...
[ "Close - the argument to timers.timer is the number of seconds that the timer should time for at first. But every time you call timers.timer(), you'll get a new timer instance.\nSo your code could look more like:\n timerB = timers.timer(1800)\n while 1: \n if timerB.isexpired(): \n print 'tim...
[ 2 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0001943182_python_timer.txt
Q: wxPython progress bar I can't use wx.ProgressDialog because I need to add extra contents to the dialog box (a pause button and information about what is currently being processed). Is there a control for just the progress bar that I can use in my own dialog box? I could of course draw something simple myself, but...
wxPython progress bar
I can't use wx.ProgressDialog because I need to add extra contents to the dialog box (a pause button and information about what is currently being processed). Is there a control for just the progress bar that I can use in my own dialog box? I could of course draw something simple myself, but since the program needs to...
[ "What about wxGauge which displays a horizontal or vertical bar?\nhttp://www.wxpython.org/docs/api/wx.Gauge-class.html\nMore complete C++ doc:\nhttp://docs.wxwidgets.org/2.6/wx_wxgauge.html#wxgauge \n", "You could always create your own derivative of wx.Dialog and using a sizer, add in the widgets you require.\nH...
[ 6, 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001883528_python_wxpython.txt
Q: Python regular expression inconsistency I am getting different results based on whether I precompile a regular expression: >>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean') ' Bean' >>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE) 'Mr Bean' The Python documentation says Some of the functions are simplified vers...
Python regular expression inconsistency
I am getting different results based on whether I precompile a regular expression: >>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean') ' Bean' >>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE) 'Mr Bean' The Python documentation says Some of the functions are simplified versions of the full featured methods for compile...
[ "re.sub() can't accept the re.IGNORECASE, it appears.\nThe documentation states:\n\nsub(pattern, repl, string, count=0) \nReturn the string obtained by replacing the leftmost\nnon-overlapping occurrences of the pattern in string by the\nreplacement repl. repl can be either a string or a callable;\nif a string, bac...
[ 12, 5, 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001943400_python_regex.txt
Q: python fetching multiple pages using post and cookies Got a test site that I'm fetching. The site uses the POST method, as well as cookies. (Not sure that the cookies are critical, but i'm inclined to think they are..) The app presents a page, with a "next button" to generate the subsequent pages. I've used LiveHt...
python fetching multiple pages using post and cookies
Got a test site that I'm fetching. The site uses the POST method, as well as cookies. (Not sure that the cookies are critical, but i'm inclined to think they are..) The app presents a page, with a "next button" to generate the subsequent pages. I've used LiveHttpHeaders/Firefof to determine what the post data should be...
[ "I'm really not sure what's going wrong. It may not be helpful, but a different way to do it:\nOpen a table-row for each 1st page submit then keep only the rowId in the cookie and add to the row with subsequent accesses.\ntf.\n" ]
[ 0 ]
[]
[]
[ "cookies", "post", "python", "urllib2" ]
stackoverflow_0001943546_cookies_post_python_urllib2.txt
Q: redirecting standard output to the calling process Im no bash expert so bear with me I have a python script thats starting other processes, which then emit log messages on stdout. what bash command would I use to redirect stdout of those child processes back to the stdout of the parent process (the python script...
redirecting standard output to the calling process
Im no bash expert so bear with me I have a python script thats starting other processes, which then emit log messages on stdout. what bash command would I use to redirect stdout of those child processes back to the stdout of the parent process (the python script thats starting the processes)? thank you in advance
[ "If you just want to capture the output of the child processes in your python script, the best way to do it would be to use the subprocess module:\nimport subprocess\n\np = subprocess.Popen(['/bin/ls', '-l'], stdout=subprocess.PIPE)\n(out, _) = p.communicate()\nprint \"Output:\", out\n\n", "I'm assuming you're us...
[ 3, 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0001943712_bash_python.txt
Q: Grab Focus for Frame after Shortcut Pressed in wxPython on GNOME I'm building an app that uses global shortcut keys (using python-keybinder), but there's a problem. The frame pops up and raises properly but doesn't have focus. I have to click on frame. After I press my keyboard shortcut my frame appears, but it i...
Grab Focus for Frame after Shortcut Pressed in wxPython on GNOME
I'm building an app that uses global shortcut keys (using python-keybinder), but there's a problem. The frame pops up and raises properly but doesn't have focus. I have to click on frame. After I press my keyboard shortcut my frame appears, but it is not focused. I can see that the frame I was focused on previously (e...
[ "How are you showing the frmae initially, with frame.Show()? I'm not sure if you're saying the frame itself doesn't have focus (but/or a child of the frame does), or your application doesn't have focus?\nAre you calling SetFocus in the Frame that initialises all your widgets? It could be an issue of the focus being...
[ 0 ]
[]
[]
[ "gnome", "python", "wxpython" ]
stackoverflow_0001943682_gnome_python_wxpython.txt
Q: Open 3rd party Application with Python I am on Windows XP and have a 3rd party application that I want to be able to open using a Python script. How do I go about doing it? from win32com.client import Dispatch mySuite = Dispatch("TestSuite.Application") throws an error File "C:\Python26\Lib\site-packages\pythonw...
Open 3rd party Application with Python
I am on Windows XP and have a 3rd party application that I want to be able to open using a Python script. How do I go about doing it? from win32com.client import Dispatch mySuite = Dispatch("TestSuite.Application") throws an error File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312...
[ "Looks like the TestSuite.Application COM class has not been registered -- try opening it in, say, VBScript, to verify, and it should also fail. In which case maybe you can fix it with regsvr32.exe or similar tools.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001943367_python.txt
Q: How to get value on a certain index, in a python list? I have a list which looks something like this List = [q1,a1,q2,a2,q3,a3] I need the final code to be something like this dictionary = {q1:a1,q2:a2,q3:a3} if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can g...
How to get value on a certain index, in a python list?
I have a list which looks something like this List = [q1,a1,q2,a2,q3,a3] I need the final code to be something like this dictionary = {q1:a1,q2:a2,q3:a3} if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it?
[ "Python dictionaries can be constructed using the dict class, given an iterable containing tuples. We can use this in conjunction with the range builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict, such that the values organize themselves into key/value pairs in t...
[ 11, 11, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001943824_python.txt
Q: Why isn't count() working the way I expect in my code? class FriendshipManager(models.Manager): def are_friends(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count() > 0: return True if self.filter(from_user=user2, to_user=user1).count() > 0:...
Why isn't count() working the way I expect in my code?
class FriendshipManager(models.Manager): def are_friends(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count() > 0: return True if self.filter(from_user=user2, to_user=user1).count() > 0: return True return False and i...
[ "The issue here is that you've mixed up two methods with the same name.\nOn a sequence in Python, count() works exactly has Dustin describes to \"count the number of occurrences of the parameter in the sequence.\"\nThe code you're referencing however, is from a Django model. There, calling count() on the filter ob...
[ 8, 4, 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001944064_django_python.txt
Q: What is the relationship between __getattr__ and getattr? I know this code is right: class A: def __init__(self): self.a = 'a' def method(self): print "method print" a = A() print getattr(a, 'a', 'default') print getattr(a, 'b', 'default') print getattr(a, 'method', 'defa...
What is the relationship between __getattr__ and getattr?
I know this code is right: class A: def __init__(self): self.a = 'a' def method(self): print "method print" a = A() print getattr(a, 'a', 'default') print getattr(a, 'b', 'default') print getattr(a, 'method', 'default') getattr(a, 'method', 'default')() And this is wrong:...
[ "Alex's answer was good, but providing you with a sample code since you asked for it :)\nclass foo:\n def __init__(self):\n self.a = \"a\"\n def __getattr__(self, attribute):\n return \"You asked for %s, but I'm giving you default\" % attribute\n\n\n>>> bar = foo()\n>>> bar.a\n'a'\n>>> bar.b\n\"...
[ 63, 39, 19 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0001944625_getattr_python.txt
Q: What's the difference between _b and b in this place class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(): print 'bbbb' a.py class a: def __init__(self): self._b()#why here...
What's the difference between _b and b in this place
class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(): print 'bbbb' a.py class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'...
[ "Prefixing a variable or function name with an underscore is a convention in Python to indicate that the variable is private. From the docs:\n\nPrivate” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code...
[ 10, 8, 4, 3, 0, 0 ]
[ "The class object a has an attribute _b which is found when asking for self._b. The same class object a has no attribute b.\n_b and b are as different as beehive and zulu. \nYou will get a parameter error when calling self._b because Python will implicitly pass self as the first argument to a bound method. The s...
[ -1 ]
[ "python" ]
stackoverflow_0001943863_python.txt
Q: Singleton python generator? Or, pickle a python generator? I am using the following code, with nested generators, to iterate over a text document and return training examples using get_train_minibatch(). I would like to persist (pickle) the generators, so I can get back to the same place in the text document. Howe...
Singleton python generator? Or, pickle a python generator?
I am using the following code, with nested generators, to iterate over a text document and return training examples using get_train_minibatch(). I would like to persist (pickle) the generators, so I can get back to the same place in the text document. However, you cannot pickle generators. Is there a simple workaround...
[ "You can create a standard iterator object, it just won't be as convenient as the generator; you need to store the iterator's state on the instace (so that it is pickled), and define a next() function to return the next object:\nclass TrainExampleIterator (object):\n def __init__(self):\n # set up interna...
[ 2, 2, 0, 0, 0 ]
[ "You can try create callable object: \nclass TrainExampleGenerator:\n\n def __call__(self):\n for l in open(HYPERPARAMETERS[\"TRAIN_SENTENCES\"]):\n prevwords = []\n for w in string.split(l):\n w = string.strip(w)\n id = None\n prevwords....
[ -1 ]
[ "generator", "persistent", "pickle", "python", "singleton" ]
stackoverflow_0001939015_generator_persistent_pickle_python_singleton.txt
Q: Having trouble with Python's telnetlib module I have a basic chat server which I can easily connect to with telnet. I simply enter the host and port and, without any further authentication, can begin entering commands that the server can interpret. In an effort to simulate user traffic, I would like to create a sc...
Having trouble with Python's telnetlib module
I have a basic chat server which I can easily connect to with telnet. I simply enter the host and port and, without any further authentication, can begin entering commands that the server can interpret. In an effort to simulate user traffic, I would like to create a script that will open telnet, connect to the server, ...
[ "Perhaps adding a newline would help?\nmyTel.write('login\\n')\n\nI'd also recommend using some network sniffing tool (i.e. Wireshark) to verify that you're really sending what you intended.\n", "In your code, you write to the server, but in order to receive data, you'll eventually have to one of the read methods...
[ 3, 0, 0 ]
[]
[]
[ "python", "telnet" ]
stackoverflow_0001945084_python_telnet.txt
Q: Format for DateTimeField Possible Duplicate: Converting string into datetime In Django I get this error "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." when I try to assign a string "22-DEC-2009" to a DateTimeField in a model. How is it possible to make DateTimeField accept a date string in f...
Format for DateTimeField
Possible Duplicate: Converting string into datetime In Django I get this error "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." when I try to assign a string "22-DEC-2009" to a DateTimeField in a model. How is it possible to make DateTimeField accept a date string in format "22-DEC-2009"?
[ "You can pass the input formats as input_formats argument to DateTimeField, so you can do this\n# you can keep a list of formats yourself, or copy from django 1.2 version e.g.\n# my_formats = fields.DEFAULT_DATETIME_INPUT_FORMATS + ['%d-%b-%Y']\n# for latest django use this\nfrom django.utils.formats import get_for...
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001945239_django_python.txt
Q: Why does the following code always output 16? def makeActions(): acts=[] for i in range(5): print len(acts) acts.append(lambda x: i ** x) print acts[i] return acts acts=makeActions() for i in range(5): print acts[i](2) Output: 16 16 16 16 16 Expected output: 0 1 4 9 16 A:...
Why does the following code always output 16?
def makeActions(): acts=[] for i in range(5): print len(acts) acts.append(lambda x: i ** x) print acts[i] return acts acts=makeActions() for i in range(5): print acts[i](2) Output: 16 16 16 16 16 Expected output: 0 1 4 9 16
[ "Because the i in the lambda is probably not what you expect. To verify this, change the code:\nacts.append(lambda x: (i, i ** x))\n\nNow the print tells you the value of i:\n(4, 16)\n(4, 16)\n(4, 16)\n(4, 16)\n(4, 16)\n\nThis means that the lambda doesn't copy the value of i but keeps a reference to the variable, ...
[ 23, 6, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001945270_python.txt
Q: How can I copy a remote image over HTTP to gtk.gdk.pixbuf by Python? this is first post here and I am a noob programmer. This may be a stupid question. I'd like to create a personal Twitter notifier on GNOE Desktop. And I've decided to use pynotify and Tweepy. Now I just want to make pynotify show Twitter user's i...
How can I copy a remote image over HTTP to gtk.gdk.pixbuf by Python?
this is first post here and I am a noob programmer. This may be a stupid question. I'd like to create a personal Twitter notifier on GNOE Desktop. And I've decided to use pynotify and Tweepy. Now I just want to make pynotify show Twitter user's icon, and there seems to be 2 ways using pynotify; setting URI to local ima...
[ "did you mean something like this?\n" ]
[ 2 ]
[]
[]
[ "gtk", "pynotify", "python" ]
stackoverflow_0001945331_gtk_pynotify_python.txt
Q: MYSQLDB python module I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement: connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor. Again using the DB handle above, iam pe...
MYSQLDB python module
I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement: connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor. Again using the DB handle above, iam performing a "select" stateme...
[ "With no code, I can only make a guess: try not closing the cursor until you are done with that connection. I think that calling cursor() again after calling cursor.close() will just give you a reference to the same cursor, which can no longer be used for queries.\nI am not 100% sure if that is the intended behav...
[ 0, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001922623_mysql_python.txt
Q: python add a new div every 3rd iteration I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding <div> around each group of 3 products will solve this is the template file at the moment {% for product in category.products.all ...
python add a new div every 3rd iteration
I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding <div> around each group of 3 products will solve this is the template file at the moment {% for product in category.products.all %} <div class="{% cycle 'clear' '' '' ...
[ "codeape's solution only works if you are using a very recent SVN checkout of Django trunk. If you're using version 1.1 or below, that syntax is not supported.\nInstead, you can use the divisibleby filter:\n{% if forloop.counter|divisibleby:3 %}<div>{% endif %}\n\n", "Use forloop.counter and a modulo operator ins...
[ 40, 10 ]
[]
[]
[ "django_templates", "python" ]
stackoverflow_0001945379_django_templates_python.txt
Q: Python Format string "}" fill Python 2.6 defines str.format(…), which, from Python 3.0, is preferred to the old % style of string formatting. Looking at the "mini-language", however, it seems that it is impossible to use the } character as a fill character. This seems like a strange omission to me. Is it possible ...
Python Format string "}" fill
Python 2.6 defines str.format(…), which, from Python 3.0, is preferred to the old % style of string formatting. Looking at the "mini-language", however, it seems that it is impossible to use the } character as a fill character. This seems like a strange omission to me. Is it possible to somehow escape that character an...
[ "You could always specify it as a separate parameter like so:\n>>> \"The word is {0:{1}<10}\".format(\"spam\", \"}\")\n'The word is spam}}}}}}'\n\nSee, it gets passed in and used in place of {1}.\n" ]
[ 8 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0001945230_python_string_formatting.txt
Q: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists I have a dataset of ca. 9K lists of variable length (1 to 100K elements). I need to calculate the length of the intersection of all possible 2-list combinations in this dataset. Note that elements in each list are...
Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists
I have a dataset of ca. 9K lists of variable length (1 to 100K elements). I need to calculate the length of the intersection of all possible 2-list combinations in this dataset. Note that elements in each list are unique so they can be stored as sets in python. What is the most efficient way to perform this in python? ...
[ "If your sets are stored in s, for example:\ns = [set([1, 2]), set([1, 3]), set([1, 2, 3]), set([2, 4])]\n\nThen you can use itertools.combinations to take them two by two, and calculate the intersection (note that, as Alex pointed out, combinations is only available since version 2.6). Here with a list comrehensio...
[ 3, 2, 0 ]
[]
[]
[ "combinations", "intersection", "list", "python", "set" ]
stackoverflow_0001757698_combinations_intersection_list_python_set.txt
Q: Sqlalchemy query not commiting I'm trying to create a simple unique username function for use in a Formencode schema. Here is the function: class UniqueUsername(formencode.FancyValidator): def _to_python(self, value, state): user = DBSession.query(User.user_name).filter(User.username==value) ...
Sqlalchemy query not commiting
I'm trying to create a simple unique username function for use in a Formencode schema. Here is the function: class UniqueUsername(formencode.FancyValidator): def _to_python(self, value, state): user = DBSession.query(User.user_name).filter(User.username==value) if user is not None: ...
[ "It should be:\nuser = DBSession.query(User.user_name).filter(User.username==value).first()\n\nalso: is it User.user_name or User.username ?\n" ]
[ 4 ]
[]
[]
[ "formencode", "python", "sqlalchemy" ]
stackoverflow_0001944423_formencode_python_sqlalchemy.txt
Q: converting a zcml based python script to a standalone script in zope/plone I have a python class working in zope 3 zcml kind of way, but i want to move the python into a standalone script that a could access via something along the lines of tal:content='context/get_tags'. This is the code as it stands: class TagLi...
converting a zcml based python script to a standalone script in zope/plone
I have a python class working in zope 3 zcml kind of way, but i want to move the python into a standalone script that a could access via something along the lines of tal:content='context/get_tags'. This is the code as it stands: class TagListView(BrowserView): def getCategories(self): categories = set() for ca...
[ "You can access views from page templates with the @@ syntax: context/@@viewname:\ntal:define=\"view context/@@get_tags;\n entries view/entries;\"\n\n" ]
[ 2 ]
[]
[]
[ "plone", "python", "zope" ]
stackoverflow_0001945812_plone_python_zope.txt
Q: Variable referenced instead of copied When I run the code below it removes deleted_partner from B. But as it removes it from B it also removes it from A. So that when I try to remove it from A the program crashes. What is the problem? for deleted_partner in self.list_of_trading_partners: B = A[:] print("t...
Variable referenced instead of copied
When I run the code below it removes deleted_partner from B. But as it removes it from B it also removes it from A. So that when I try to remove it from A the program crashes. What is the problem? for deleted_partner in self.list_of_trading_partners: B = A[:] print("t", deleted_partner) print(B[self.ID].li...
[ "You're not removing from B or A, but from A[some_ID].list_of_trading_partners and B[some_ID].list_of_trading_partners. [:] only makes a \"shallow copy\" of the list, in that it creates a new, separate list, but the elements contained in that list (one of which list_of_trading_partners is an attribute of) are not c...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001946109_python.txt
Q: Best way to serialize a range of hours to meaningful data A part of my web app involves creating 'appointments' (shifts) using a drag-and-drop selector for each day. Currently, this data is serialized to something like this: 9,10,11,12,13,14,15,16,76,77,78,298,299,300,301,302,303,304, Where each number represents...
Best way to serialize a range of hours to meaningful data
A part of my web app involves creating 'appointments' (shifts) using a drag-and-drop selector for each day. Currently, this data is serialized to something like this: 9,10,11,12,13,14,15,16,76,77,78,298,299,300,301,302,303,304, Where each number represents the nth half-hour of the week (so 304 is the 300th half-hour o...
[ "You're talking about intervals. \nThe best way to have an interval is a start time and a duration.\nclass Shift( object ):\n def __init__( self, start, length ):\n self.start= start\n self.length= length\n def __repr__( self ):\n return \"Shift(%d,%d)\" % ( self.start, self.length )\...
[ 2, 1 ]
[]
[]
[ "javascript", "jquery", "python", "serialization" ]
stackoverflow_0001946265_javascript_jquery_python_serialization.txt
Q: How to create an internationalized Google App Engine application I would like to provide my Python GAE website in the user's own language, using only the tools available directly in App Engine. For that, I would like to use GNU gettext files (.po and .mo files). Has someone successfully combined Python Google App...
How to create an internationalized Google App Engine application
I would like to provide my Python GAE website in the user's own language, using only the tools available directly in App Engine. For that, I would like to use GNU gettext files (.po and .mo files). Has someone successfully combined Python Google App Engine and gettext files? If so, could you please provide the steps y...
[ "As my needs were simple, I used a simple hack instead of (unavailable) gettext. I created a file with string translations, translate.py. Approximately like this:\nen={}\nru={}\n\nen['default_site_title']=u\"Site title in English\"\nru['default_site_title']=u\"НазваниС сайта ΠΏΠΎ-русски\"\n\nThen in the main code I d...
[ 6, 4 ]
[]
[]
[ "gettext", "google_app_engine", "internationalization", "python" ]
stackoverflow_0001946251_gettext_google_app_engine_internationalization_python.txt
Q: asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn I need to have an at-home project now that I'm working on Python/Django at work. I'd like to learn something new, so I was thinking of checking out Java. What's the most well respected web framework for deploying Java web apps? T...
asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn
I need to have an at-home project now that I'm working on Python/Django at work. I'd like to learn something new, so I was thinking of checking out Java. What's the most well respected web framework for deploying Java web apps? The only reason I'm not checking out ruby on rails is because of how similar the ORM and oth...
[ "With that range of skills, why don't you learn something more outside your comfort zone, like carpentry or painting, or any of hundreds of other skills that have little to do with your field.\nAt some point, all languages are the same and you'll get scant benefit from learning another. \nWhereas, with something to...
[ 14, 6, 4, 3, 2, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "haskell", "java", "lisp", "python", "smalltalk" ]
stackoverflow_0001583597_haskell_java_lisp_python_smalltalk.txt
Q: Python: How to change hex string int integer? Possible Duplicate: Convert hex string to int in Python Hello, I want to use some string like "0xFF123456" as a 32-bit unsigned integer. Please give me some advice. Thanks. A: a = int("0xFF123456", 0) If it doesn't have a 0x prefix you could also use: a = int("FF12...
Python: How to change hex string int integer?
Possible Duplicate: Convert hex string to int in Python Hello, I want to use some string like "0xFF123456" as a 32-bit unsigned integer. Please give me some advice. Thanks.
[ "a = int(\"0xFF123456\", 0)\nIf it doesn't have a 0x prefix you could also use:\na = int(\"FF123456\", 16)\n", ">>> int('0xFF123456', 16)\n4279383126\n>>> \n\n", "try this:\n>>>print int(\"0xFF123456\",0)\n\nor\n>>>print int(\"0xFF123456\",16)\n\n" ]
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001946796_python.txt
Q: Making Python code Pythonic How would you make the give code more Pythonic? I want to get Paths out of the sample like /usr/local/sources/devel/algebra.py: def _alg(...) without the character :. My code import os FunctionPath = "/usr/local/sources/devel/sage-main/build/sage/" cmd = "grep -R 'def ' %s | cut -d' ' -...
Making Python code Pythonic
How would you make the give code more Pythonic? I want to get Paths out of the sample like /usr/local/sources/devel/algebra.py: def _alg(...) without the character :. My code import os FunctionPath = "/usr/local/sources/devel/sage-main/build/sage/" cmd = "grep -R 'def ' %s | cut -d' ' -f1" % (FunctionPath) cmd += ' &' ...
[ "Why not do this:\nfor line in open(FunctionPath):\n line = line.strip()\n if line.startswith('def '):\n print '%s: %s' % (FunctionPath, line.partition(':')[0])\n\nAnd if you use fileinput module you can iterate over lines from multiple input streams very easily:\nimport fileinput\nfor line in fileinpu...
[ 11, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001946701_python.txt
Q: Solr Facet Range with Integers My index contains peoples information, name, age, phone email etc. I am faceting on Age. I group ages kinda like Date Range functionality. My ranges are: 0 to 10 11 to 20 21 to 30 31 to 40 etc etc When I do a query: ?q=*:*&facet=true&fq=age:[21+TO+30] It return...
Solr Facet Range with Integers
My index contains peoples information, name, age, phone email etc. I am faceting on Age. I group ages kinda like Date Range functionality. My ranges are: 0 to 10 11 to 20 21 to 30 31 to 40 etc etc When I do a query: ?q=*:*&facet=true&fq=age:[21+TO+30] It returns all the ages I want in the range 2...
[ "In your request, you don't have any facet queries. You are using filter queries. Which will narrow you're results set down.\nPerhaps you could try adding some facet.query's to your request and copy the results from the facet.counts area, in to your question above. At the very least this will tell you how many resu...
[ 3, 3, 1 ]
[]
[]
[ "django", "python", "solr" ]
stackoverflow_0001901567_django_python_solr.txt
Q: select object to edit I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows: def edit_record(request): if request...
select object to edit
I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows: def edit_record(request): if request.method == 'POST': ...
[ "The important thing about get is \"get what?\"\nWhen you say\na=ProjectRecord.objects.get()\n\nyou neglected to provide any selection criteria. Which row do you want from the database?\nWhich row? Hmmmm... How does the GET transaction know which row is going to be edited?\nUsually, we put that in the URL.\nSo, y...
[ 2, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0001947067_django_django_views_python.txt
Q: urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY? import urllib print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() The above script works and returns the expected results while: im...
urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY?
import urllib print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() The above script works and returns the expected results while: import urllib2 print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Moni...
[ "That URL does indeed result in a 404, but with lots of HTML content. urllib2 is handling it (correctly) as an error condition. You can recover the content of that site's 404 page like so:\nimport urllib2\ntry:\n print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_Aqua...
[ 35 ]
[]
[]
[ "http_status_code_404", "python", "url", "urllib", "urllib2" ]
stackoverflow_0001947133_http_status_code_404_python_url_urllib_urllib2.txt
Q: Django - Using trees to build a comment system A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to...
Django - Using trees to build a comment system
A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so: comment <--top ...
[ "Have a look at django-threadedcomments. It's purpose is more fit to be used as comments on a blog than a full featured forum, but if it doesn't fit your case, you can at least look at the source code and learn a couple things from it.\nAs far as tree-based structures go, there are three projects I'm aware of for D...
[ 2, 1 ]
[]
[]
[ "django", "python", "tree" ]
stackoverflow_0001947176_django_python_tree.txt
Q: fastcgi, cherrypy, and python So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library? I realize thi...
fastcgi, cherrypy, and python
So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library? I realize this question extends from a basic mis...
[ "This is because of performance. For development, autoreloading is helpful. But for production, you don't want to autoreload. This is actually a decently-sized bottleneck in say PHP. Every time you access a PHP webpage, the server has to parse and load each page from scratch. With Python, the script is already...
[ 8, 0 ]
[]
[]
[ "cherrypy", "fastcgi", "lighttpd", "python" ]
stackoverflow_0001947344_cherrypy_fastcgi_lighttpd_python.txt
Q: python email error I am trying to email a results file. I am getting an import error: Traceback (most recent call last): File "email_results.py", line 5, in ? from email import encoders ImportError: cannot import name encoders I am also unsure on how to get this to connect to the server. Can anyon...
python email error
I am trying to email a results file. I am getting an import error: Traceback (most recent call last): File "email_results.py", line 5, in ? from email import encoders ImportError: cannot import name encoders I am also unsure on how to get this to connect to the server. Can anyone help? Thanks #!/home/b...
[ "The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance?\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0001947701_python.txt
Q: authenticate returns nothing what im experimenting is the next: S:\proj>manage.py shell Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) django 1.1.1 >>> from django.contrib.auth.models import User >>> u = User(username='luis', password='admin') >>> u.save() #sucessfull created in mysql db >>> from django.contrib...
authenticate returns nothing
what im experimenting is the next: S:\proj>manage.py shell Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) django 1.1.1 >>> from django.contrib.auth.models import User >>> u = User(username='luis', password='admin') >>> u.save() #sucessfull created in mysql db >>> from django.contrib.auth import authenticate >>> usua...
[ "The problem is not with authenticate, but with your creation of the user.\nThe value stored in u.password needs to be the hashed value of the password, not the raw password itself.\nYou can use u.set_password('password') to take care of the hashing for you:\n>>> u = User(name='luis')\n>>> u.set_password('password'...
[ 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001947811_django_django_models_python.txt
Q: Diacritic signs How should I write "mΔ…ka" in Python without an exception? I've tried var= u"mΔ…ka" and var= unicode("mΔ…ka") etc... nothing helps I have coding definition in first line in my document, and still I've got that exception: 'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte A: Sav...
Diacritic signs
How should I write "mΔ…ka" in Python without an exception? I've tried var= u"mΔ…ka" and var= unicode("mΔ…ka") etc... nothing helps I have coding definition in first line in my document, and still I've got that exception: 'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte
[ "Save the following 2 lines into write_mako.py:\n# -*- encoding: utf-8 -*-\nopen(u\"mΔ…ka.txt\", 'w').write(\"mΔ…ka\\n\")\n\nRun:\n$ python write_mako.py\n\nmΔ…ka.txt file that contains the word mΔ…ka should be created in the current directory.\nIf it doesn't work then you can use chardet to detect actual encoding of t...
[ 4, 2, 1, 1 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0001947837_django_python_unicode.txt
Q: Python library for sending/managing usage statistics Recall those applications that provide the option to "Send usage statistics to help improve X" during the installation? I presume it collects certain patterns of usage and sends it back to the server. Back at the server, there may be some sort of mining going on...
Python library for sending/managing usage statistics
Recall those applications that provide the option to "Send usage statistics to help improve X" during the installation? I presume it collects certain patterns of usage and sends it back to the server. Back at the server, there may be some sort of mining going on. Is there a Python library to do this .. at least from th...
[ "Sending and receiving logging events across a network\nFrom the docs:\nimport logging, logging.handlers\n\nrootLogger = logging.getLogger('')\nrootLogger.setLevel(logging.DEBUG)\nsocketHandler = logging.handlers.SocketHandler('localhost',\n logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n# don't bot...
[ 2 ]
[]
[]
[ "python", "usage_statistics" ]
stackoverflow_0001948404_python_usage_statistics.txt
Q: python - Importing a file that is a symbolic link If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly? A: You only have to be careful in ...
python - Importing a file that is a symbolic link
If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly?
[ "You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link.\n", "Python will import it twice.\nA link is a file system concept. To the Python interpreter, x.py and y.py are two different mo...
[ 13, 11 ]
[]
[]
[ "import", "python", "testing" ]
stackoverflow_0001158108_import_python_testing.txt
Q: pygtk: howto change background of a gtk.TextView widget I want to make the background of a textview widget black and the foreground white. Been trying the .modify_bg and .modify_fg methods, but none affect the way this thing looks. Can anyone suggest anything or is this just not possible? A: I resolved some simi...
pygtk: howto change background of a gtk.TextView widget
I want to make the background of a textview widget black and the foreground white. Been trying the .modify_bg and .modify_fg methods, but none affect the way this thing looks. Can anyone suggest anything or is this just not possible?
[ "I resolved some similar manipulating the gtk rcstyles:\nwidget.set_name('mywidget')\n\n# Set mywidget internal style.\ngtk.rc_parse_string('\\\n style \"mywidget\"\\n\\\n {\\n\\\n attribute1 = value1\\n\\\n attribute2 = value2\\n\\\n }\\n\\\n widget \"*.mywidget\" style \"mywidget\"')\n\n...
[ 2, 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0001948396_gtk_pygtk_python.txt
Q: how can I catch the error of "no existing page" in python I developpe a browser with python and pyqt4 but I don't know what I put in loaderror try: self.webView.load(QtCore.QUrl(self.lineEdit.text())) except loaderreur: self.webView.load(QtCore.QUrl('erreur.html')) when the page doesn't exist thx A: T...
how can I catch the error of "no existing page" in python
I developpe a browser with python and pyqt4 but I don't know what I put in loaderror try: self.webView.load(QtCore.QUrl(self.lineEdit.text())) except loaderreur: self.webView.load(QtCore.QUrl('erreur.html')) when the page doesn't exist thx
[ "Try loading up your browser of choice, and see what they do when given a page that doesn't exist.\nYou likely want to mimic that behaviour (Generic 404 page).\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0001949049_pyqt4_python.txt
Q: Displaying graphics on top of another full screen application; hardware overlay? On Windows (Vista32), I want to display some simple graphics on top of a fullscreen flash window (an overlay of useful information while using the flash application). What's the fastest way to accomplish it? I think I may be able to a...
Displaying graphics on top of another full screen application; hardware overlay?
On Windows (Vista32), I want to display some simple graphics on top of a fullscreen flash window (an overlay of useful information while using the flash application). What's the fastest way to accomplish it? I think I may be able to achieve it using DirectX with the DDSCAPS_OVERLAY flag but with the only example I've f...
[ "Just create a Layered Window and draw to it with an alpha channel - in WPF, this is as easy as setting the AllowsTransparency bit on the Window\n", "While the transparent layered window is useful, it doesn't appear on top of the fullscreen flash with WS_EX_TOPMOST set.\nNote sure how to reply to Paul sadly.\nOve...
[ 1, 0 ]
[]
[]
[ "c++", "directx", "flash", "python", "windows" ]
stackoverflow_0001934910_c++_directx_flash_python_windows.txt
Q: Choice of database for a Django-based RSS application? I'm planning a web application using Django, and it's based on a big pile of data from RSS feeds. What would be the best database to use to store the content of a lot of posts and metadata, as well as data about how each user relates to each post? I've heard t...
Choice of database for a Django-based RSS application?
I'm planning a web application using Django, and it's based on a big pile of data from RSS feeds. What would be the best database to use to store the content of a lot of posts and metadata, as well as data about how each user relates to each post? I've heard that the consensus is that ZODB is too slow, but it'd be hand...
[ "Django is tuned to work (and perform) nicely with RDBMS, so that's probably the path of least resistance, until you've demonstrated to yourself that an RDBMS won't solve your problem. If you do reach that point, this page on the wiki is probably a good jumping off point for non-relational DBs in Django.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "python", "rss" ]
stackoverflow_0001949228_database_django_python_rss.txt
Q: twisted threading with subprocess.Popen? I'm trying to implement a service with Twisted that's fairly close to the "finger" tutorial found here: http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html I've got a basic.LineListener waiting for a command and then executing it, then I have a client ...
twisted threading with subprocess.Popen?
I'm trying to implement a service with Twisted that's fairly close to the "finger" tutorial found here: http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html I've got a basic.LineListener waiting for a command and then executing it, then I have a client connecting and issuing commands. Trouble is th...
[ "As mg said in his comment, don't use the subprocess module. On POSIX platforms, it's necessary (more or less) to handle the SIGCHLD signal to deal with child processes that exit. Since there can only be one SIGCHLD handler, multiple libraries generally won't cooperate. Twisted's child process support and the su...
[ 7 ]
[]
[]
[ "multithreading", "python", "subprocess", "twisted" ]
stackoverflow_0001948641_multithreading_python_subprocess_twisted.txt
Q: RabbitMQ gives a "access refused, login refused for user" error when attempting to follow the celery tutorial I'm attempting to follow the celery tutorial, but I run into a problem when I run python manage.py celeryd: my RabbitMQ server (installed on a virtual machine on my dev box) won't let my user login. I get ...
RabbitMQ gives a "access refused, login refused for user" error when attempting to follow the celery tutorial
I'm attempting to follow the celery tutorial, but I run into a problem when I run python manage.py celeryd: my RabbitMQ server (installed on a virtual machine on my dev box) won't let my user login. I get the following on my Django management console: [ERROR/MainProcess] AMQP Listener: Connection Error: Socket closed. ...
[ "Are you running django?\nIf so, then try this:\n>>> from carrot.connection import DjangoBrokerConnection\n>>> c = DjangoBrokerConnection()\n>>> c.connection\n\nDoes it give the same thing?\nAre you sure you're connecting to the right hostname, and that the username and password has access to the virtual host?\nUPD...
[ 5 ]
[]
[]
[ "amqp", "celery", "django", "python", "rabbitmq" ]
stackoverflow_0001878306_amqp_celery_django_python_rabbitmq.txt
Q: Parsing an html file and adding found images to a zip file I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images. Assume the images variable ...
Parsing an html file and adding found images to a zip file
I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images. Assume the images variable is already populated from parsing the html. What I need help wit...
[ "I'm not quite sure what you're asking here, since you appear to have most of it sorted. \nHave you investigated HtmlParser to actually perform the HTML parsing ? I wouldn't try hand-rolling a parser yourself - it's a major task with numerous edge cases. Don't even think about regexps for anything but the most triv...
[ 1, 1, 1 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0001949549_python_zip.txt
Q: What is a good & free game engine? For C++, Java, or Python, what are some good game + free game engines that are easy to pick up? Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities. A: For my Computer Graphics course in College we ...
What is a good & free game engine?
For C++, Java, or Python, what are some good game + free game engines that are easy to pick up? Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.
[ "For my Computer Graphics course in College we used the open source OGRE 3D engine. Not only is this an extremely robust 3D engine but it was a blast! \nDevelop a medium sized game using it and you will get a good taste of many of the different game programming specialties. You'll find yourself doing 3d modeling, ...
[ 17, 14, 13, 5, 3, 3, 2, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "c++", "java", "python" ]
stackoverflow_0000564469_c++_java_python.txt
Q: Which is a more functional programming language, Haskell or Python? Had learned Haskell during a Functional Programming course in school. Had found Haskell a bit difficult to work with. Have now worked a lot on Python. Python is quite easy to work with. Python does support some functional programming constructs. W...
Which is a more functional programming language, Haskell or Python?
Had learned Haskell during a Functional Programming course in school. Had found Haskell a bit difficult to work with. Have now worked a lot on Python. Python is quite easy to work with. Python does support some functional programming constructs. Was thinking of revisiting Functional Programming. What would be a better ...
[ "Haskell is a functional programming language, whereas Python just has some features of functional programming languages. So, this is settled. Q.e.d.\nEdit: What is lacking in Python, just to give one example, is the optimization of recursive function calls. This is vital in most real functional programming languag...
[ 38, 33, 11, 7, 0 ]
[ "From the Haskell homepage:\n\nHaskell is an advanced purely functional programming language. An open source product of more than twenty years of cutting edge research, it allows rapid development of robust, concise, correct software. \n\nSarcastic translation: \n\n\"advanced\" = \"Not for everyone\"\n\"purely func...
[ -3 ]
[ "functional_programming", "haskell", "python" ]
stackoverflow_0001945634_functional_programming_haskell_python.txt
Q: Is the Python 3.x signal library for Windows incomplete? I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I hav...
Is the Python 3.x signal library for Windows incomplete?
I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I haven't found any 3.0 docs yet mentioning that this was moved EDI...
[ "Windows is NOT posix compliant OS so it does not have all signals - my guess is that on 3.0 the missing signals do not show up there any longer.\n", "It seems you are running your 2.5 in cygwin, which is probably the reason that it shows up there.\nPython 2.5.1 (r251:54863, May 18 2007, 16:56:43)\n[GCC 3.4.4 (cy...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001948862_python.txt
Q: wxPython file dialog error: missing "|" in the wildcard string! I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dial...
wxPython file dialog error: missing "|" in the wildcard string!
I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dialog, I get this: Traceback (most recent call last): File "D:\Projects\...
[ "The wildcard string has a quirky format, borrowed from Win32:\nDesc1|wildcard1|Desc2|wildcard2 ...\n\nThere should be an odd number of pipes, so that the pipe-separated pieces form pairs, a description, and a wildcard. For example:\nSpreadsheet (*.xls)|*.xls|Plain-old text (*.txt)|*.txt|Random noise|*.dat\n\nNote...
[ 7 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001950454_python_wxpython.txt
Q: Python: Split list into list of dicts? Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'Failure...
Python: Split list into list of dicts?
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'ID:0:0:1', '...
[ "result = [{}]\nfor item in data:\n key, val = item.split(\":\", 1)\n if key in result[-1]:\n result.append({})\n result[-1][key] = val\n\n", "import re\n\nresults = []\ntemp = {}\nfor item in data:\n (key, value) = re.search('(.*?):(.*)', item).groups()\n if temp.has_key(key): temp = {}\n ...
[ 8, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0001950672_dictionary_list_python.txt
Q: python lottery suggestion I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one. However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery? Let say, the simplest situation. 100 names and generat...
python lottery suggestion
I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one. However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery? Let say, the simplest situation. 100 names and generate 20 names randomly. I don't wa...
[ "You can generate your own pseudo-random numbers -- there's a huge amount of theory behind that, start for example here -- and of course you won't be able to compete with Python's random \"Mersenne twister\" (explained halfway down the large wikipedia page I pointed you to), in either quality or speed, but for purp...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001950539_python.txt
Q: What is the purpose of classmethod in this code? In django.utils.tree.py: def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) I don't know what classmethod does in this ...
What is the purpose of classmethod in this code?
In django.utils.tree.py: def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) I don't know what classmethod does in this code sample. Can someone explain what it does and how ...
[ "classmethod is a decorator, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof:\n>>> class x(object):\n... def c1(*args): print 'c1', args\n... c1 = classmethod(c1)\n... @classmethod\n... def c2(*args): print 'c2', args\n... \n>>> inst = x()\n>>> x.c...
[ 213, 9 ]
[]
[]
[ "python" ]
stackoverflow_0001950414_python.txt
Q: Insights on SystemError: com_backpatch: offset too large In python, "SystemError: com_backpatch: offset too large" is thrown when executing the code generated by the following: f = open("test.py", "w") f.write("def fn():\n a =1000\n") for a in xrange(3000): if a == 0: f.write(" if a == "+str(a)+": \n ...
Insights on SystemError: com_backpatch: offset too large
In python, "SystemError: com_backpatch: offset too large" is thrown when executing the code generated by the following: f = open("test.py", "w") f.write("def fn():\n a =1000\n") for a in xrange(3000): if a == 0: f.write(" if a == "+str(a)+": \n print "+str(a)+"\n") else: f.write(" elif a =...
[ "Accourding to this: http://www.cgl.ucsf.edu/pipermail/chimera-dev/2007/000404.html\n\nThe Python bytecode compiler has a\n limitation of a maximum of a 16 bit\n offset in a jump instruction. This\n means that you don't want to have 64K\n worth of characters in a single\n conditional block of code\n\nMore det...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001867070_python.txt
Q: Making Django admin display the Primary Key rather than each object's Object type In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: Select host to change * Add host Host object Host object Host object Host object Host object This happens for all model...
Making Django admin display the Primary Key rather than each object's Object type
In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: Select host to change * Add host Host object Host object Host object Host object Host object This happens for all models in my site, not just Hosts. Rather than display the same name for each object, I woul...
[ "Add a __unicode__() method to Host. To show the primary key of your host objects, you'd want something like:\nclass Host(models.Model):\n host = models.CharField(max_length=100, primary_key=True)\n\n def __unicode__(self):\n return self.pk\n\n ...\n\nYou might want to think about showing the conten...
[ 33, 10, 3 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0001594436_admin_django_python.txt
Q: SendKeys failing after 2 runs in thread Python and SendKeys import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().star...
SendKeys failing after 2 runs in thread
Python and SendKeys import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().start(); return True hm = pyHook.Hoo...
[ "It seems that SendKeys is thread safe. The following code works on Vista - Python 2.6\nclass Auto(threading.Thread):\n def run(self):\n SendKeys.SendKeys(\"#\",pause=0.1);\n print('Sent');\n exit();\n\nfor i in xrange(30):\n Auto().start()\n\nMaybe the problem comes from some interferenc...
[ 1, 0 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0001950781_python_sendkeys.txt
Q: Python: intercept a class loading action Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start ...
Python: intercept a class loading action
Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports...
[ "You can intercept import and from ... import statements by defining your own __import__ function and assigning it to __builtin__.__import__ (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to import __builtin__ to get the builtin-objects module).\nFor...
[ 5, 1, 1, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001950062_python_unit_testing.txt
Q: What is meant by 2D array support? I read that Python does not actually support 2D arrays but rather an array of an array. I understand the array of an array thing but what does it mean by supporting 2D arrays? In C a 2D array is simply converted to a 1D array by doing some fancy math (Seen here). Are there lang...
What is meant by 2D array support?
I read that Python does not actually support 2D arrays but rather an array of an array. I understand the array of an array thing but what does it mean by supporting 2D arrays? In C a 2D array is simply converted to a 1D array by doing some fancy math (Seen here). Are there languages that implement actual 2D arrays? T...
[ "There are languages that implement 2D (or 3D, etc) arrays. Fortran is one of them. It means you can write an array index expression like array[x,y] and the language will take care of the math to find the correct element.\nAlso, Numpy is a numerical extension to Python that provides n-dimensional arrays.\n", "S...
[ 10, 6, 2, 1, 1, 1, 1 ]
[]
[]
[ "arrays", "c", "multidimensional_array", "python" ]
stackoverflow_0001698553_arrays_c_multidimensional_array_python.txt
Q: Python - Things I shouldn't be doing? I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ... junk_block = "".join(open("foo.txt","rb").read().split()) ... I don't do this anymore because I can see that it makes code harder to read, but would the ...
Python - Things I shouldn't be doing?
I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ... junk_block = "".join(open("foo.txt","rb").read().split()) ... I don't do this anymore because I can see that it makes code harder to read, but would the code run slower if I split the statements u...
[ "As long as you're inside a function (not at module top level), assigning intermediate results to local barenames has an essentially-negligible cost (at module top level, assigning to the \"local\" barenames implies churning on a dict -- the module's __dict__ -- and is measurably costlier than it would be within a ...
[ 21, 4, 3, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001951012_python.txt
Q: python gnutella programming I wanna learn how to build a p2p application in python that conforms to the gnutella protocol so it can tap-in the existing network like limewire, etc. Any body who knows something where to start or a ste-by-step guide? I've been reading the http://wiki.limewire.org/index.php?title=GDF ...
python gnutella programming
I wanna learn how to build a p2p application in python that conforms to the gnutella protocol so it can tap-in the existing network like limewire, etc. Any body who knows something where to start or a ste-by-step guide? I've been reading the http://wiki.limewire.org/index.php?title=GDF but I need something with an exam...
[ "First of all: read the protocol specification carefully\nThere are multiple python Gnutella implementations, I was able to find at least the following with quick googling:\nQuack, gnuppy. Check their source code for reference.\nThe python modules you might find helpful with protocol packet decoding and message par...
[ 4 ]
[]
[]
[ "p2p", "python" ]
stackoverflow_0001951113_p2p_python.txt
Q: How to read/write .sit files with Python in Linux How to read/write a .sit archive using Python in Linux? A: For dealing with older library formats I tend to fall back on command line utilities. You should be able to find sit manipulation tools such as this one: http://ctan.binkerton.com/ctan.readme.php?filenam...
How to read/write .sit files with Python in Linux
How to read/write a .sit archive using Python in Linux?
[ "For dealing with older library formats I tend to fall back on command line utilities. You should be able to find sit manipulation tools such as this one:\nhttp://ctan.binkerton.com/ctan.readme.php?filename=tools/unstuff/unsit.c\nAs to making them, I'd suggest using an alternative format. You probably have a spec...
[ 0 ]
[]
[]
[ "extract", "file", "python" ]
stackoverflow_0001951419_extract_file_python.txt
Q: Who can call __get__, __set__ and __del__? This is my code. I don't know why it doesn't work. class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') Please try to answer in code, because my English is not very good. Thank you. class HideX(object): ...
Who can call __get__, __set__ and __del__?
This is my code. I don't know why it doesn't work. class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') Please try to answer in code, because my English is not very good. Thank you. class HideX(object): def __init__(self, x): self.x = x d...
[ "I think you should read a bit more on Descriptors before you try to use them.\n", "You are calling obj.get, but there is no get function in class A, hence error,\neither rename __get__ to get or if you by chance are trying to use descriptors do something like this\nclass A(object):\n def __get__(self, obj, kl...
[ 1, 1 ]
[]
[]
[ "descriptor", "python" ]
stackoverflow_0001951415_descriptor_python.txt
Q: Customize login in Google App Engine I need to add few more options for login and therefore need to customize create_login_url with some HTML code. Is there a way to add on your code in default login screen of Google? Environment: Python (Google App Engine) I want to continue having the default Google ext class U...
Customize login in Google App Engine
I need to add few more options for login and therefore need to customize create_login_url with some HTML code. Is there a way to add on your code in default login screen of Google? Environment: Python (Google App Engine) I want to continue having the default Google ext class Users behavior in place.
[ "You can't customize the login page. Allowing you to do so would introduce the possibility of XSS vulnerabilities, as well as making it harder for users to identify a legitimate login page.\nIf you want to provide for federated login, you may want to simply redirect users to an interstitial page that allows them to...
[ 2, 2, 1 ]
[]
[]
[ "authentication", "google_app_engine", "python", "registration" ]
stackoverflow_0000994965_authentication_google_app_engine_python_registration.txt
Q: How to change the default property on a set in python and Google AppEngine In the following code: class ClassA(db.Model): name = db.StringProperty() class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) ClassA will have a prop...
How to change the default property on a set in python and Google AppEngine
In the following code: class ClassA(db.Model): name = db.StringProperty() class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) ClassA will have a property called classb_set. When I call classb_set within code, I do not want it to...
[ "You can always use a Python property to accomplish your goal:\nclass ClassA(db.Model):\n name = db.StringProperty()\n\n def __get_classBdeleted(self):\n return self.classB_set.filter('deleted_flag =', 'True')\n\n classBdeleted = property(__get_classBdeleted)\n\nclass ClassB(db.Model):\n name = d...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001951379_google_app_engine_python.txt