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: Prevent overriding property for class methods in Python? I have the following code: class Test(object): _spam = 42 @classmethod def get_spam(cls): cls._spam @classmethod def set_spam(cls, value): cls._spam = value spam = property(get_spam, set_spam) print Test.spam Test...
Prevent overriding property for class methods in Python?
I have the following code: class Test(object): _spam = 42 @classmethod def get_spam(cls): cls._spam @classmethod def set_spam(cls, value): cls._spam = value spam = property(get_spam, set_spam) print Test.spam Test.spam = 24 print Test.spam The output is: <property object at...
[ "I suppose this stops developers from accidentally overwriting Test's spam property. Is that why you want this? I not sure that is a good idea (what if a developer wants to override the spam property? why throw up roadblocks?), but...\nYou could use a metaclass. If you don't supply a setter for the metaclass's prop...
[ 1 ]
[]
[]
[ "class_method", "oop", "properties", "python" ]
stackoverflow_0006962480_class_method_oop_properties_python.txt
Q: Matplotlib legend: how to assign multiple scatterpoints values I'm using the matplotlib library in python to generate publication-quality xy scatter plots. I ran into a problem regarding the markers in the legend. I'm plotting 2 different xy-scatter series; one is a set of xy points that forms a curve, and the ot...
Matplotlib legend: how to assign multiple scatterpoints values
I'm using the matplotlib library in python to generate publication-quality xy scatter plots. I ran into a problem regarding the markers in the legend. I'm plotting 2 different xy-scatter series; one is a set of xy points that forms a curve, and the other is a single xy point. I would like the legend to show 3 markers ...
[ "you can get the line in legend, and change it yourself:\nimport numpy as np\nimport pylab as pl\nx = np.linspace(0, 2*np.pi, 100)\npl.plot(x, np.sin(x), \"-x\", label=u\"sin\")\npl.plot(x, np.random.standard_normal(len(x)), 'o', label=u\"rand\")\nleg = pl.legend(numpoints=3)\nl = leg.legendHandles[1]\nl._legmarker...
[ 5 ]
[]
[]
[ "legend", "markers", "matplotlib", "plot", "python" ]
stackoverflow_0006961591_legend_markers_matplotlib_plot_python.txt
Q: IPython doesn't find the Shell.IPShell class After installing Django, I followed the tutorial Playing with the API. When I run the following command. python manage.py shell I got this error message. File "/Library/Python/2.6/site-packages/django/core/management/commands/shell.py", line 29, in handle_noargs ...
IPython doesn't find the Shell.IPShell class
After installing Django, I followed the tutorial Playing with the API. When I run the following command. python manage.py shell I got this error message. File "/Library/Python/2.6/site-packages/django/core/management/commands/shell.py", line 29, in handle_noargs shell = IPython.Shell.IPShell(argv=[]) Attri...
[ "A change was made to IPython back in August 19, 2009 that removed this name, and Django hasn't caught up yet. So, Django bug.\nEDIT:\nAnd here it is.\n", "Here is an official commit from django-extensions repo at GitHub:\nDjango-Extensions GitHub repo\nYou can install it by doing this:\n$ git clone git://github....
[ 7, 3, 1 ]
[]
[]
[ "django", "ipython", "python" ]
stackoverflow_0004262938_django_ipython_python.txt
Q: PHP -> python seems to not work on web server I have a few pages (one html, one php, and one python script) that takes a user input, and then outputs a pdf file (using reportlab) for the user. When I test on apache (localhost), it works perfectly. However, online on a real web host it is not working. The version o...
PHP -> python seems to not work on web server
I have a few pages (one html, one php, and one python script) that takes a user input, and then outputs a pdf file (using reportlab) for the user. When I test on apache (localhost), it works perfectly. However, online on a real web host it is not working. The version of PHP on the web server is 5.2.17 and python is ins...
[ "\nLook at /var/logs/httpd/error_log, or wherever your distro's apache stores logs. Odds are you'll find an error message there from PHP.\nIn addition to checking the path like sberry recommended, double check perms, too. Apache will need execute permissions on the python script: chown apache:apache pdfgeneratio...
[ 0 ]
[]
[]
[ "html", "pdf", "php", "python" ]
stackoverflow_0006961703_html_pdf_php_python.txt
Q: Pasting in the Tkinter Text widget I'm using the line below to paste text in a Tkinter Text widget. However, I'd like to have the ability to alter the text prior to it being pasted. I'm specifically trying to remove anything that would cause a new line to be made (e.g., return, '\n'). So how would I get the copied...
Pasting in the Tkinter Text widget
I'm using the line below to paste text in a Tkinter Text widget. However, I'd like to have the ability to alter the text prior to it being pasted. I'm specifically trying to remove anything that would cause a new line to be made (e.g., return, '\n'). So how would I get the copied text as a string, then how would I set ...
[ "You don't need to use event_generate if you're going to pre-process the data. You simply need to grab the clipboard contents, manipulate the data, then insert it into the widget. To fully mimic paste you also need to delete the selection, if any.\nHere's a quick example, barely tested:\nimport Tkinter as tk\nfrom...
[ 6 ]
[]
[]
[ "copy_paste", "python", "string", "text", "tkinter" ]
stackoverflow_0006950007_copy_paste_python_string_text_tkinter.txt
Q: How do I extend Python with C? I have been doing a lot of reading on this subject and am having a lot of trouble wrapping my brain around how this needs to happen. What I want to do is have a function: int Add(int a, int b) { return a + b; } And be able to call it from my Python scripts. How do I do this? A: T...
How do I extend Python with C?
I have been doing a lot of reading on this subject and am having a lot of trouble wrapping my brain around how this needs to happen. What I want to do is have a function: int Add(int a, int b) { return a + b; } And be able to call it from my Python scripts. How do I do this?
[ "The easiest way by far is using the ctypes module, which will allow you to call functions in C libraries directly from Python. Once you have your C function compiled as a library, you can write something to the effect of:\n# Load ctypes, and your library\nfrom ctypes import *\nmylib = CDLL(\"mylibrary.so\")\n\n# D...
[ 9, 7, 2, 2, 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006961204_c_python.txt
Q: Twisted unhandled error When the twisted reactor is running and an exception occurs within a deferred that isn't caught, "Unhandled Error" is printed to the terminal along with a traceback and the exception. Is it possible to handle/intercept these exceptions (e.g., set a callback or override a method)? EDIT: I'm ...
Twisted unhandled error
When the twisted reactor is running and an exception occurs within a deferred that isn't caught, "Unhandled Error" is printed to the terminal along with a traceback and the exception. Is it possible to handle/intercept these exceptions (e.g., set a callback or override a method)? EDIT: I'm aware that I can catch a fail...
[ "Because these tracebacks are written using a call to twisted.python.log.deferr() (in Twisted 10.2 anyway), it is possible to redirect them using a log observer. This is the most common thing to do with these stack traces. I can't find any base class for log observers (surprisingly) but there are a couple built i...
[ 6, 3, 1 ]
[]
[]
[ "python", "reactor", "twisted", "twisted.internet" ]
stackoverflow_0006962738_python_reactor_twisted_twisted.internet.txt
Q: SWIG: 'module' object has no attribute 'Decklist' I'm having one hell of a time with SWIG, due in part to the lack of good C++ examples to learn from. I finally got my first program to compile with SWIG, but am having troubles running it. Let me just get right to the code... setup.py: #!/usr/bin/env python """ ...
SWIG: 'module' object has no attribute 'Decklist'
I'm having one hell of a time with SWIG, due in part to the lack of good C++ examples to learn from. I finally got my first program to compile with SWIG, but am having troubles running it. Let me just get right to the code... setup.py: #!/usr/bin/env python """ setup.py file for SWIG example """ from distutils.core...
[ "change decklist.i as following:\n//decklist.i\n%module decklist\n%{\n #include \"decklist.hpp\"\n%}\n%include \"decklist.hpp\" // <-- *** use % in *.i ***\n\nor you can declare your classes & functions here that you want to export.\n" ]
[ 2 ]
[]
[]
[ "c++", "gcc", "python", "python_idle", "swig" ]
stackoverflow_0006960470_c++_gcc_python_python_idle_swig.txt
Q: Mean subtraction of patches in python nympy scipy I have a numpy array of 3 dimension, it's a grid of patches of 8x8 images. What is the best way to subtract from each patch it's average, in other words each patch has a unique mean and I want to subtract it. I tried the following with no success obviously because ...
Mean subtraction of patches in python nympy scipy
I have a numpy array of 3 dimension, it's a grid of patches of 8x8 images. What is the best way to subtract from each patch it's average, in other words each patch has a unique mean and I want to subtract it. I tried the following with no success obviously because both arrays are not equal in shape patches=- patches.me...
[ "import numpy as np\na = np.random.rand(10,8,8)\nmean = a.mean(axis=2).mean(axis=1)\nb = a - mean[:, np.newaxis, np.newaxis] # reshape the mean as (10, 1, 1)\n\n", "I think you are looking for broadcasting:\nhttp://docs.scipy.org/doc/numpy/user/basics.broadcasting.html\n" ]
[ 3, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0006963080_numpy_python_scipy.txt
Q: Python string search efficiency For very large strings (spanning multiple lines) is it faster to use Python's built-in string search or to split the large string (perhaps on \n) and iteratively search the smaller strings? E.g., for very large strings: for l in get_mother_of_all_strings().split('\n'): if 'target' ...
Python string search efficiency
For very large strings (spanning multiple lines) is it faster to use Python's built-in string search or to split the large string (perhaps on \n) and iteratively search the smaller strings? E.g., for very large strings: for l in get_mother_of_all_strings().split('\n'): if 'target' in l: return True return False or...
[ "Probably Certainly the second, I don't see any difference in doing a search in a big string or many in small strings. You may skip some chars thanks to the shorter lines, but the split operation has its costs too (searching for \\n, creating n different strings, creating the list) and the loop is done in python.\n...
[ 14, 1, 1, 1, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0006963236_performance_python.txt
Q: Best way to parse VisualStudio .csproj file using python What is the best way to parse Visual Studio .csproj file using python, for further modification? It is some .csproj file: ... <ItemGroup> <Reference Include="SomeAssembly, Version=1.1.1.1"/> ... </ItemGroup> ... I want to insert this: <HintPath>pa...
Best way to parse VisualStudio .csproj file using python
What is the best way to parse Visual Studio .csproj file using python, for further modification? It is some .csproj file: ... <ItemGroup> <Reference Include="SomeAssembly, Version=1.1.1.1"/> ... </ItemGroup> ... I want to insert this: <HintPath>path/to/SomeAassembly.dll</HintPath> into the <Reference/> node...
[ "VS project files are XML. Python comes with a number of XML parsing libraries: http://docs.python.org/library/markup.html \nEither of xml.parsers.expat or xml.minidom could accomplish what you describe. For processing small XML documents like VS project files, choosing among them is a matter of taste. The example ...
[ 2 ]
[]
[]
[ "csproj", "parsing", "python", "visual_studio" ]
stackoverflow_0006959824_csproj_parsing_python_visual_studio.txt
Q: How to check if webpage are alive with python with multiproccessing I have a list of urls (about 25k) and I am trying to check if they are alive (200 response). want to do these checks in parallel using the multiprocessing library for Python. I wrote the following (largely based on the Python doc example) but it ...
How to check if webpage are alive with python with multiproccessing
I have a list of urls (about 25k) and I am trying to check if they are alive (200 response). want to do these checks in parallel using the multiprocessing library for Python. I wrote the following (largely based on the Python doc example) but it seems to run pretty slowly. Is there any way I can make this script run f...
[ "There is an easy way:\nhttp://scrapy.org/\nScrapy provides web crawler framework for Python: you can give it a list of URLs to crawl (in your case it doesn't need to follow links) and it will automatically scale to several crawlers within the process/thread limitations you give to it - you don't need to go to the ...
[ 1 ]
[]
[]
[ "http", "python" ]
stackoverflow_0006963350_http_python.txt
Q: Python functions return 1 when there is an exception Could you please explain why does the followin function return "1" when there is an exception? What is the purpose of returning "1"? def initialize(): """ Starting point for the program. """ try: go = Car() print "Instance of Car ...
Python functions return 1 when there is an exception
Could you please explain why does the followin function return "1" when there is an exception? What is the purpose of returning "1"? def initialize(): """ Starting point for the program. """ try: go = Car() print "Instance of Car created" except KeyboardInterrupt: return 1
[ "It's a fairly common idiom in C to return a non-zero value in case of an error.\nMy hunch here is that the person who created this function was used to programming in C and unfamiliar with exception handling. It's impossible to tell without a larger code sample, but if I'm right, then there is probably some sort o...
[ 4, 0 ]
[]
[]
[ "exception", "python", "return" ]
stackoverflow_0006963446_exception_python_return.txt
Q: Pickle: Reading a dictionary, EOFError I recently found out about pickle, which is amazing. But it errors on me when used for my actual script, testing it with a one item dictionary it worked fine. My real script is thousands of lines of code storing various objects within maya into it. I do not know if it has any...
Pickle: Reading a dictionary, EOFError
I recently found out about pickle, which is amazing. But it errors on me when used for my actual script, testing it with a one item dictionary it worked fine. My real script is thousands of lines of code storing various objects within maya into it. I do not know if it has anything to do with the size, I have read aroun...
[ "Try using pickle.dumps() and pickle.loads() as a test.\nIf you don't recieve the same error, you know it is related to the file write.\n" ]
[ 4 ]
[]
[]
[ "eoferror", "maya", "pickle", "python" ]
stackoverflow_0006519366_eoferror_maya_pickle_python.txt
Q: Serializing a class into json for python/gae [noob question] What's the simplest way to encode a class into JSON in python running on GAE? Not using Django and just whatever built-in stuff that GAE has. My class is defined like this: class Sample: def __init__(self, myName, myEmail, myLocality, myAliases, myRo...
Serializing a class into json for python/gae
[noob question] What's the simplest way to encode a class into JSON in python running on GAE? Not using Django and just whatever built-in stuff that GAE has. My class is defined like this: class Sample: def __init__(self, myName, myEmail, myLocality, myAliases, myRoles): self.name = myName; self.ema...
[ "How about this:\n>>> import json\n>>> json.dumps(Sample(1, 2, [3, 4], 4, {5: 5, 5: 5}).__dict__)\n1: '{\"aliases\": 4, \"locality\": [3, 4], \"name\": 1, \"roles\": {\"5\": 5}, \"email\": 2}'\n\n" ]
[ 3 ]
[ "From json.org\nPython:\n\nThe Python Standard Library.\nsimplejson.\npyson.\nYajl-Py.\n\nLinks found in http://www.json.org/ (look at the bottom part where the libraries for different languages and platforms are listed)\nFor the built in way:\nhttp://docs.python.org/library/json.html\n" ]
[ -1 ]
[ "google_app_engine", "python" ]
stackoverflow_0006963509_google_app_engine_python.txt
Q: Why do my Dialog Box Classes write to each other? I'm working on a program that is going to be used with a Time Motion study. There are times that the user may have to create add new objects (Observer, Subject, Clinic). In order to accomplish this I have employed the use of a modal dialog box, (since all data is...
Why do my Dialog Box Classes write to each other?
I'm working on a program that is going to be used with a Time Motion study. There are times that the user may have to create add new objects (Observer, Subject, Clinic). In order to accomplish this I have employed the use of a modal dialog box, (since all data is associated to a subject, observer, and clinic). I ha...
[ "You are storing references to the NewDataDialog instances in self.newsubject, self.newobserver and self.newclinic. This means the objects continue to exist, and to listen for \"mainpanel.SaveButton\" events, even after the newsubject, newobserver, and newclinic methods exit. Once you've opened one of each kind of ...
[ 4 ]
[]
[]
[ "duplicates", "modal_dialog", "python", "wxpython" ]
stackoverflow_0006963189_duplicates_modal_dialog_python_wxpython.txt
Q: Python urllib2 resume download doesn't work when network reconnects I'm using urllib2 to make a resuming downloader, roughly based on this method. I can end the program and re-start it, and it starts downloading where it left off, downloading the file that ends up the same size as if it were downloaded all at once...
Python urllib2 resume download doesn't work when network reconnects
I'm using urllib2 to make a resuming downloader, roughly based on this method. I can end the program and re-start it, and it starts downloading where it left off, downloading the file that ends up the same size as if it were downloaded all at once. However, I have tested it when disabling and reenabling network, and it...
[ "I added self._outfile.close() with the self._netfile.close() in the IOError handler, that seems to have fixed it. I guess this error was caused by opening for appending again without closing it.\n" ]
[ 1 ]
[]
[]
[ "python", "resume_download", "urllib2" ]
stackoverflow_0006963283_python_resume_download_urllib2.txt
Q: In Python, can I make a code thread safe, if I'm using a C extension that is not? My Python code have strange bugs, and I wonder if it could be caused by using a thread unsafe C extension. Would it be possible to use some Python features, like "lock", to fix that C extension problem? And how could I implement this...
In Python, can I make a code thread safe, if I'm using a C extension that is not?
My Python code have strange bugs, and I wonder if it could be caused by using a thread unsafe C extension. Would it be possible to use some Python features, like "lock", to fix that C extension problem? And how could I implement this? [edit 1] Here's what my code looks like: import CextensionPackage as cext try: (...
[ "If you think your C extension is not thread-safe, then you can use Python synchronization primitives (like a lock) to ensure that only one thread is executing in the extension at a time. There's no way for me to know if that will help you with your problems.\n", "If the c extension code does something stupid, I...
[ 0, 0 ]
[]
[]
[ "python", "thread_safety" ]
stackoverflow_0006963656_python_thread_safety.txt
Q: What is the equivalent code to the sentence in Python below? post_data = None if post_args is None else urllib.urlencode(post_args) I can't understand what this code really do. Any help? Thanks. A: post_data = None if post_args is None else urllib.urlencode(post_args) is equivalent to the following: if post_ar...
What is the equivalent code to the sentence in Python below?
post_data = None if post_args is None else urllib.urlencode(post_args) I can't understand what this code really do. Any help? Thanks.
[ "post_data = None if post_args is None else urllib.urlencode(post_args)\n\nis equivalent to the following:\nif post_args is None:\n post_data = None \nelse: \n post_data = urllib.urlencode(post_args)\n\n", "That's a conditional expression, introduced in python 2.5. (It really ought to be on one line).\nIt d...
[ 4, 2 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0006964194_if_statement_python.txt
Q: Python: matching user names w/ password ; prompted for password if incorrect ; I am trying to create a login. I am not sure how to create/import a library of usernames and passwords; I am researching to find answer at the moment but asked either way. match usernames with passwords //(partially solved; need to add...
Python: matching user names w/ password ; prompted for password if incorrect ;
I am trying to create a login. I am not sure how to create/import a library of usernames and passwords; I am researching to find answer at the moment but asked either way. match usernames with passwords //(partially solved; need to add multiple usernames with matching passwords) How to create a loop if password is inc...
[ "What you want is the while statement.\nInstead of nesting if-statements like this:\nif password != '123':\n return 'please try again'\n password = raw_input('password:')\n if password != '123':\n return 'please try again'\nelif password == '123':\n return 'access granted'\n\nYou can do this:\nwh...
[ 2, 1 ]
[]
[]
[ "import", "matching", "passwords", "python" ]
stackoverflow_0006964354_import_matching_passwords_python.txt
Q: py2exe not working on windows 7 starter netbook I have a netbook with windows 7 starter and when ever I try to run my setup.py, I get either of these errors with their corresponding changes: console = [{"script":"FileName.py"}] It won't open. windows = [{"script":"FileName.py"}] It immediately stops working. My pr...
py2exe not working on windows 7 starter netbook
I have a netbook with windows 7 starter and when ever I try to run my setup.py, I get either of these errors with their corresponding changes: console = [{"script":"FileName.py"}] It won't open. windows = [{"script":"FileName.py"}] It immediately stops working. My program has a GUI. It just seems that every setup.py va...
[ "Your setup.py script worked for me on my Windows 7 Professional VM. Tried it with both a simple console script and a wxPython gui script. \nIt is not in your example (and I'm assuming you have this), but you'd need the following imports in your setup:\nimport sys\nfrom setuptools import setup # or from distutils....
[ 2 ]
[]
[]
[ "macos", "parallels", "py2exe", "python", "windows" ]
stackoverflow_0006963335_macos_parallels_py2exe_python_windows.txt
Q: Readability and efficiency, Which is better? Numpy, tuple, etc? I'm working with xyz vectors a lot in my program. I'm using them enough that giving each one a variable (such as offset_x, offset_y, etc) is becoming tedious and cluttering code-wise. Now, I could put each set of x, y, and into tupples (such as offset...
Readability and efficiency, Which is better? Numpy, tuple, etc?
I'm working with xyz vectors a lot in my program. I'm using them enough that giving each one a variable (such as offset_x, offset_y, etc) is becoming tedious and cluttering code-wise. Now, I could put each set of x, y, and into tupples (such as offset = (x,y,z) ) , But I've found that doing stuff like offset[0] everywh...
[ "Check out namedtuple if you're looking for a more readable tuple. Points are the example given in the docs.\nPoint = namedtuple('Point', ['x', 'y'])\n>>> p = Point(11, y=22) # instantiate with positional or keyword arguments\n>>> p[0] + p[1] # indexable like the plain tuple (11, 22)\n33\n>>> x, y =...
[ 2 ]
[]
[]
[ "arrays", "numpy", "python", "tuples" ]
stackoverflow_0006964489_arrays_numpy_python_tuples.txt
Q: python: import random for multiple question I have already created a login(). Trying to ask a random question each time and if answered correctly to run login(). feel that i am on the right track with the latest answer . but running into some trouble . Below is the outline of what I am trying to do: >>> def h...
python: import random for multiple question
I have already created a login(). Trying to ask a random question each time and if answered correctly to run login(). feel that i am on the right track with the latest answer . but running into some trouble . Below is the outline of what I am trying to do: >>> def human_check(): random_question = random.choice(que...
[ "You can do something like this:\nimport random\n\nquestions = []\nquestions.append((\"1+1=\", \"2\"))\nquestions.append((\"the cow jumped over the ....\", \"moon\"))\n\ndef human_check():\n random_question = random.choice(questions)\n question, answer = random_question\n user_answer = raw_input(question)\...
[ 3 ]
[]
[]
[ "import", "python", "random", "user_input" ]
stackoverflow_0006964616_import_python_random_user_input.txt
Q: IOError with lxml etree parse function I have a logic like : for root, dirs, files in os.walk(os.getcwd()): if "info.xml" in files: root = lxml.etree.parse("%s/info.xml" % root) tag = root.xpath("/info/tagname")[0].text when parse one info.xml which very deep in current path, met Error Message...
IOError with lxml etree parse function
I have a logic like : for root, dirs, files in os.walk(os.getcwd()): if "info.xml" in files: root = lxml.etree.parse("%s/info.xml" % root) tag = root.xpath("/info/tagname")[0].text when parse one info.xml which very deep in current path, met Error Message: Traceback (most recent call last): F...
[ "Here's my solution, as per my comment above. I'm opening files for read, them closing them right after so I don't hit the 1024 file limit.\nimport lxml.etree as etree\nfor root,dirs,files in os.walk(os.getcwd()):\n if \"info.xml\" in files:\n with open('%s/info.xml'%root) as processfile: #use 'rb' if ne...
[ 0 ]
[]
[]
[ "ioerror", "lxml", "parsing", "python" ]
stackoverflow_0006341659_ioerror_lxml_parsing_python.txt
Q: python tkinter scrollbar and text widget issues I'm trying to get two text boxes that each have scrollbars. When I try this however: from Tkinter import * root = Tk() s_start = Scrollbar(root) t_start = Text(root, width=50, height=10) t_start.focus_set() s_start.pack(side=RIGHT, fill=Y) t_start.pack(side=LEFT,...
python tkinter scrollbar and text widget issues
I'm trying to get two text boxes that each have scrollbars. When I try this however: from Tkinter import * root = Tk() s_start = Scrollbar(root) t_start = Text(root, width=50, height=10) t_start.focus_set() s_start.pack(side=RIGHT, fill=Y) t_start.pack(side=LEFT, fill=Y) s_start.config(command=t_start.yview) t_sta...
[ "The trick is to use Frames and add the Scrollbars to the Frames instead of to Root.\nfrom Tkinter import *\n\nroot = Tk()\n\nleft = Frame(root)\nright = Frame(root)\n\nt_start = Text(left, width=20)\nt_start.pack(side=LEFT, fill=Y)\ns_start = Scrollbar(left)\ns_start.pack(side=RIGHT, fill=Y)\ns_start.config(comman...
[ 3 ]
[]
[]
[ "python", "scrollbar", "text", "tkinter" ]
stackoverflow_0006964629_python_scrollbar_text_tkinter.txt
Q: subprocess.Popen running infinite loop with py2exe I'm trying to use py2exe to compile a python script into an executable. I've set up the setup.py file just like it's described in documentation: from distutils.core import setup import py2exe setup(console=['agent.py', 'test.py']) The agent.py file simply uses s...
subprocess.Popen running infinite loop with py2exe
I'm trying to use py2exe to compile a python script into an executable. I've set up the setup.py file just like it's described in documentation: from distutils.core import setup import py2exe setup(console=['agent.py', 'test.py']) The agent.py file simply uses subprocess.Popen to open another script: import sys impor...
[ "sys.executable points to agent.exe instead of python.exe when run as compiled executable. You need to change your Popen to:\nchild = subprocess.Popen(['test.exe'])\n\nwhen running compiled executable. You can use hasattr(sys, \"frozen\") to determine whether you're in frozen (py2exe) or not (Python script) mode.\n...
[ 2, 0 ]
[]
[]
[ "popen", "py2exe", "python", "subprocess" ]
stackoverflow_0006961607_popen_py2exe_python_subprocess.txt
Q: When using iterdescendants() on an etree, is it ok to modify the tree? (Python 3.2) I'm using etree to parse some XML. To do this, I'm recursively iterating through the document with iterdescendants(). So, something like: for elem in doc.iterdescendants(): if elem.tag == "tag": pass # Further processin...
When using iterdescendants() on an etree, is it ok to modify the tree?
(Python 3.2) I'm using etree to parse some XML. To do this, I'm recursively iterating through the document with iterdescendants(). So, something like: for elem in doc.iterdescendants(): if elem.tag == "tag": pass # Further processing Sometimes, I process a parent tag that contains children that I want to p...
[ "I have the following code in place of yours and it seems to work, deleting all the child elements. I use iterfind to find all descendants with the tag and delete them.\nfor element in doc.iterfind('.//%s'%tag):\n element.getparent().remove(element)\n\n" ]
[ 1 ]
[]
[]
[ "lxml", "parsing", "python", "python_3.x", "xml" ]
stackoverflow_0006963931_lxml_parsing_python_python_3.x_xml.txt
Q: How can I use Ajax to check the status and result of a django-celery task? The Django Celery documentation suggests there are URLs I can check to get the status of a task. What are these URLs? A: To access these URLs, you need to include them from one of your urls.py files. For example: urlpatterns = patterns(''...
How can I use Ajax to check the status and result of a django-celery task?
The Django Celery documentation suggests there are URLs I can check to get the status of a task. What are these URLs?
[ "To access these URLs, you need to include them from one of your urls.py files. For example:\nurlpatterns = patterns('',\n url('^tasks/', include('djcelery.urls')),\n)\n\nYou would then access them using, for example, http://example.com/tasks/{{ task_id }}/status/.\n" ]
[ 6 ]
[]
[]
[ "ajax", "celery", "django", "django_celery", "python" ]
stackoverflow_0006964607_ajax_celery_django_django_celery_python.txt
Q: Video Transitions with GStreamer & GNonLin not working I've been trying to combine 2 videos together with gstreamer with a short transition (like smpte) between them using gstreamer & gnonlin in python. However I can't get the gnloperation/smpte transition to work. Goal Below is a programme. I want it to play the ...
Video Transitions with GStreamer & GNonLin not working
I've been trying to combine 2 videos together with gstreamer with a short transition (like smpte) between them using gstreamer & gnonlin in python. However I can't get the gnloperation/smpte transition to work. Goal Below is a programme. I want it to play the first 4 sec of one file, and at 2 sec to start doing a smpte...
[ "It looks like the problem is in the properties of your second source file.\nin stead of:\ngsrc2.props.start = 2 * gst.SECOND\ngsrc2.props.duration = 6 * gst.SECOND\ngsrc2.props.media_start = 0\ngsrc2.props.media_duration = 2 * gst.SECOND\ngsrc2.props.priority = 2\n\ntry:\ngsrc2.props.start ...
[ 2 ]
[]
[]
[ "gnonlin", "gstreamer", "python", "python_gstreamer", "video_processing" ]
stackoverflow_0006910446_gnonlin_gstreamer_python_python_gstreamer_video_processing.txt
Q: Installing Django Apps outside of the project folder? For reasons of utter silliness, I want to completely change the way my Django project's filesystem is laid out. In particular, I want to move the actual apps making up the website into separate folders from the admin/settings files. For example, rather than: dj...
Installing Django Apps outside of the project folder?
For reasons of utter silliness, I want to completely change the way my Django project's filesystem is laid out. In particular, I want to move the actual apps making up the website into separate folders from the admin/settings files. For example, rather than: django/ site/ __init__.py manage.py ...
[ "With a setup like that, you could even completely separate your code from django site configuration:\nsite/\n yoursitename/\n __init__.py\n manage.py\n settings.py\n urls.py\nsrc/\n your/\n namespaced/\n apps/\n app1/\n models.py...
[ 7, 0, 0, 0 ]
[]
[]
[ "django", "django_models", "filesystems", "python" ]
stackoverflow_0006947471_django_django_models_filesystems_python.txt
Q: Compressing a sinewave table I have a large array with 1024 entries that have 7 bit values in range(14, 86) This means there are multiple range of indices that have the same value. For example, consider the index range 741 to 795. It maps to 14 consider the index range 721 to 740. It maps to 15 consider the index ...
Compressing a sinewave table
I have a large array with 1024 entries that have 7 bit values in range(14, 86) This means there are multiple range of indices that have the same value. For example, consider the index range 741 to 795. It maps to 14 consider the index range 721 to 740. It maps to 15 consider the index range 796 to 815. It maps to 15 I...
[ "If you don't mind slightly different values due to rounding, I can compress that really well for you.\nfrom math import pi, sin\ninterval=2*pi/1024\nsinval=lambda i:int(round(sin(i*interval)*36))+50\n\nHere is code to actually do what you want; it works with\nvals = sorted((sinval(i), i) for i in range(1024))\n\na...
[ 3, 2 ]
[]
[]
[ "compression", "python", "run_length_encoding", "trigonometry" ]
stackoverflow_0006964576_compression_python_run_length_encoding_trigonometry.txt
Q: How do I implement two decorators in Python both of which would eventually want to call the calling function I am trying to simply my Web application handlers, by using Python decorators. Essentially I want to use decorators to abstract code that checks for authenticated sessions and the other that checks to see ...
How do I implement two decorators in Python both of which would eventually want to call the calling function
I am trying to simply my Web application handlers, by using Python decorators. Essentially I want to use decorators to abstract code that checks for authenticated sessions and the other that checks to see if the cache provider (Memcache in this instance) has a suitable response. Consider this method definition with th...
[ "Each successive decorator receives the previously wrapped function, so the function itself only gets called once at the end of the chain. Here's a simple example:\ndef dec1(f):\n def wrapped():\n print 'dec1'\n return f()\n return wrapped\n\ndef dec2(f):\n def wrapped():\n print 'dec2...
[ 4, 1 ]
[]
[]
[ "decorator", "design_patterns", "python" ]
stackoverflow_0006965021_decorator_design_patterns_python.txt
Q: Python Character Limiter How can I limit a string based on character count, and in the same time preserve complete words ? I just don't want to slice, but even want to preserve the complete words. Please guide me .. Edit Example string = "stackoverflow rocks , I know it." so I need a function, for example limite...
Python Character Limiter
How can I limit a string based on character count, and in the same time preserve complete words ? I just don't want to slice, but even want to preserve the complete words. Please guide me .. Edit Example string = "stackoverflow rocks , I know it." so I need a function, for example limiter(string,5) which should retu...
[ "Will this work for you?\n#!/usr/bin/python\n\ndef limiter(x, limit):\n for i in range(len(x)):\n if i >= limit and x[i] == \" \":\n break\n return x[:i]\n\ndef main():\n x = \"stackoverflow rocks , I know it.\"\n print limiter(x, 5)\n print limiter(x, 25)\n\nif __name__ == '__main_...
[ 5, 4 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006965055_python_string.txt
Q: What is wrong with this way of showing the progress of the function? Here is my function def f(task_list): results = [] for task_id in task_list: results.append(work(task_id)) print len(results) # show the progress return results I use execfile() in ipython to run this function, but i...
What is wrong with this way of showing the progress of the function?
Here is my function def f(task_list): results = [] for task_id in task_list: results.append(work(task_id)) print len(results) # show the progress return results I use execfile() in ipython to run this function, but it seems that the progress is showed until the whole function ends =======...
[ "try to force to flush stdout : \nimport sys\ndef f(task_list):\n results = []\n for task_id in task_list:\n results.append(work(task_id))\n print len(results) # show the progress\n sys.stdout.flush() # this will force the system to display what is in the stdout queue\n return results...
[ 0, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0005854770_ipython_python.txt
Q: can't import MySQLdb Hi I ran the following scripts from macports and still can't run the import MySQLdb. Any idea what the problem could be? sudo port install py26-mysql sudo port install mysql5-server >>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No mo...
can't import MySQLdb
Hi I ran the following scripts from macports and still can't run the import MySQLdb. Any idea what the problem could be? sudo port install py26-mysql sudo port install mysql5-server >>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named MySQLdb >>>
[ "Most likely you are not using Macports Python, but OSX native Python installation, or wrong version of Python from Macports.\nMake sure you launch Python interpreter 2.6 from Macports. \n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0006965156_mysql_mysql_python_python.txt
Q: postgreSQL pl/python how do I get the RETURNING from a query? in this (vey condensed) query, how would one return the myfile_key from RETURNING? CREATE OR REPLACE FUNCTION myfunction (src int, OUT result int) AS $$ plan = plpy.prepare("INSERT INTO myfile VALUES (nextval('seq_myfile'),$1,$2) RETURNING myfile_key",...
postgreSQL pl/python how do I get the RETURNING from a query?
in this (vey condensed) query, how would one return the myfile_key from RETURNING? CREATE OR REPLACE FUNCTION myfunction (src int, OUT result int) AS $$ plan = plpy.prepare("INSERT INTO myfile VALUES (nextval('seq_myfile'),$1,$2) RETURNING myfile_key", ["integer","integer"] ) $$ LANGUAGE plpythonu; (where the first ...
[ "I assume there is a call to plpy.execute missing in your code. You are in principle right to access the RETURNING columns like rv[0][\"myfile_key\"]. What's not working is the assignment to OUT parameters in PL/Python. I suggest that you rewrite your function without OUT parameters using a normal return stateme...
[ 0 ]
[]
[]
[ "plpython", "postgresql", "python", "sql_returning" ]
stackoverflow_0006947800_plpython_postgresql_python_sql_returning.txt
Q: PySide IPC with signals/slots I've been trying to figure out if there's any way to manage IPC in PySide and still take advantage of Qt's signals/slots mechanism. The QtDBus module sounds great, but it doesn't appear to be available in PySide. I came across https://wiki.qt.io/PySide_DBus_Integration on the Qt wiki ...
PySide IPC with signals/slots
I've been trying to figure out if there's any way to manage IPC in PySide and still take advantage of Qt's signals/slots mechanism. The QtDBus module sounds great, but it doesn't appear to be available in PySide. I came across https://wiki.qt.io/PySide_DBus_Integration on the Qt wiki - but that doesn't seem to get me t...
[ "There are three basic IPC solutions [source]:\n\n\nPipes \nSockets (sockets, ZMQ)\nSystem V IPC, like shared memory, message queue, semaphore, (DBus)\n\nIPython uses ZMQ to solve similar problems. \nHere is some nice documentation about that: IPython QT interface\n" ]
[ 1 ]
[]
[]
[ "dbus", "ipc", "pyside", "python", "qt" ]
stackoverflow_0006963528_dbus_ipc_pyside_python_qt.txt
Q: How to transform hyperlink codes into normal URL strings? I'm trying to build a blog system. So I need to do things like transforming '\n' into < br /> and transform http://example.com into < a href='http://example.com'>http://example.com< /a> The former thing is easy - just using string replace() method The latte...
How to transform hyperlink codes into normal URL strings?
I'm trying to build a blog system. So I need to do things like transforming '\n' into < br /> and transform http://example.com into < a href='http://example.com'>http://example.com< /a> The former thing is easy - just using string replace() method The latter thing is more difficult, but I found solution here: Find Hype...
[ "Sounds like the wrong approach. Making round-trips work correctly is always challenging. Instead, store the source text only, and only format it as HTML when you need to display it. That way, alternate output formats / views (RSS, summaries, etc) are easier to create, too.\nSeparately, we wonder whether this parti...
[ 5, 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0006965582_html_python.txt
Q: Do Python generator objects become "unusable" after being traversed? I was working on a Flask project, getting some data from an API wrapper. The wrapper returned a generator object, so I print the values (for obj in gen_object: print obj) before passing it to Flask's render_template(). When requesting the page w...
Do Python generator objects become "unusable" after being traversed?
I was working on a Flask project, getting some data from an API wrapper. The wrapper returned a generator object, so I print the values (for obj in gen_object: print obj) before passing it to Flask's render_template(). When requesting the page while printing the objects, the page is empty. But removing the for loop th...
[ "Yes, generators are ment to be consumed once. Each time we iterate a generator we ask it to give us another value, and if there's no more values to give the StopIteration exception is thrown which would stop the iteration. There's no way for the generator to know that we want to iterate it again without cloning it...
[ 9 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0006965704_flask_python.txt
Q: Reading a line from standard input in Python What (if any) are the differences between the following two methods of reading a line from standard input: raw_input() and sys.stdin.readline() ? And in which cases one of these methods is preferable over the other ? A: raw_input() takes an optional prompt argument. I...
Reading a line from standard input in Python
What (if any) are the differences between the following two methods of reading a line from standard input: raw_input() and sys.stdin.readline() ? And in which cases one of these methods is preferable over the other ?
[ "raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns, and supports history features if the readline module is loaded.\nreadline() takes an optional size argument, does not strip the trailing newline character and does not support history whatsoever...
[ 36, 8 ]
[]
[]
[ "input", "language_features", "python" ]
stackoverflow_0006966194_input_language_features_python.txt
Q: python: convert base64 encoded png image to jpg I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw: import base64 pngraw = base64.decodestring(png_b64text) but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me ...
python: convert base64 encoded png image to jpg
I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw: import base64 pngraw = base64.decodestring(png_b64text) but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me a png file. I know I can use PIL, but HOW exactly wou...
[ "You can use PIL:\ndata = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE\n FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi\n w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt\n 7NUUD9rCiupZqAdTu6yhXgzgBtNFSXQ1+FPTAA...
[ 21, 4 ]
[]
[]
[ "image", "jpeg", "png", "python" ]
stackoverflow_0006966205_image_jpeg_png_python.txt
Q: Process notifications from Google Alert (using PubSubHubbub): PHP or Python I have created some custom alerts using Google alerts. I have set the alerts up so that they are sent to my Google account (RSS) feed. According to the deliver to RSS feed section, "Developers and feed readers can receive real-time updates...
Process notifications from Google Alert (using PubSubHubbub): PHP or Python
I have created some custom alerts using Google alerts. I have set the alerts up so that they are sent to my Google account (RSS) feed. According to the deliver to RSS feed section, "Developers and feed readers can receive real-time updates by subscribing to the feed using the PubSubHubbub protocol. This allows applicat...
[ "Subscribe your callback URL, then recieve notifications. Store the notifications to file. That's it.\nSubscribe/Unsubscribe: http://code.google.com/p/pubsubhubbub/source/browse/trunk/subscriber_clients/php/example.php\nCallback Notification Format:\nhttp://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0....
[ 2 ]
[]
[]
[ "google_alerts", "php", "python", "rss", "websub" ]
stackoverflow_0006965651_google_alerts_php_python_rss_websub.txt
Q: Logarithmic 2D - Histogram using matplotlib This is my first program in python, so there could be things that are "funny" in my program. The program reads 3 columns from the files it finds in a given directory. Then computes the histogram for each file and the results are added to a two dimensional matrix in order...
Logarithmic 2D - Histogram using matplotlib
This is my first program in python, so there could be things that are "funny" in my program. The program reads 3 columns from the files it finds in a given directory. Then computes the histogram for each file and the results are added to a two dimensional matrix in order to create something like a 2D-Hist. My difficult...
[ "For the first part of the question, you have the following options,\n\nApply np.log(my_array) on the results before plotting.\nScale the axes with a hist plot by consulting this previous question: Plot logarithmic axes with matplotlib in python.\nScale 2D color plots like pcolor and imshow by passing a matplotlib....
[ 4 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0006966358_matplotlib_numpy_python.txt
Q: How to query for models with specific parent (not any ancestor) in GAE The docs says that ancestor will apply a filter of given ancestor being somewhere in the ancestry tree. You can filter your datastore queries to a specified ancestor, so that results contain only entities containing that ancestor. In other w...
How to query for models with specific parent (not any ancestor) in GAE
The docs says that ancestor will apply a filter of given ancestor being somewhere in the ancestry tree. You can filter your datastore queries to a specified ancestor, so that results contain only entities containing that ancestor. In other words, all of the results will have the ancestor as their parent, or parent's...
[ "You are right: querying for ancestor will get all parents, not only the direct one. To get the direct parent only, you must store it in a property (can be a ReferenceProperty or you can just store an encoded key in a StringProperty), then query for it.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006966539_google_app_engine_google_cloud_datastore_python.txt
Q: How to render partial with django? I am working on a web project with Django and I have a list of objects displayed on the main column of my page. I want to make filters (like price filter, city...) of this objects on left. I would like to separate this two parts of code, with a special views method to render the ...
How to render partial with django?
I am working on a web project with Django and I have a list of objects displayed on the main column of my page. I want to make filters (like price filter, city...) of this objects on left. I would like to separate this two parts of code, with a special views method to render the left colum (filters) and an other one to...
[ "You can use the {% include %} template tag. \nAlternatively, you can create a custom template tag if the \"partial\" are used in multiple views and you don't want to explicitly insert extra context variables.\n" ]
[ 4 ]
[]
[]
[ "django", "partial", "python" ]
stackoverflow_0006966915_django_partial_python.txt
Q: Python; How to import methods to a class 'pluginstyle'? I'm trying to make a class that imports its methods from plugin-like modules. What I want for this class is for it to be able to import functions/vars from modules that are stored in a separate folder, i.e 'plugins'. Is this possible? i know about __import__(...
Python; How to import methods to a class 'pluginstyle'?
I'm trying to make a class that imports its methods from plugin-like modules. What I want for this class is for it to be able to import functions/vars from modules that are stored in a separate folder, i.e 'plugins'. Is this possible? i know about __import__(), but how can i use it to import so they belong to this clas...
[ "I would break the problem up into two parts: turning a list of files into a list of modules, then extending the class to include functions from those modules.\nBrett Cannon has covered how to import a module from just a file path, so I won't duplicate that here… Although I'll suggest that you check out the glob mo...
[ 1, 0 ]
[]
[]
[ "class", "import", "methods", "plugins", "python" ]
stackoverflow_0006964732_class_import_methods_plugins_python.txt
Q: Is there any good alternative for python's webkit module that works on windows? Is there any official good alternative for webkit that works on windows? A: Try QtWebKit module from PyQt.
Is there any good alternative for python's webkit module that works on windows?
Is there any official good alternative for webkit that works on windows?
[ "Try QtWebKit module from PyQt.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006967136_python.txt
Q: Make filters of an object list I get from my database a list of objects with attributes. So I want to make dynamics filters on the left depends of my list results. For example, if i have an advertisement on "Paris" and "New York" i want to see Paris(1), New york (1) on the left. When you click on it, you will see ...
Make filters of an object list
I get from my database a list of objects with attributes. So I want to make dynamics filters on the left depends of my list results. For example, if i have an advertisement on "Paris" and "New York" i want to see Paris(1), New york (1) on the left. When you click on it, you will see just Paris' advertisement or New yor...
[ "from django.db.models import Q\nAdvertisement.objects.filter( Q(name = 'Paris') | Q(name = 'New York') )\n\nYou need to use filters and Q objects.\n", "You can use the aggregation \nhttps://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset\nexemple:\ncities = ...
[ 2, 0 ]
[]
[]
[ "django", "filter", "python", "tags" ]
stackoverflow_0006967039_django_filter_python_tags.txt
Q: Python "import" performance query Well, this query struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this statement as compared to from package import x, y, z, isn't there any overhead of importing the e...
Python "import" performance query
Well, this query struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this statement as compared to from package import x, y, z, isn't there any overhead of importing the entire package?
[ "I don't expect any performance difference. Whole package will be loaded anyway.\nFor example:\n# load dirname() function from os.path module\n>>> from os.path import dirname\n\n#the os.path.basename() was not imported\n>>> basename('/foo/bar.txt')\nNameError: name 'basename' is not defined\n\n# however, basename()...
[ 7, 3, 3, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006967166_import_python.txt
Q: Python Django: models in root giving error Iam newbie to Python and Django. I have following "models.py" file . from django.db import models from django.contrib.auth.models import User class Greeting(models.Model): author = models.ForeignKey(User, null=True, blank=True) content = models.TextField() date = m...
Python Django: models in root giving error
Iam newbie to Python and Django. I have following "models.py" file . from django.db import models from django.contrib.auth.models import User class Greeting(models.Model): author = models.ForeignKey(User, null=True, blank=True) content = models.TextField() date = models.DateTimeField(auto_now_add=True) 1- When ...
[ "You shouldn't. You are fighting the basic project/application model of Django which underlies the entire system. You will continue to have nothing but problems and issues if you continue down this path.\nCreate an application and put the models.py in that application's subdirectory.\nEdit: I don't mean to sound t...
[ 5 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0006965462_django_models_python.txt
Q: Python: memory efficient list with list.sort(cmp=myfnc) What is the best way to improve this code: def my_func(x, y): ... do smth ... return cmp(x',y') my_list = range(0, N) my_list.sort(cmp=my_func) A python's list takes a lot of memory in comparison with numpy array (6800MB vs 700MB), but nympy.array ...
Python: memory efficient list with list.sort(cmp=myfnc)
What is the best way to improve this code: def my_func(x, y): ... do smth ... return cmp(x',y') my_list = range(0, N) my_list.sort(cmp=my_func) A python's list takes a lot of memory in comparison with numpy array (6800MB vs 700MB), but nympy.array doesn't have the sort function with cmp argument. Are there o...
[ "If you can write a ufunc that convert your array, you can do fast sort by argsort:\nb = convert(a)\nidx = np.argsort(b)\nsort_a = a[idx]\n\n", "As an alternative you can use the builtin sorted with an numpy array:\n>>> a = np.arange(10, 1, -1)\n>>> sorted(a, cmp=lambda a,b: cmp(a,b))\n[2, 3, 4, 5, 6, 7, 8, 9, 10...
[ 2, 0 ]
[]
[]
[ "large_data", "numpy", "python", "sorting" ]
stackoverflow_0006965623_large_data_numpy_python_sorting.txt
Q: Alias method and pass static argument too I was wondering if anybody had any ideas on how to easily alias a method (without creating another method) but pass a static argument too? An example (from how we would normally alias the object - but it obviously doesn't work) to demonstrate what I mean. # Short and to t...
Alias method and pass static argument too
I was wondering if anybody had any ideas on how to easily alias a method (without creating another method) but pass a static argument too? An example (from how we would normally alias the object - but it obviously doesn't work) to demonstrate what I mean. # Short and to the point # Normal: alias = method alias = metho...
[ "from functools import partial\nalias = partial(method, 'static')\n\nor, slower but without imports:\nalias = lambda *args, **kwargs: method('static', *args, **kwargs)\n\npartial is for exactly this purpose; the lambda method is a little more flexible if you need to interleave predefined and changing arguments.\n" ...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0006967572_python.txt
Q: Can someone explain Python hasattr/delattr on a method attribute? I've got a bug caused by some weird behavior. I might be fundamentally missing something about the semantics of function attributes. Or it may be a bug. I'm on $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 First...
Can someone explain Python hasattr/delattr on a method attribute?
I've got a bug caused by some weird behavior. I might be fundamentally missing something about the semantics of function attributes. Or it may be a bug. I'm on $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 First I define a class, and add an attribute to one of its methods. >>> clas...
[ "You should do :\ndel Foo.bar.im_func.xyzzy\n\nThe im_func is needed to access the real method Foo.bar, the instancemethod is a kind of decorator that deal with passing self automatically ... .\n\nAs i may have understand from your question while you was successfully accessing the xyzzy attribute of Foo.bar using g...
[ 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0006967937_python.txt
Q: web.py db.insert function throw error : : 'long' object is unsubscriptable I have a database(mysql) table named foo, and its primary key is bigint type, and auto increment, I write the following codes to insert a record and get the record's primary key q = db.insert('foo', name='bob', age=2, _test=True) print q ...
web.py db.insert function throw error : : 'long' object is unsubscriptable
I have a database(mysql) table named foo, and its primary key is bigint type, and auto increment, I write the following codes to insert a record and get the record's primary key q = db.insert('foo', name='bob', age=2, _test=True) print q this record has been insert into the table, but I got the following error: type...
[ "You get the TypeError: '<type>' object is not subscriptable error when you try to use the __getitem__ interface to an object that doesn't support it. That normally looks like this container[...].\nTake a look at the full traceback. Somewhere, you should see an object being accessed that way. Since you haven't show...
[ 1, 0 ]
[]
[]
[ "database", "mysql", "python", "sql", "web.py" ]
stackoverflow_0006967210_database_mysql_python_sql_web.py.txt
Q: How is the order of test-case invocation chosen by unittest.main() romantest.py: Dive into Python: Introducing romantest.py Dive into Python: Test-First Programming - $ python romantest.py -v fromRoman should only accept uppercase input ... ERROR toRoman should always return uppercase ... ERROR fromRoman should ...
How is the order of test-case invocation chosen by unittest.main()
romantest.py: Dive into Python: Introducing romantest.py Dive into Python: Test-First Programming - $ python romantest.py -v fromRoman should only accept uppercase input ... ERROR toRoman should always return uppercase ... ERROR fromRoman should fail with malformed antecedents ... FAIL fromRoman should fail with repe...
[ "According to the unittest documentation:\n\nNote that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings.\n\n", "Mostly, you should avoid thinking about the order of tests. You need to write each test so that i...
[ 3, 2 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0006967570_python_unit_testing.txt
Q: Python module in path: ImportError raised in mako template There is an ImportError that has the potential to drive me mad. The situation looks like this: tests/ testWebsite.py website/ __init__.py __main__.py _webtools/ __init__.py templatedefs.py ... _templates/ ...
Python module in path: ImportError raised in mako template
There is an ImportError that has the potential to drive me mad. The situation looks like this: tests/ testWebsite.py website/ __init__.py __main__.py _webtools/ __init__.py templatedefs.py ... _templates/ base.mako article.mako ... The code (sans the ...
[ "This indeed drives one mad. However here are some things:\n\n./nosetests:\nthis works and all 9 tests pass\n'templatedefs' is the only key missing in '_webtools.__dict__' when you add an 'from website import _webtools' to your mako template and compare 'nosetests' to 'python -m unittest tests.testWebsite': the oth...
[ 3 ]
[]
[]
[ "importerror", "mako", "python", "unit_testing" ]
stackoverflow_0006821572_importerror_mako_python_unit_testing.txt
Q: Python converting '\' to '\\' I am writing a program to sort a list fo input strings (song names). Those songnames contains latex chars like $\lambda$, which i want to get sorted like 'lambda' instead, så i'm using a the ability to apply a function to each element during sort. like this: # -*- coding: UTF8 -*- de...
Python converting '\' to '\\'
I am writing a program to sort a list fo input strings (song names). Those songnames contains latex chars like $\lambda$, which i want to get sorted like 'lambda' instead, så i'm using a the ability to apply a function to each element during sort. like this: # -*- coding: UTF8 -*- def conv( inp ): if inp == '$\lam...
[ "\nBut for some reason, when i append the lambda sign or \\her it converts it to \\\\her or $\\\\lambda$...\n\nNo it doesn't. What you're seeing is the representation, which always doubles solo backslashes for clarity. If you print the actual strings instead you'll see that they're fine.\n", "There is nothing wro...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "append", "latex", "list", "python", "sorting" ]
stackoverflow_0006968382_append_latex_list_python_sorting.txt
Q: Terminate applications opened with "subprocess.Popen()"? I want to view an image in Eye of Gnome (eog), and then have it automatically close later. I am not very well versed in subprocess, but so far I have tried: eog = subprocess.Popen('oeg <some file>', shell=True) # ...Code, Code, Code... eog.kill() or eog.ter...
Terminate applications opened with "subprocess.Popen()"?
I want to view an image in Eye of Gnome (eog), and then have it automatically close later. I am not very well versed in subprocess, but so far I have tried: eog = subprocess.Popen('oeg <some file>', shell=True) # ...Code, Code, Code... eog.kill() or eog.terminate() Neither work. Any help?
[ "Do not use shell=True, example:\nimport subprocess, shlex\ncommand = 'eog <filename'>\neog = subprocess.Popen(shlex(command))\n..code..\neog.kill()\n\n" ]
[ 4 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006968365_python_subprocess.txt
Q: Sporadic TemplateDoesNotExist errors in django I have a django (v1.1.1) on a server running Python 2.4. On my localhost/development computer the site works perfect. When I uploaded the files to the production server, it seemed to work fine, but after a page refresh I am receiving random TemplateDoesNotExist errors...
Sporadic TemplateDoesNotExist errors in django
I have a django (v1.1.1) on a server running Python 2.4. On my localhost/development computer the site works perfect. When I uploaded the files to the production server, it seemed to work fine, but after a page refresh I am receiving random TemplateDoesNotExist errors. In the trace report I looked at the TEMPLATE_DIRS ...
[ "It sounds like a problem with your apache configuration or what ever you are using for the web server. The PROJECT_ROOT:\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\nIs dependent upon the current absolute path which is set by what ever environment is running the application. Make sure that only ...
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003113015_django_django_templates_python.txt
Q: urllib2 download captcha image I am trying download captcha image from VBB board by using "mechanize" aka urllib2. This is where captcha locate (login with any username and pass you will be asked captcha): <img id="imagereg" src="image.php?type=hv&amp;hash=c76c6f3c2e0fc3bf32fd99d36555fa04" alt="" width="201" heigh...
urllib2 download captcha image
I am trying download captcha image from VBB board by using "mechanize" aka urllib2. This is where captcha locate (login with any username and pass you will be asked captcha): <img id="imagereg" src="image.php?type=hv&amp;hash=c76c6f3c2e0fc3bf32fd99d36555fa04" alt="" width="201" height="61" border="0" /> i was try retr...
[ "Here is a short script that goes to the lost password page, finds the captcha, and downloads the image to out.jpg.\nThis script requires the lxml library.\nHope this helps. Cheers!\nimport urllib2\nimport lxml.html\n\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/2010010' \\\n ...
[ 1 ]
[]
[]
[ "captcha", "mechanize", "python", "urllib", "urllib2" ]
stackoverflow_0006967908_captcha_mechanize_python_urllib_urllib2.txt
Q: PyQt/PySide QMainWindow - switching between views Hello PyQt/PySide experts, I am a newbie to both PyQt/PySide and desktop application development (I'm a web developer). I have a question about how you should navigate among different views in a PyQt/PySide application. Suppose my app has views (i.e. like pages in ...
PyQt/PySide QMainWindow - switching between views
Hello PyQt/PySide experts, I am a newbie to both PyQt/PySide and desktop application development (I'm a web developer). I have a question about how you should navigate among different views in a PyQt/PySide application. Suppose my app has views (i.e. like pages in a web app) "TEST1"(default) and "TEST2", and I want to ...
[ "stackedwidget might do the trick\n" ]
[ 5 ]
[]
[]
[ "pyqt", "pyside", "python" ]
stackoverflow_0006968597_pyqt_pyside_python.txt
Q: What is the correct sequence for bliting surfaces to the screen in pygame? I am creating a simple mp3 player and my first task was to create a simple button that a user could press. I created a class called Button which handled this behavior and detects if a user has clicked it and then changes color. I am now try...
What is the correct sequence for bliting surfaces to the screen in pygame?
I am creating a simple mp3 player and my first task was to create a simple button that a user could press. I created a class called Button which handled this behavior and detects if a user has clicked it and then changes color. I am now trying to have a default text that the button displays and another string (pres_str...
[ "Clear the surface every loop\ndef draw(self):\n # clear screen.\"\n self.screen.fill( self.color_bg )\n\n # first draw background\n # Then buttons\n # then any extra top level text\n\n # update\n pygame.display.flip()\n\ntip: For colors, you can call pygame.Color() with human-names like red ( ...
[ 1, 0 ]
[]
[]
[ "event_driven", "pygame", "python" ]
stackoverflow_0006795644_event_driven_pygame_python.txt
Q: scipy on os x lion I'm am trying to get my python/numpy/scipy working environment running on OS X Lion. I've already managed to compile numpy and scipy from their latest sourcecode versions with the usual python setup.py build python setup.py install I do run the Python 2.7.2 version downloaded from python.org: t...
scipy on os x lion
I'm am trying to get my python/numpy/scipy working environment running on OS X Lion. I've already managed to compile numpy and scipy from their latest sourcecode versions with the usual python setup.py build python setup.py install I do run the Python 2.7.2 version downloaded from python.org: tobi-mbp:~ tobi$ python P...
[ "There appears to be a path issue somewhere. Perhaps you are setting PYTHONPATH? When you are running the python.org 2.7.2, the Apple-supplied Python 2.7.1's Extras directory should not be on sys.path. To help figure out what's going on, launch the Python 2.7.2 and examine the following:\n>>> import sys, os, ppri...
[ 2 ]
[]
[]
[ "numpy", "osx_lion", "python", "scipy" ]
stackoverflow_0006968219_numpy_osx_lion_python_scipy.txt
Q: python limit repeating letters What would be the best way to limit repeating letters down to 1 and 2 such as: appppppppple => aple and apple bbbbbeeeeeer => ber, beer, bber, bbeer Right now, I have this: a = "hellllllllllooooooooooooo" match = re.search('(.)\\1+', a) if match: print 'found' ...
python limit repeating letters
What would be the best way to limit repeating letters down to 1 and 2 such as: appppppppple => aple and apple bbbbbeeeeeer => ber, beer, bber, bbeer Right now, I have this: a = "hellllllllllooooooooooooo" match = re.search('(.)\\1+', a) if match: print 'found' print re.sub('(.)\\1+', '\\1', ...
[ "Don't use REs for this. REs are good for searching, matching, and transforming, but not for generating strings. \nWe can consider a string as a vector; each letter is a dimension, and the count of repetitions is the length of a component along that dimension. Given a vector V, You want all possible vectors of the ...
[ 5, 2, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0006968346_python_regex_string.txt
Q: Python: Iterating over dictionary while another thread modifies dictionary I have a pyglet window that has a attribute "observer". The observer has a dictionary "dict". In the main_loop() function the window re-draws the window according to the content of observer.dict. The observer itself is a thread reading a st...
Python: Iterating over dictionary while another thread modifies dictionary
I have a pyglet window that has a attribute "observer". The observer has a dictionary "dict". In the main_loop() function the window re-draws the window according to the content of observer.dict. The observer itself is a thread reading a stream, adding readings to dict. The observer also has a timer thread that checks ...
[ "Probably some simple lock can fix your problem. Observer class:\nclass Observer(threading.Thread):\n def __init__(self, lock):\n threading.Thread.__init__(self)\n self.dict_lock = lockthreading.RLock()\n self.dict = {}\n self.timer = Timer(1, self.delete_obsolete);\n self.time...
[ 5 ]
[]
[]
[ "dictionary", "locking", "multithreading", "python" ]
stackoverflow_0006968856_dictionary_locking_multithreading_python.txt
Q: How do I throw up Windows tray notifications? I'm trying to use tray notifications in my Python script. I don't care about portability, so I'd be fine with using ctypes and some of the pywin32 modules, but I don't know what calls to use. My script would be running in the background the whole while, and just ale...
How do I throw up Windows tray notifications?
I'm trying to use tray notifications in my Python script. I don't care about portability, so I'd be fine with using ctypes and some of the pywin32 modules, but I don't know what calls to use. My script would be running in the background the whole while, and just alerts the user when they may want to take a possible ...
[ "The Windows function that drives these notifications is Shell_NotifyIcon().\nYou should find an example of how to use it from Python in the Lib\\site-packages\\win32\\demos\\win32gui_menu.py.\n" ]
[ 6 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006968960_python_windows.txt
Q: python str.replace not getting arguments I'm sorting a list using the key= function, i'm sorting a list of song titles written in LaTeX. songs = sorted(songs, key=str.replace('$\lambda$','lambda')) The problem is that when the function runs it says: "TypeError: replace() takes at least 2 arguments (got one) A: ...
python str.replace not getting arguments
I'm sorting a list using the key= function, i'm sorting a list of song titles written in LaTeX. songs = sorted(songs, key=str.replace('$\lambda$','lambda')) The problem is that when the function runs it says: "TypeError: replace() takes at least 2 arguments (got one)
[ "Your key parameter should be a callable. You are sending a string now, this is the error.\nYou could try this:\nsongs = sorted(songs, key=lambda s: s.replace('$\\lambda$','lambda'))\n\nAnd for in-place sorting\nsongs.sort(key=lambda s: s.replace('$\\lambda$','lambda'))\n\n" ]
[ 6 ]
[]
[]
[ "arguments", "python", "sorting" ]
stackoverflow_0006968983_arguments_python_sorting.txt
Q: Why no python implicit line continuation on 'and', 'or', etc.? Is there a reason why this doesn't work in Python? if 1 != 1 or 2 != 2: print 'Something is wrong...' A: Perhaps this prevents a grammar ambiguity, but I feel that this behaviour is in the spirit of PEP 20, specifically 'Simple is better than c...
Why no python implicit line continuation on 'and', 'or', etc.?
Is there a reason why this doesn't work in Python? if 1 != 1 or 2 != 2: print 'Something is wrong...'
[ "Perhaps this prevents a grammar ambiguity, but I feel that this behaviour is in the spirit of PEP 20, specifically 'Simple is better than complex' (among others). In other words, 'Unless you have a good reason, why should expressions span multiple lines?'. If you have a good reason, the syntax devices to get aroun...
[ 6, 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006968900_python.txt
Q: Interfacing C and Python Possible Duplicate: Calling C/C++ from python? I am looking to bridge a C++ and python code. The interfaces needed by python code are : floatvect(): this one should return an empty float vector (basically a list) get_quant(input_list_2, self.m_state_num, self.m_qm_vector) The correspond...
Interfacing C and Python
Possible Duplicate: Calling C/C++ from python? I am looking to bridge a C++ and python code. The interfaces needed by python code are : floatvect(): this one should return an empty float vector (basically a list) get_quant(input_list_2, self.m_state_num, self.m_qm_vector) The corresponding C++ function is : int e...
[ "You need to write equalwidth_quant as a C-extension for Python. Check out Cython or here's a simple tutorial.\n" ]
[ 1 ]
[]
[]
[ "c", "function", "python" ]
stackoverflow_0006969391_c_function_python.txt
Q: Creating Multable pyGTK objects based on a list I am trying to create multable pyGtk objects with different names based on a list for objects in object_list: self.'%s'_entry % objects.upper() = gtk.Entry(max=0) self.vbox_entry.add(self.'%s'_entry % objects.upper()) File "gtk test.py", line 11...
Creating Multable pyGTK objects based on a list
I am trying to create multable pyGtk objects with different names based on a list for objects in object_list: self.'%s'_entry % objects.upper() = gtk.Entry(max=0) self.vbox_entry.add(self.'%s'_entry % objects.upper()) File "gtk test.py", line 113 self.'%s'_entry % objects.upper() = gtk.Entry(m...
[ "Make your life easier and just use a list.\nself.entries = [gtk.Entry(max=0) for objects in object_list]\nfor entry in self.entries:\n self.vbox_entry.add(entry)\n\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python", "string" ]
stackoverflow_0006969496_gtk_pygtk_python_string.txt
Q: Web scraping using Python I am trying to scrape the website http://www.nseindia.com using urllib2 and BeautifulSoup. Unfortunately, I keep getting 403 Forbidden when I try to access the page through Python. I thought it was a user agent issue, but changing that did not help. Then I thought it may have something to...
Web scraping using Python
I am trying to scrape the website http://www.nseindia.com using urllib2 and BeautifulSoup. Unfortunately, I keep getting 403 Forbidden when I try to access the page through Python. I thought it was a user agent issue, but changing that did not help. Then I thought it may have something to do with cookies, but apparentl...
[ "http://www.nseindia.com/ seems to require an Accept header, for whatever reason. This should work:\nimport urllib2\nr = urllib2.Request('http://www.nseindia.com/')\nr.add_header('Accept', '*/*')\nr.add_header('User-Agent', 'My scraping program <author@example.com>')\nopener = urllib2.build_opener()\ncontent = open...
[ 9 ]
[]
[]
[ "python", "urllib2", "web_scraping" ]
stackoverflow_0006969567_python_urllib2_web_scraping.txt
Q: Write a simple python script to convert all .wav files in a specific folder to .mp3 using lame I'd like to write a simple script to convert a few dozen .wav files I have in a folder to v0 mp3. It doesn't need to be complicated, just enough to do the job and help me learn a little bit of python in the process ;) I'...
Write a simple python script to convert all .wav files in a specific folder to .mp3 using lame
I'd like to write a simple script to convert a few dozen .wav files I have in a folder to v0 mp3. It doesn't need to be complicated, just enough to do the job and help me learn a little bit of python in the process ;) I've gathered that I'll need to use something like "from subprocess import call" to do the calling of ...
[ "Here's a sample that works on Ubuntu Linux at least. If you're on Windows, you'll need to change the direction of the slashes.\nimport os\nimport os.path\nimport sys\nfrom subprocess import call\n\ndef main():\n path = '/path/to/directory/'\n filenames = [\n filename\n for filename\n in ...
[ 2 ]
[ "This is what i came up with so far\n#!/usr/bin/env python\nimport os\n\nlamedir = 'lame'\nsearchdir = \"/var/test\"\nname = []\n\nfor f in os.listdir(searchdir):\n name.append(f)\n\nfor files in name:\n iswav = files.find('.wav')\n #print files, iswav\n if(iswav >0):\n print lamedir + ' -h -V 6 ...
[ -1 ]
[ "audio", "lame", "mp3", "python" ]
stackoverflow_0006969464_audio_lame_mp3_python.txt
Q: dealing with an empty list inside a list I have a list which looks something like this: mylist = ([(0.1, 0.5),(0.4, 1.0)], [(0.2, 0.4),(0.15, 0.6)], None, [(0.35, 0.8),(0.05, 1.0)]) What I would like to know is how do I check for the empty entry or None in the list and if there is one then it should continue fu...
dealing with an empty list inside a list
I have a list which looks something like this: mylist = ([(0.1, 0.5),(0.4, 1.0)], [(0.2, 0.4),(0.15, 0.6)], None, [(0.35, 0.8),(0.05, 1.0)]) What I would like to know is how do I check for the empty entry or None in the list and if there is one then it should continue further ignoring it. Something like, if mylist =...
[ "Basically, in python \n[], (), 0, \"\", None, False \n\nall of these means that the value is False\nTherefore:\nnewList = [i for i in myList if i] # this will create a new list which does not have any empty item\n\nemptyList = [i for i in myList if not i] # this will create a new list which has ONLY empty items\n\...
[ 4, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006969609_python.txt
Q: python - time to execute a loop increases suddenly I have some small piece of software that calculates the number of factors of each triangle number to see what is the first one of them has more than X number of factors (yes, it's a projecteuler problem, number 12,, although i didn't solve it yet)... as am trying ...
python - time to execute a loop increases suddenly
I have some small piece of software that calculates the number of factors of each triangle number to see what is the first one of them has more than X number of factors (yes, it's a projecteuler problem, number 12,, although i didn't solve it yet)... as am trying making X some random values to see what the code does an...
[ "Have you looked at the actual values involved?\nThe first triangular number with more than 47 factors is T(104) = 5460, which has 48 factors.\nBut the first triangular number with more than 48 factors is T(224) = 25200, which has 90 factors. So no wonder it takes a lot more work.\nIf your code runs up to T(n), the...
[ 6, 3 ]
[]
[]
[ "function_calls", "loops", "python", "time" ]
stackoverflow_0006969671_function_calls_loops_python_time.txt
Q: Media content working So I'm trying to make a portfolio and trying to just test things locally but it's NOT using my media content.. I've really tried LOTS of stuff.. and I'm out of ideas. The HTML generated is correct, since I used the W3C validator for that. And the src it refers to is also correct: /media/css/f...
Media content working
So I'm trying to make a portfolio and trying to just test things locally but it's NOT using my media content.. I've really tried LOTS of stuff.. and I'm out of ideas. The HTML generated is correct, since I used the W3C validator for that. And the src it refers to is also correct: /media/css/foo.css And I'm quite sure ...
[ "You seem to be using the media for what the static is for, check here\nIn resume, the media folder is made for people uploading photos, files, etc. \nthe static folder is for css, js, images you use in your website.\nif you are not loading your static folder into a separate server you can add this lines to your ur...
[ 3 ]
[]
[]
[ "css", "django", "html", "media", "python" ]
stackoverflow_0006969701_css_django_html_media_python.txt
Q: Finding out what is inside a python library file I am having a python .so file which works fine with python v2.4.3 , but I dont have the source code of that library file. Now It fails to work in python 2.6.5. Is it possible to open the .so file and recompile it in python 2.6.5 ?? I dont know whether it is possible...
Finding out what is inside a python library file
I am having a python .so file which works fine with python v2.4.3 , but I dont have the source code of that library file. Now It fails to work in python 2.6.5. Is it possible to open the .so file and recompile it in python 2.6.5 ?? I dont know whether it is possible, I am just curious . Thanks ! The error I get Trac...
[ "A .so file (.pyd on Windows) is a module which was written in C. It's compiled for, and tied to, a specific version of Python, in this case Python 2.4.x.\nIf you want it to work with a different version of Python, you'll need to re-compile the original source code for that version.\n", "Extension modules need to...
[ 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0006969951_linux_python.txt
Q: Drag drop file onto Python script I'm looking for a cross-platform way of making my Python script process a file's path by implementing a drag n drop method. At the moment I manually go to the terminal and use the sys.argv method: python myscript.py /Python/myfile.xls However this is slow and "techy". Ideally I w...
Drag drop file onto Python script
I'm looking for a cross-platform way of making my Python script process a file's path by implementing a drag n drop method. At the moment I manually go to the terminal and use the sys.argv method: python myscript.py /Python/myfile.xls However this is slow and "techy". Ideally I would a quick and interactive way of all...
[ "If you want to use Tkinter, have a look at the Tkinter DnD binding from here http://klappnase.bubble.org/TkinterDnD/index.html\nWhen run, the binding shows an example with a listbox that allows you to drag a file on to it.\n", "Do you want to drag and drop the myfile.xls onto your python script within your file ...
[ 2, 1, 0 ]
[]
[]
[ "drag_and_drop", "python" ]
stackoverflow_0006969110_drag_and_drop_python.txt
Q: python encoding and decoding strings I am reading a first and last name in Python from a file and am having trouble with encoding. I want to print out the name, but am getting "UnicodeEncodeError: 'charmap' codec can't encode character '\u021b' in position 11: character maps to undefined" with this code: first...
python encoding and decoding strings
I am reading a first and last name in Python from a file and am having trouble with encoding. I want to print out the name, but am getting "UnicodeEncodeError: 'charmap' codec can't encode character '\u021b' in position 11: character maps to undefined" with this code: first = obj.first_name.encode('utf-8') last...
[ "The problem is that your output terminal/console doesn't have any way of displaying ț. Try chcp 65001 before running the script if you're using Windows.\n" ]
[ 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006970110_python_string.txt
Q: Using a variable as both an integer and a string (Python) I would like to use a variable as an integer and a string in the same statement. In BASIC, it would look like this: cnt = 0 while cnt < 10: cnt = cnt + 1 print cnt + " + 1 = " + cnt + 1 I understand it's a bit different with Python (integers have...
Using a variable as both an integer and a string (Python)
I would like to use a variable as an integer and a string in the same statement. In BASIC, it would look like this: cnt = 0 while cnt < 10: cnt = cnt + 1 print cnt + " + 1 = " + cnt + 1 I understand it's a bit different with Python (integers have to be converted before you print them as strings, but here usi...
[ "There isn't one, since Python is strongly typed.\nprint '%d + 1 = %d' % (cnt, cnt + 1)\n\n", "For Python 2.6+, the format method is the preferred way to build up strings containing other values:\n'{0} + 1 = {1}'.format(cnt, cnt + 1)\n\n", "You had it nearly right; you just need to tell Python exactly when to m...
[ 6, 5, 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006970122_python.txt
Q: Is there such a thing for Django as there is Heroku for Ruby on Rails Is there a cloud based development for Django, such as there is cloud based development and hosting environment for Ruby / heroku A: ep.io provides WSGI hosting Heroku style. It's from Andrew Godwin of South fame. From their website: This i...
Is there such a thing for Django as there is Heroku for Ruby on Rails
Is there a cloud based development for Django, such as there is cloud based development and hosting environment for Ruby / heroku
[ "ep.io provides WSGI hosting Heroku style. It's from Andrew Godwin of South fame. From their website:\n\nThis is ep.io, the hosted WSGI hosting and deployment solution. We take your Django, Flask, Pylons or other WSGI code, run all the annoying hosting parts for you, and make sure everything's redundant and backe...
[ 16, 15, 3, 2, 1, 1, 1, 1, 0 ]
[ "Media Temple has Django grid containers starting at $20/month.\n" ]
[ -1 ]
[ "django", "heroku", "python" ]
stackoverflow_0004064029_django_heroku_python.txt
Q: Does the upcoming changes to AppEngine billing mean asynchronous batch operations will be much cheaper than with the current billing model? In the pursuit of efficient batch operating on AppEngine, I've been experimenting with async calls and have ended up with a request signature that looks like... /task/batch_re...
Does the upcoming changes to AppEngine billing mean asynchronous batch operations will be much cheaper than with the current billing model?
In the pursuit of efficient batch operating on AppEngine, I've been experimenting with async calls and have ended up with a request signature that looks like... /task/batch_remove_model 200 402ms 43582cpu_ms 42859api_cpu_ms. I understand that under the current billing model I'd pay for the 43582ms of cpu time, but how ...
[ "You will pay for the 402ms of instance time used to server the request, plus you'll pay for each of the datastore operations. Datastore operations include entity reads and entity and index writes (not RPC calls), so the cost will be proportional (probably higher) to what you're paying now.\nFor more details see t...
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006969247_google_app_engine_google_cloud_datastore_python.txt
Q: web2py — Format requires mapping? I have figured out how to get my site to say 'Hello, John' when the user is logged in, but I can't figure out how to have it not return the error: <type 'exceptions.TypeError'>(format requires a mapping) In regards to this code: return dict(listings=listings, hello='hello %(first...
web2py — Format requires mapping?
I have figured out how to get my site to say 'Hello, John' when the user is logged in, but I can't figure out how to have it not return the error: <type 'exceptions.TypeError'>(format requires a mapping) In regards to this code: return dict(listings=listings, hello='hello %(first_name)s' % auth.user)
[ "Perhaps your auth.user is None\nhere is a quick check that it would throw that exception\n>>> hello='hello %(first_name)s' % None\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: format requires a mapping\n\nYou could try somthing like this\nhello = 'hello %(first_name)s %s'...
[ 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0006970149_python_web2py.txt
Q: editing a list of lists python3 I have the following code class Board: def __init__(self, size=7): self._size = size self._list, self._llist =[],[] for i in range (self._size): self._list.append('_ ') for j in range(self._size): self._llist.append(self._l...
editing a list of lists python3
I have the following code class Board: def __init__(self, size=7): self._size = size self._list, self._llist =[],[] for i in range (self._size): self._list.append('_ ') for j in range(self._size): self._llist.append(self._list) def printboard(self): ...
[ "You are creating llist with the same list object, repeated multiple times. If you want each list in llist to be a separate, independent object (so that when you modify the contents only one list is changed) then you need to append a different copy to each. The easiest way to do this is to change:\nself._llist.ap...
[ 1 ]
[]
[]
[ "nested_lists", "python", "python_3.x" ]
stackoverflow_0006970364_nested_lists_python_python_3.x.txt
Q: Get cell by column name using xlrd If I have two rows in an Excel (.xls) sheet, like a key-value pair, is there a way to get the value (row1) by entering in the key (row0) in xlrd? For example, if I have (0,0) = COLOR and (1,0) = RED, how would I do something like: value = sh.col_values("COLOR") ? The closest I h...
Get cell by column name using xlrd
If I have two rows in an Excel (.xls) sheet, like a key-value pair, is there a way to get the value (row1) by entering in the key (row0) in xlrd? For example, if I have (0,0) = COLOR and (1,0) = RED, how would I do something like: value = sh.col_values("COLOR") ? The closest I have been able to find is sh.col_values(i...
[ "You have to search down the column until you find COLOR then get the value in the next row.\nfrom itertools import product\n\ndef value_from_key(sheet, key):\n for row_index, col_index in product(xrange(sheet.nrows), xrange(sheet.ncols)):\n if sheet.cell(row_index, col_index).value == key:\n r...
[ 3 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0006970543_python_xlrd.txt
Q: Is gradually translating a program written in C++ to Python feasible? This is simply a personal exercise/project, I don't intend to inflict this on the world. My goal is to further my understanding of both languages, and it would be a nice having a nice Python code base in the end. But basically there is a progra...
Is gradually translating a program written in C++ to Python feasible?
This is simply a personal exercise/project, I don't intend to inflict this on the world. My goal is to further my understanding of both languages, and it would be a nice having a nice Python code base in the end. But basically there is a program I like with a large (about 100ksloc) C++ code base, what I'd like to do i...
[ "\nhaving the existing C++ code use the new Python\n\nI think you'll find that python makes a better glue language for C++ than C++ does for python. So you probably will have an easier time converting the main function to python first (in fact, the first step could be just renaming the main function, compiling the...
[ 4 ]
[]
[]
[ "boost_python", "c++", "python", "translation" ]
stackoverflow_0006970557_boost_python_c++_python_translation.txt
Q: Help with making a big subplot look nicer and clearer I have a subplot of 28 lines x 2 columns(it can change, actually). The yaxis scale of all the lines of the 1st column is supposed to be the same (that must work for that 2nd column as well).... All the xaxis are supposed to be the same. What I want to do is to ...
Help with making a big subplot look nicer and clearer
I have a subplot of 28 lines x 2 columns(it can change, actually). The yaxis scale of all the lines of the 1st column is supposed to be the same (that must work for that 2nd column as well).... All the xaxis are supposed to be the same. What I want to do is to make something inside the output figure that shows what is ...
[ "I'm not entirely sure what you're asking, but here's how I'd go about plotting something along those lines...\nThe aspect ratio for your figure is controlled by the figsize kwarg to plt.figure (or plt.subplots, in this case).\nThe rest you can do with judicious application of annotate.\nHere's an example:\nimport ...
[ 3 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0006942312_matplotlib_plot_python.txt
Q: Python: Make a dynamically created class (as in the class itself) iterable? I started with this code snippet, which, by my understanding, is essentially a class-factory of sorts to emulate an "enum" type from other languages: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))),...
Python: Make a dynamically created class (as in the class itself) iterable?
I started with this code snippet, which, by my understanding, is essentially a class-factory of sorts to emulate an "enum" type from other languages: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) (which I took from here: How can I ...
[ "Use a smarter metaclass than type.\nclass EnumMC(type):\n def __contains__(self, val):\n return val in self.__dict__\n\ndef enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return EnumMC('Enum', (), enums)\n\nMyEnum = enum('FOO', 'BAR', 'JIMMY')\ndef func(my_enum...
[ 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006970718_python.txt
Q: Increase availible memory for python in windows I'm working on a program in python on Windows 7 that matches features between multiple images in real time. It is intended to be the only program running. When I run it on my laptop, it runs very slowly. However, when I check how much memory it is using with the task...
Increase availible memory for python in windows
I'm working on a program in python on Windows 7 that matches features between multiple images in real time. It is intended to be the only program running. When I run it on my laptop, it runs very slowly. However, when I check how much memory it is using with the task manager, it is only using about 46,000 KB. I would l...
[ "Python does not have a built-in mechanism for limiting memory consumption; if that's all it's using, then that's all it'll use.\n", "If you're doing image comparisons, chances are good you are CPU-bound, not memory-bound. Unless those are gigantic images, you're probably OK.\nSo, check your code for performance ...
[ 4, 3, 0 ]
[]
[]
[ "memory_management", "python", "windows" ]
stackoverflow_0006970855_memory_management_python_windows.txt
Q: python dealing with SSH [many clients ] i mange 3 server [ Linux ] and i have to turn on scripts on these servers every 6 hours so it's take a lite bit time to login in each one .. so i made this code import paramiko import os ZI1={"ip":"192.168.1.2","pass":"server-1"} ZI2={"ip":"192.168.1.3","pass":"Server-2"} ...
python dealing with SSH [many clients ]
i mange 3 server [ Linux ] and i have to turn on scripts on these servers every 6 hours so it's take a lite bit time to login in each one .. so i made this code import paramiko import os ZI1={"ip":"192.168.1.2","pass":"server-1"} ZI2={"ip":"192.168.1.3","pass":"Server-2"} ZI3={"ip":"192.168.1.4","pass":"server-3"} ss...
[ "for F1 in ZI1:\n\nWhat the fried monkey are you trying to do here? For is repeating something, but you don't want to repeat anything.\nDo you see the difference between these two lines of code:\nstdin, stdout, stderr = ssh.exec_command('uname -a')\n\nssh.exec_command('ls -la')\n\nYour second and third servers are ...
[ 3, 2, 0, 0 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0006255472_paramiko_python_ssh.txt
Q: Python find audio frequency and amplitude over time Here is what I would like to do. I would like to find the audio frequency and amplitude of a .wav file at every say 1ms of that .wav file and save it into a file. I have graphed frequency vs amplitude and have graphed amplitude over time but I cannot figure out f...
Python find audio frequency and amplitude over time
Here is what I would like to do. I would like to find the audio frequency and amplitude of a .wav file at every say 1ms of that .wav file and save it into a file. I have graphed frequency vs amplitude and have graphed amplitude over time but I cannot figure out frequency overtime. My end goal is to be able to read the ...
[ "Use a STFT with overlapping windows to estimate the spectrogram. To save yourself the trouble of rolling your own, you can use the specgram method of Matplotlib's mlab. It's important to use a small enough window for which the audio is approximately stationary, and the buffer size should be a power of 2 to efficie...
[ 7 ]
[]
[]
[ "audio_processing", "frequency", "python" ]
stackoverflow_0006970943_audio_processing_frequency_python.txt
Q: Python and preventing email header injections I am currently creating a web contact form in python. My main aim is to teach myself python and I am not using a framework (just raw python). I am using python 2.5 as that is what my webhost has. Sending email seems simple in python and that is clear in the documentati...
Python and preventing email header injections
I am currently creating a web contact form in python. My main aim is to teach myself python and I am not using a framework (just raw python). I am using python 2.5 as that is what my webhost has. Sending email seems simple in python and that is clear in the documentation. The problem I have is that I can not find any c...
[ "Just make sure your script sends two newlines (CRLF to be compliant with relevant RFCs, LF only to be compliant with most MTAs) after the headers you want, and any attempted injected headers will show up in the email body.\nAlso, of course, do sanity-checks on the from:, to: and any other data input by a user to m...
[ 0 ]
[]
[]
[ "code_injection", "email", "header", "python" ]
stackoverflow_0006971273_code_injection_email_header_python.txt
Q: Unit testing metaclasses and inner classes in python I usually unit test per class and this is no problem. However after messing around with python I have hit a problem that I have not encountered before in other languages, meta classes and inner classes. Say I have a class that contains an inner class and also ha...
Unit testing metaclasses and inner classes in python
I usually unit test per class and this is no problem. However after messing around with python I have hit a problem that I have not encountered before in other languages, meta classes and inner classes. Say I have a class that contains an inner class and also has a meta class, what is the best way to structure unit tes...
[ "You test a class by instantiating it. The \"dummy class\" you mentioned would be an instance of the metaclass, so that's exactly how you should test it.\nWhen it comes to testing the inner class / outer class -- yes, I would include testing the inner class in the test for the outer class. If it makes sense to test...
[ 3 ]
[]
[]
[ "inner_classes", "metaclass", "python", "python_unittest", "unit_testing" ]
stackoverflow_0006971335_inner_classes_metaclass_python_python_unittest_unit_testing.txt
Q: Web-development for high-load in Python My friends and I are going to develop some web application. The most common scripting language in average for us is the Python, so we would like to use it for the development. However, we are confused with choosing a proper tool set for our task. We expect very high load, so...
Web-development for high-load in Python
My friends and I are going to develop some web application. The most common scripting language in average for us is the Python, so we would like to use it for the development. However, we are confused with choosing a proper tool set for our task. We expect very high load, so we would like to keep it in mind at the begi...
[ "Sounds like you are doing premature optimization. The right solution for handling high load depends heavily on the kind of load. Can you be sure that the topics you talk about will really be your bottlenecks? I would choose a toolset which is known to be reasonalbe fast and which will keep you flexible in the futu...
[ 4 ]
[]
[]
[ "high_load", "python", "tornado", "wsgi" ]
stackoverflow_0006971519_high_load_python_tornado_wsgi.txt
Q: How to use Python mechanize to save a page inlcuding images on the page So I understand that mechanize can make python script behave exactly like a browser. With a browser, I can save a loaded page into local disk, including the images in the page How can I do this with mechanize ? It doesn't seem to be able to sa...
How to use Python mechanize to save a page inlcuding images on the page
So I understand that mechanize can make python script behave exactly like a browser. With a browser, I can save a loaded page into local disk, including the images in the page How can I do this with mechanize ? It doesn't seem to be able to save images on the page I'm using example from This page Thanks in advance
[ "There isn't a direct way to do this however here are the steps you'll need to take\n\nopen the page with mechanize or urllib2\nget the html\nparse html with lxml\nfind all image urls\nfor each image url open with mechanize or urllib2 and save\n\nIn this situation mechanize doesn't really offer you anything over ur...
[ 3 ]
[]
[]
[ "mechanize", "python", "screen_scraping" ]
stackoverflow_0006971470_mechanize_python_screen_scraping.txt
Q: Python Find distance between two coordinates I'm working with a range of 0 to 255. My data would be a set of numbers within this range. Except I need the difference between 255 & 0 = 1 254 & 5 = 7 So in a sense this range is a circular set, and 255 and 0 are the pole. Is there some function / easy way to do ...
Python Find distance between two coordinates
I'm working with a range of 0 to 255. My data would be a set of numbers within this range. Except I need the difference between 255 & 0 = 1 254 & 5 = 7 So in a sense this range is a circular set, and 255 and 0 are the pole. Is there some function / easy way to do this? Or do I need to take the second half of the...
[ "def diff256(a, b):\n return min((a - b) % 256, (b - a) % 256)\n\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0006971705_python.txt
Q: Dynamic subdomain in python flask engine a.example.com b.example.com I want to put in in flask with the same application folder,diferrent config files. I found the following solution,but how to use them? Create a context processor that injects 'request.host' into your templates and branch accordingly. For more co...
Dynamic subdomain in python flask engine
a.example.com b.example.com I want to put in in flask with the same application folder,diferrent config files. I found the following solution,but how to use them? Create a context processor that injects 'request.host' into your templates and branch accordingly. For more control, you could create a Site object, instant...
[ "Take a look at flask Document, It's quite easy to implement a domain handling function via Application Factories and Application Dispatching which is clearly explained in 'Patterns for Flask' section:\nhttp://flask.pocoo.org/docs/patterns/appdispatch/\nhttp://flask.pocoo.org/docs/patterns/appfactories/ \n" ]
[ 1 ]
[]
[]
[ "dns", "flask", "python", "subdomain" ]
stackoverflow_0005527976_dns_flask_python_subdomain.txt
Q: How do I insert a list into another list? I have two lists: A = [1,2,3] B = [4,5,6] Is there an elegant way to insert B into A at an arbitrary position? Hypothetical output: [1,4,5,6,2,3] Obviously I could iterate through B and insert them one at a time, but I figured there was a better way. A: A[1:1] = B A w...
How do I insert a list into another list?
I have two lists: A = [1,2,3] B = [4,5,6] Is there an elegant way to insert B into A at an arbitrary position? Hypothetical output: [1,4,5,6,2,3] Obviously I could iterate through B and insert them one at a time, but I figured there was a better way.
[ "A[1:1] = B\n\nA will be [1, 4, 5, 6, 2, 3]\n", "def insert(outer, inner, pos):\n outer[pos:pos] = inner\n\n" ]
[ 13, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006970579_list_python.txt
Q: django include_javascript/use_javascript and similar I'm searching for the way to include javascript/css files inside django templates using symfony-like style or similar. My base/layout.html template looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/x...
django include_javascript/use_javascript and similar
I'm searching for the way to include javascript/css files inside django templates using symfony-like style or similar. My base/layout.html template looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1...
[ "You can extract js and css calls into another template like ie. js.html and then every time you would like to add it, you're calling django's native {% include \"js.html\" %}. Docs: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include.\nYou can always use {{ block.super }} in child te...
[ 1 ]
[]
[]
[ "css", "django", "javascript", "python", "slots" ]
stackoverflow_0006970592_css_django_javascript_python_slots.txt
Q: Cannot display the image in web browser provided by Python via Apache Server I am trying to display an image file in web browser via the Apache server by Python. I am using: windows 7 apache http server 2.2 python 2.7 Configuration in httpd.conf: DocumentRoot "C:/Apache2.2/htdocs" RewriteRule ^images/(.+)$ ...
Cannot display the image in web browser provided by Python via Apache Server
I am trying to display an image file in web browser via the Apache server by Python. I am using: windows 7 apache http server 2.2 python 2.7 Configuration in httpd.conf: DocumentRoot "C:/Apache2.2/htdocs" RewriteRule ^images/(.+)$ /imagetest.py?img=$1 [QSA,L] imagetest.py under htdocs folder : import cgitb; ...
[ "file.read() is not guaranteed to read the entire file. Use shutil.copyfileobj() to copy the file contents to sys.stdout.\nOr, better yet, enable and use mod_xsendfile.\n" ]
[ 2 ]
[]
[]
[ "apache2", "cgi", "python" ]
stackoverflow_0006972105_apache2_cgi_python.txt
Q: Logic Impasse in a Simple Insertion Sort I'm teaching myself Python and I'm having difficulty with a relatively simple concept. The goal is to sort a list in ascending order using insertion sort. Here is the code: def InsertionSort(A): for j in range(1, len(A)): key = A[j] i = j - 1 whi...
Logic Impasse in a Simple Insertion Sort
I'm teaching myself Python and I'm having difficulty with a relatively simple concept. The goal is to sort a list in ascending order using insertion sort. Here is the code: def InsertionSort(A): for j in range(1, len(A)): key = A[j] i = j - 1 while (i >=0) and (A[i] > key): A[i+1...
[ "I think it's just because of the line A[i+1]=key.\nThe first algorithm does the following: Consider the list [1,2,4,5,3], assume we are in iteration where j=4, i.e. we are considering list element 3. The algorighm stores the element 3 in key and checks the following:\n[1,2,4,5,3]\n ^ 5>3 (key) => move 5 f...
[ 3, 2 ]
[]
[]
[ "insertion_sort", "python", "sorting" ]
stackoverflow_0006972454_insertion_sort_python_sorting.txt