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: Pydev problems with "Go to definition" and "package Explorer" I'm using Pydev on Eclipse. I have created a new project, added __init__.py and a module in a package in the src folder. The problem is, I can't see classes and functions outlines when I try to expand the module by clicking the arrow left to it. Nothing...
Pydev problems with "Go to definition" and "package Explorer"
I'm using Pydev on Eclipse. I have created a new project, added __init__.py and a module in a package in the src folder. The problem is, I can't see classes and functions outlines when I try to expand the module by clicking the arrow left to it. Nothing expands. I expect to see a list of classes with a capital "C" lett...
[ "add your code dir into the project->properties->PyDev - PYTHONPATH->sourceFolders, you can find the C mark in the package Explorer\n", "I'm using Pydev 1.6.5 and I also can't view the outline when I expand the module. For this I use the Outline view, see the screenshot:\n\nDid you add the view? \nWindow > Show ...
[ 1, 0 ]
[]
[]
[ "definition", "eclipse", "package", "pydev", "python" ]
stackoverflow_0005988099_definition_eclipse_package_pydev_python.txt
Q: Good guide to using Ajax in a Django project? I'm working on a Django project that will need jQuery, jQuery UI, and one or two more JavaScript libraries. What good tutorial or reference can be recommend on how to make JavaScript and Django talk with each other? (that is, handling XMLHTTPRequests, passing informati...
Good guide to using Ajax in a Django project?
I'm working on a Django project that will need jQuery, jQuery UI, and one or two more JavaScript libraries. What good tutorial or reference can be recommend on how to make JavaScript and Django talk with each other? (that is, handling XMLHTTPRequests, passing information from a Django model to a JavaScript function, et...
[ "Using Ajax in Django is just like any other web request that comes to your Django application. You need to route the request to your controller which has to provide some HTML to jQuery's Ajax handler, that is, X function(data){}.\nFor more understanding, see Ajax in Django with jQuery.\n" ]
[ 2 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0006316556_ajax_django_javascript_python.txt
Q: List index out of range I have written a program that makes sure each cookie has more than 5 chips before moving on. However, the line if cookie[i] > 5: seems to be problematic, as it produces a "list index out of range" error. I thought foo = [] created a list with no ending, so I don't get why any number would b...
List index out of range
I have written a program that makes sure each cookie has more than 5 chips before moving on. However, the line if cookie[i] > 5: seems to be problematic, as it produces a "list index out of range" error. I thought foo = [] created a list with no ending, so I don't get why any number would be out of range in this list. ...
[ "Try:\nlen(cookie)\n\nYou'll see if you haven't put anything in it that it'll be size 0. With cookie = [] you can continuously add elements to the list but it's initialized empty.\n", "How about:\ncookies = []\n\n...\n\nfor cookie in cookies:\n if cookie > 5:\n break\n\n", "You can't really have a li...
[ 5, 2, 2, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006317287_list_python.txt
Q: Checking for events, logging times, and interacting with PowerPoint from a Python program Is there a way to have a Python program to "listen" for an event? I'd like to create a small program that 'looks for/waits' for Presentation Mode in PowerPoint to be activated. Once it recognizes that it has started, I want ...
Checking for events, logging times, and interacting with PowerPoint from a Python program
Is there a way to have a Python program to "listen" for an event? I'd like to create a small program that 'looks for/waits' for Presentation Mode in PowerPoint to be activated. Once it recognizes that it has started, I want to log the times that the user spends on each slide. What would be the best way to go about th...
[ "I'm pretty sure you'll have to use a macro to execute a specific script.\nI don't know of any way for a Python program to listen for a PowerPoint event.\n" ]
[ 0 ]
[]
[]
[ "powerpoint", "python" ]
stackoverflow_0006317227_powerpoint_python.txt
Q: SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list I am trying to construct a sqlalchemy query to get the list of names of all professors who are assistants professors on MIT. Note that there can be multiple assistant professors associated with a certain course. What I'm ...
SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list
I am trying to construct a sqlalchemy query to get the list of names of all professors who are assistants professors on MIT. Note that there can be multiple assistant professors associated with a certain course. What I'm trying to do is roughly equivalent to: uni_mit = University.get_by(name='MIT') s = select([Professo...
[ "You can find the intermediate table where Elixir has hidden it away, but note that it uses fully qualified column names (such as __package_path_with_underscores__course_id). To avoid this, define your ManyToMany using e.g.\nclass Course(Entity):\n ...\n assistants = ManyToMany('Professor', inverse='courses_a...
[ 0 ]
[]
[]
[ "many_to_many", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0006316726_many_to_many_python_python_elixir_sqlalchemy.txt
Q: How can I splice a string? I know I can slice a string in Python by using array notation: str[1:6], but how do I splice it? i.e., replace str[1:6] with another string, possibly of a different length? A: Strings are immutable in Python. The best you can do is construct a new string: t = s[:1] + "whatever" + s[6:...
How can I splice a string?
I know I can slice a string in Python by using array notation: str[1:6], but how do I splice it? i.e., replace str[1:6] with another string, possibly of a different length?
[ "Strings are immutable in Python. The best you can do is construct a new string:\nt = s[:1] + \"whatever\" + s[6:]\n\n", "You can't do this since strings in Python are immutable.\nTry next:\nnew_s = ''.join((s[:1], new, s[6:]))\n\n", "Nevermind. Thought there might be a built in function. Wrote this instead:\n...
[ 26, 15, 7, 4, 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006317500_python_string.txt
Q: Is there a way to run two or more python modules simultaneously from Eclipse(pyDev)? I am in the process of building a system in python that centralizes the compilation of our code to a set of machines. I have all three programs written, running and working; however I'm still trying to weed out some of the more el...
Is there a way to run two or more python modules simultaneously from Eclipse(pyDev)?
I am in the process of building a system in python that centralizes the compilation of our code to a set of machines. I have all three programs written, running and working; however I'm still trying to weed out some of the more elusive bugs. I have been mostly testing over the localhost interface and therefore run all ...
[ "Yes - just run them as normal and use the Console menu to flip between them. If you run them under the debugger, you can also use the Debug view in the Debug perspective to terminate them - in either case, using the red square icon to do the terminating.\n" ]
[ 3 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0006311577_eclipse_pydev_python.txt
Q: Python: set class method as class attribut The following seems not to be valid in python 3: class A: callback = A.callback_function def callback_function(self): pass You'll get an error saying type 'A' is not defined. Is it because 'A' cannot be refered to in it self? Is there anyway I can achieve this type ...
Python: set class method as class attribut
The following seems not to be valid in python 3: class A: callback = A.callback_function def callback_function(self): pass You'll get an error saying type 'A' is not defined. Is it because 'A' cannot be refered to in it self? Is there anyway I can achieve this type of functionality? What I'm trying to do is somet...
[ "Well, you can just name your function callback, and it'll be just the same, but if you really insist on this way:\nclass A:\n def callback_function(self): pass\n\n callback = callback_function\n\n" ]
[ 9 ]
[]
[]
[ "attributes", "callback", "function", "python", "static" ]
stackoverflow_0006317725_attributes_callback_function_python_static.txt
Q: How do I correctly model joined table inheritance with discriminator based on Role in SQLAlchemy Is it possible to specify a discriminator column from another table? How do I do this with Declarative? The reason for this is I have a joined table inheritance with class User(Base): id = Column(...) class Custom...
How do I correctly model joined table inheritance with discriminator based on Role in SQLAlchemy
Is it possible to specify a discriminator column from another table? How do I do this with Declarative? The reason for this is I have a joined table inheritance with class User(Base): id = Column(...) class Customer(User): customer_id = Column('id', ...) class Mechanic(User): mechanic_id = Column('id', .....
[ "Here's an awkward and inefficient way to achieve the specific result, which will also fail if more than one Role is present on the target User:\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nrole_to_user = Table('role...
[ 3, 1 ]
[]
[]
[ "data_modeling", "orm", "python", "sqlalchemy" ]
stackoverflow_0006146795_data_modeling_orm_python_sqlalchemy.txt
Q: How to avoid "()" when writing a decorator accepting optional arguments? I've written this decorator to deprecate a function and (optionally) provide a callable as replacement def deprecated(repfun=None): """A decorator which can be used to mark functions as deprecated. Optional repfun is a callable that...
How to avoid "()" when writing a decorator accepting optional arguments?
I've written this decorator to deprecate a function and (optionally) provide a callable as replacement def deprecated(repfun=None): """A decorator which can be used to mark functions as deprecated. Optional repfun is a callable that will be called with the same args as the decorated function. """ ...
[ "Since the argument to deprecated() is a function, there is no reliable way to determine if this is the function to be used as a replacement, or the function to be deprecated. Hence, there is no way to do what you want without changing it to take a string instead.\n" ]
[ 3 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0006317946_decorator_python.txt
Q: Can the 'range' function be assigned to a list? I am studying the Learn Python The Hard Way PDF. On page 82 i come across this question. Could you have avoided that for-loop entirely on line 23 and just assigned range(0,6) directly to elements? Given the code: # we can also build lists, first start with an empty...
Can the 'range' function be assigned to a list?
I am studying the Learn Python The Hard Way PDF. On page 82 i come across this question. Could you have avoided that for-loop entirely on line 23 and just assigned range(0,6) directly to elements? Given the code: # we can also build lists, first start with an empty one elements = [] # then use the range function to ...
[ "In python 2.x, range returns a list. In 3.x, it returns an iterable range object. You can always use list(range(...)) to get a list.\nHowever, for x in y does not require y to be a list, just an iterable (such as xrange(2.x only), range, list, str, ...)\n", "But you can also do quite complex assignments as well....
[ 10, 4, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006317940_python.txt
Q: Architecture for providing different linear algebra back-ends I am prototyping a new system in Python; the functionality is mostly numerical. An important requirement is the ability to use different linear algebra back-ends: from individual user implementations to generic libraries, such as Numpy. The linear algeb...
Architecture for providing different linear algebra back-ends
I am prototyping a new system in Python; the functionality is mostly numerical. An important requirement is the ability to use different linear algebra back-ends: from individual user implementations to generic libraries, such as Numpy. The linear algebra implementation (that is, the back-end) must be independent from ...
[ "You should check out PEP-3141 and the standard lib module ABCMeta. \nFor a detailed explanation of how to use ABCMeta, the always helpful PyMOTW has a nice write-up.\n", "Why not simply make a \"virtual\" class (AbstractVector) which is like Vector in your example, and make different subclasses of it for each im...
[ 6, 3, 2 ]
[]
[]
[ "architecture", "backend", "linear_algebra", "metaclass", "python" ]
stackoverflow_0005365126_architecture_backend_linear_algebra_metaclass_python.txt
Q: Large matplotlib pixel figure best approach I have a large 2D dataset where I want to associate to each X,Y pair a color and plot it with matplotlib. I am talking about 1000000 points. I wonder what is the best approach in terms of performance (speed) and if you could point to some example A: If you're dealing w...
Large matplotlib pixel figure best approach
I have a large 2D dataset where I want to associate to each X,Y pair a color and plot it with matplotlib. I am talking about 1000000 points. I wonder what is the best approach in terms of performance (speed) and if you could point to some example
[ "If you're dealing with a regular grid, just treat it as an image:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnrows, ncols = 1000, 1000\nz = 500 * np.random.random(nrows * ncols).reshape((nrows, ncols))\n\nplt.imshow(z, interpolation='nearest')\nplt.colorbar()\nplt.show()\n\n\nIf you have randomly orde...
[ 9 ]
[]
[]
[ "colors", "figure", "matplotlib", "python" ]
stackoverflow_0006318170_colors_figure_matplotlib_python.txt
Q: Inspect import path string from object If an object is a module's class or function I need to retrieve the absolute import path as a string. Example: >>> from a.b.c import foo >>> get_import_path(foo) 'a.b.c.foo' I tried to look into inspect module but there's nothing to do that. A: What your are trying to do i...
Inspect import path string from object
If an object is a module's class or function I need to retrieve the absolute import path as a string. Example: >>> from a.b.c import foo >>> get_import_path(foo) 'a.b.c.foo' I tried to look into inspect module but there's nothing to do that.
[ "What your are trying to do is inherently impossible. foo simply does not know how you imported it -- it might even have been imported in multiple different ways. Example on my Linux box:\n>>> from os.path import normpath\n>>> from posixpath import normpath as normpath2\n>>> normpath is normpath2\nTrue\n\nSo norm...
[ 4, 0 ]
[]
[]
[ "import", "inspect", "python" ]
stackoverflow_0006318347_import_inspect_python.txt
Q: Unicode in PowerShell with Python? Alternative shells in Windows? I want a shell that supports Unicode on Windows. PowerShell as it ships doesn't seem to. PowerShell V2 (Windows 7 x64): PS C:\> powershell Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\> python Python 2.6.2...
Unicode in PowerShell with Python? Alternative shells in Windows?
I want a shell that supports Unicode on Windows. PowerShell as it ships doesn't seem to. PowerShell V2 (Windows 7 x64): PS C:\> powershell Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\> python Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win...
[ "The Windows console subsystem is not Unicode, but code page based. You can play around with setting the code page:\nPS> chcp 65001\nPS> ipy64.exe\n>>> print unichr(0x3a9)\nΩ\n\nI couldn't get (0xF12) to give the right character with that codepage. Perhaps it is available on another code page.\nISE can display Unic...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "powershell", "python", "unicode", "windows" ]
stackoverflow_0002105022_powershell_python_unicode_windows.txt
Q: Django middleware process_template_response method not being called I have the following middleware class: class CommonContextMiddleware: def process_template_response(self, request, response): # Get the context and top videos context = response.context_data ... # Add most_rec...
Django middleware process_template_response method not being called
I have the following middleware class: class CommonContextMiddleware: def process_template_response(self, request, response): # Get the context and top videos context = response.context_data ... # Add most_recent and most_viewed to the context... context['most_recent'] = to...
[ "I assume when you're talking about \"template response\", you are actually returning a TemplateResponse from your Django view?\nThis isn't really the best place for this sort of thing. If you just want to add variables into every template context, the best place to do it is in a context processor.\n" ]
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0006318090_django_django_templates_python.txt
Q: is there a way of hooking into a currently running python script to see whats going on? I have a python script that occasionally freezes and I'd like to find out why? Is there a way to hook into a python script and see what the variables are what line its on and/or what its doing? A: Original Answer Use a debugg...
is there a way of hooking into a currently running python script to see whats going on?
I have a python script that occasionally freezes and I'd like to find out why? Is there a way to hook into a python script and see what the variables are what line its on and/or what its doing?
[ "Original Answer\nUse a debugger as shown in the answers to How do I attach a remote debugger to a Python process?\nOnce attached, you can pause execution and examine variables, the current stack, etc...\nUpdate\nAs pointed out in the comments, the linked debuggers apparently require the process to be launched in a...
[ 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0006318591_debugging_python.txt
Q: Want to import data points from TDS3034C to Labview or Python I've got my Techtronix TDS3034C Oscilloscope hooked up to my router and I know that my computer is able to read it because I'm able to access the waveform via my web browser; however, I need to write something that is able to receive the individual data...
Want to import data points from TDS3034C to Labview or Python
I've got my Techtronix TDS3034C Oscilloscope hooked up to my router and I know that my computer is able to read it because I'm able to access the waveform via my web browser; however, I need to write something that is able to receive the individual data points and output them to a text file. I'd like to be able to do t...
[ "For Labview, you probably want to go to their drivers download page for that 'scope. To write your own software, you'll probably need to download TekVisa.\n", "You can find drivers for most Tek scopes (and others like HP, Agilent, etc) on NI's Instrument Driver Network:\nwww.ni.com/idnet\nAs Jerry Coffin mention...
[ 2, 2 ]
[]
[]
[ "labview", "oscilloscope", "python" ]
stackoverflow_0006257778_labview_oscilloscope_python.txt
Q: Python loop with lists I was writing some Python 3.2 code and this question came to me: I've got these variables: # a list of xml.dom nodes (this is just an example!) child_nodes = [node1, node2, node3] # I want to add every item in child_node into this node (this also a xml.dom Node) parent = xml_document.createE...
Python loop with lists
I was writing some Python 3.2 code and this question came to me: I've got these variables: # a list of xml.dom nodes (this is just an example!) child_nodes = [node1, node2, node3] # I want to add every item in child_node into this node (this also a xml.dom Node) parent = xml_document.createElement('TheParentNode') Thi...
[ "The former is preferable in this situation.\nThe latter is called a list comprehension and creates a new list object full of the results of each call to parent.appendChild(c). And then discards it.\nHowever, if you want to make a list based on this kind of iteration, then you should certainly employ a list compreh...
[ 8, 0 ]
[]
[]
[ "for_loop", "python", "python_3.x" ]
stackoverflow_0006318880_for_loop_python_python_3.x.txt
Q: generating hybrid *.py file from 2 other files I'm trying to write a python script that can combine two python files into a hybrid that overwrites methods from the first file using methods from a second file (those methods can be standalone, or exist inside a class). For example, say I have original.py: from somec...
generating hybrid *.py file from 2 other files
I'm trying to write a python script that can combine two python files into a hybrid that overwrites methods from the first file using methods from a second file (those methods can be standalone, or exist inside a class). For example, say I have original.py: from someclass import Class0 def fun1(a, b): print "fun1"...
[ "With your new improved description I can propose a solution that I've used in the past, as well as other teams, to great effect: use your source control to manage the differences via branches or new repositories.\nFirst things first, please use a source control system of some sort. The more advanced ones, such as ...
[ 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0006313721_parsing_python.txt
Q: Python: no module named unittest. How can I fix this? It seems strange that a module from the std Python lib to be missing. I'm probably doing something wrong, but I cannot figure out what exactly. shift@bt:~/experiments/$ python test/test_creation.py 'import site' failed; use -v for traceback Traceback (most rec...
Python: no module named unittest. How can I fix this?
It seems strange that a module from the std Python lib to be missing. I'm probably doing something wrong, but I cannot figure out what exactly. shift@bt:~/experiments/$ python test/test_creation.py 'import site' failed; use -v for traceback Traceback (most recent call last): File "test/test_creation.py", line 1, in ...
[ "You have your python environment installed into /home/shift/experiments/lib ? see docs.python.org on PYTHONHOME\n" ]
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0006318810_python_unit_testing.txt
Q: The 'int' object is unsubscriptable I have searched for nearly an hour online, but can't find anything. But I digress, line 6 keeps on returning TypeError: 'int' object is unsubscriptable. Please help me identify what causes this. def __reassigner__(allL, currentRow, currentSpace): changingRow=currentRow+1 ...
The 'int' object is unsubscriptable
I have searched for nearly an hour online, but can't find anything. But I digress, line 6 keeps on returning TypeError: 'int' object is unsubscriptable. Please help me identify what causes this. def __reassigner__(allL, currentRow, currentSpace): changingRow=currentRow+1 newl=[-1]*24 while changingRow<8: ...
[ "The variable changingRow is an integer, but you try to slice it with changingRow[0:7]. Since this operation is not allowed on ints, you get the error.\nI don't know what your intention was with that line. Maybe allL is a list of lists and you were going for allL[changingRow][0:7]?\n", "changingRow in your code s...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006319065_python.txt
Q: Storing Python data on a Linux system I have the need to create a system to store python data structures on a linux system but have concurrent read and write access to the data from multiple programs/daemons/scripts. My first thought is I would create a unix socket that would listen for connections and serve up r...
Storing Python data on a Linux system
I have the need to create a system to store python data structures on a linux system but have concurrent read and write access to the data from multiple programs/daemons/scripts. My first thought is I would create a unix socket that would listen for connections and serve up requested data as pickled python data struct...
[ "I would just use SQLite if it's available. \nSee this FAQ: http://www.sqlite.org/faq.html#q5 -- SQLite (with pysqlite [0]) should be able handle your concurrency elegantly.\nYou can keep the data as simple key-value pairs if you like, there's no need to go all BNF on your data.\n[0] http://trac.edgewall.org/wiki/P...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "data_storage", "linux", "pickle", "python" ]
stackoverflow_0006147225_data_storage_linux_pickle_python.txt
Q: Importing with boost python Whether I import like this: numpy_module = bp::import("numpy"); or like this: numpy_module = bp::scope().attr("numpy"); I get terminate called after throwing an instance of 'boost::python::error_already_set' I didn't have a problem with Python 2.7, but after upgrading to Python 3.1, ...
Importing with boost python
Whether I import like this: numpy_module = bp::import("numpy"); or like this: numpy_module = bp::scope().attr("numpy"); I get terminate called after throwing an instance of 'boost::python::error_already_set' I didn't have a problem with Python 2.7, but after upgrading to Python 3.1, this strange exception crops up.
[ "Got it: I needed to compile Boost for Python31.\n" ]
[ 1 ]
[]
[]
[ "boost_python", "python", "python_3.x" ]
stackoverflow_0006318542_boost_python_python_python_3.x.txt
Q: What's the normal structure of a Python open source project and what's the preferred way of running the tests? I wrote some code that I would like to share, and I would like to follow the best practices in creating/maintaining it's structure. I will host the code on BitBucket, and now I'm thinking about how I shou...
What's the normal structure of a Python open source project and what's the preferred way of running the tests?
I wrote some code that I would like to share, and I would like to follow the best practices in creating/maintaining it's structure. I will host the code on BitBucket, and now I'm thinking about how I should organize it. Is this a good structure? project_name/ lib/ test/ README So, this will have the source...
[ "The approach I've come to like is the following:\n\nuse distutils and create a setup.py file. (This is mostly useful\nwhen you have lots of extension classes). This will allow you to install the\nmodule system-wide or in a virtualenv directory.\nIf you want to have serious testing, but stay on the casual side of t...
[ 1 ]
[]
[]
[ "open_source", "project_structure", "python", "unit_testing" ]
stackoverflow_0006319192_open_source_project_structure_python_unit_testing.txt
Q: What happened to thread.start_new_thread in python 3 I liked the ability to turn a function into a thread without the unnecessary line to define a class. I know about _thread, however it appears that you are not supposed to use _thread. Is there a good-practice equivalent of thread.start_new_thread for python 3? ...
What happened to thread.start_new_thread in python 3
I liked the ability to turn a function into a thread without the unnecessary line to define a class. I know about _thread, however it appears that you are not supposed to use _thread. Is there a good-practice equivalent of thread.start_new_thread for python 3?
[ "threading.Thread(target=some_callable_function).start()\n\nor if you wish to pass arguments,\nthreading.Thread(target=some_callable_function,\n args=(tuple, of, args),\n kwargs={'dict': 'of', 'keyword': 'args'},\n ).start()\n\n", "Unfortunately there is not a direct equivalent, because Python 3 ...
[ 47, 5 ]
[]
[]
[ "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0006319268_multithreading_python_python_3.x_python_multithreading.txt
Q: Do math using Django template filter? In my database I have an integer field storing price information, like "10399", "84700". When display, they should be "$103.99" and "$847.00". I need int*0.01 to be displayed. I was wondering if there is a way to do it using Django template filter? Like: {{ item.price|int_to_f...
Do math using Django template filter?
In my database I have an integer field storing price information, like "10399", "84700". When display, they should be "$103.99" and "$847.00". I need int*0.01 to be displayed. I was wondering if there is a way to do it using Django template filter? Like: {{ item.price|int_to_float_and_times_0.01 }} Another question, a...
[ "You could make your own template filter which essentially does what you need by just dividing the input by 100. For example:\nin my_app/templatetags/currency_helper.py:\nfrom django import template\nregister = template.Library()\n\n@register.filter\ndef to_currency(value):\n return float(value) / 100.0\n\nThen...
[ 7, 1, 0, 0 ]
[]
[]
[ "django", "filter", "python", "templates" ]
stackoverflow_0006319093_django_filter_python_templates.txt
Q: Does CouchDB have an equivalent to Redis' expire? Does CouchDB have an equivalent to expire like in Redis? Example for Redis expire: #!/usr/bin/env python import redis redis_server = redis.Redis(host='localhost',port=5477,db=0) r.set('cat','meow') r.expire('cat',10) # do some work and ten seconds later... r.get('c...
Does CouchDB have an equivalent to Redis' expire?
Does CouchDB have an equivalent to expire like in Redis? Example for Redis expire: #!/usr/bin/env python import redis redis_server = redis.Redis(host='localhost',port=5477,db=0) r.set('cat','meow') r.expire('cat',10) # do some work and ten seconds later... r.get('cat') # returns None
[ "No. CouchDB does not have this.\nRedis uses a lazy approach and deletes keys when they are inspected even though they may have expired much earlier. Also, as @antirez pointed out Redis will remove a random set of expired keys every second or so to keep the database size under control.\nIf CouchDB does not natively...
[ 8, 3, 2 ]
[]
[]
[ "couchdb", "key_value_store", "python", "redis" ]
stackoverflow_0006317979_couchdb_key_value_store_python_redis.txt
Q: Connecting to a PostGreSQL 7.3 Database in Python I need to connect to an old PostGreSQL database (version 7.3), and I am using Python 3.2 on an XP machine. The py-postgresql package seemed appropriate, but it seems that it only uses the 3.0 protocol, which was implemented in version 7.4. I'd like to connect to ...
Connecting to a PostGreSQL 7.3 Database in Python
I need to connect to an old PostGreSQL database (version 7.3), and I am using Python 3.2 on an XP machine. The py-postgresql package seemed appropriate, but it seems that it only uses the 3.0 protocol, which was implemented in version 7.4. I'd like to connect to this database using Python, but when I've tried I have ...
[ "Unfortunately for you, both py-postgresql and psycopg2 only support the v3 protocol.\nI think your only option is to use the Postgres ODBC driver, and connect to it using pyODBC or mxODBC. There is a Python 3.x port of pyodbc linked from their main project page.\n", "Try with PyGreSQL:\n\nPyGreSQL is a Python m...
[ 6, 3 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0006310644_postgresql_python.txt
Q: Need to call ldap in App Engine's Python environment I'm trying to add an Ldap authentication backend to a Django project running over GAE. The project runs ok. The only problem really is Ldap is not supported by GAE. I mean: import ldap will generate a server error. Nonetheless, I do know that I could make my ow...
Need to call ldap in App Engine's Python environment
I'm trying to add an Ldap authentication backend to a Django project running over GAE. The project runs ok. The only problem really is Ldap is not supported by GAE. I mean: import ldap will generate a server error. Nonetheless, I do know that I could make my own modules available through zipimport. Does anybody have a...
[ "App Engine doesn't let you open sockets directly. Unless the LDAP server you're planning to connect to has an internet-visible HTTP front-end, you need a Plan B. (E.g., you could periodically upload extract from LDAP to your App.)\nSee http://code.google.com/appengine/docs/python/runtime.html#The_Sandbox\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "ldap", "python" ]
stackoverflow_0006319176_google_app_engine_ldap_python.txt
Q: How do I get the file location of libraries imported by Python Considering this line of Python code: import foo how do I then find the location on disk of the file that contains the source code to be executed in foo? (And I'm on Win7) A: You can find the information in foo.__file__ Note that not all modules co...
How do I get the file location of libraries imported by Python
Considering this line of Python code: import foo how do I then find the location on disk of the file that contains the source code to be executed in foo? (And I'm on Win7)
[ "You can find the information in\nfoo.__file__\n\nNote that not all modules come from files, though. Some modules are also compiled directly into the interpreter, and those modules won't have a __file__ attribute.\nA list of the modules included in the interpreter can be found in sys.builtin_module_names.\n", "I...
[ 4, 0 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0006313259_python_python_2.6.txt
Q: Problems with handling queries to a css-styled mainpage of a GoogleApp when calling an imported class I have this app.yaml file: application: ***** version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /.* script: main.py builtins: - datastore_admin: on And this main.p...
Problems with handling queries to a css-styled mainpage of a GoogleApp when calling an imported class
I have this app.yaml file: application: ***** version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /.* script: main.py builtins: - datastore_admin: on And this main.py script: import service ... ... class UrlHandler(webapp.RequestHandler): def get(self): if self.requ...
[ "service.MainPage() isn't going to have access to the request and response objects that the framework has stuck on to the webapp.RequestHandler instance that get() sees.\nYou could pass self to service.MainPage() (assuming that's a function, and not a class that you're creating an instance of and them doing nothing...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006319664_google_app_engine_python.txt
Q: Apache + mod_wsgi / Lighttpd + wsgi - am I going to see differences in performance? I'm a newbie to developing with Python and I'm piecing together the information I need to make intelligent choices in two other open questions. (This isn't a duplicate.) I'm not developing using a framework but building a web app f...
Apache + mod_wsgi / Lighttpd + wsgi - am I going to see differences in performance?
I'm a newbie to developing with Python and I'm piecing together the information I need to make intelligent choices in two other open questions. (This isn't a duplicate.) I'm not developing using a framework but building a web app from scratch using the gevent library. As far as front-end web servers go, it seems I have...
[ "Apache...\nApache is by far the most widely used web server out there. Which is a good thing. There is so much more information on how to do stuff with it, and when something goes wrong there are a lot of people who know how to fix it. But, it is also the slowest out of the box; requring a lot of tweaking and a be...
[ 5, 1 ]
[]
[]
[ "apache", "lighttpd", "python" ]
stackoverflow_0006319575_apache_lighttpd_python.txt
Q: How does Django Admin Authentication work? I've been looking at the codes for Django's Admin app to identify how they perform blanket authentication check on the user for all of its views without any idea how it was done (Django beginner here). For example, in Admin's sites.py there is the index view that that isn...
How does Django Admin Authentication work?
I've been looking at the codes for Django's Admin app to identify how they perform blanket authentication check on the user for all of its views without any idea how it was done (Django beginner here). For example, in Admin's sites.py there is the index view that that isn't called at all if the user is not authenticate...
[ "Here's the relevant file -- django/contrib/admin/sites.py. In particular, look at the admin_view decorator on line 170 (this is where login is called) and the wrap decorator on line 211, the latter of which is applied on each view of the urlpatterns on line 217. (It's similar to how the login_required decorator fr...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006319893_django_python.txt
Q: textalyser functionality using Python Which Python based library is out that gives the text-analysis functionality similar to the http://textalyser.net/ A: Depends which statistics you want, but this seems like a good start, and includes "readability" statistics like textalyser does: http://www.koders.com/python...
textalyser functionality using Python
Which Python based library is out that gives the text-analysis functionality similar to the http://textalyser.net/
[ "Depends which statistics you want, but this seems like a good start, and includes \"readability\" statistics like textalyser does:\nhttp://www.koders.com/python/fidA751A0C03B16B06781096ED2C89E2B7621FE4BCB.aspx?s=cdef%3Acrawler\nIt uses another module called textanalyzer which will do some of the other things seen ...
[ 1 ]
[]
[]
[ "python", "text_analysis" ]
stackoverflow_0006319915_python_text_analysis.txt
Q: Why I am getting AttributeError: "'NoneType' object has no attribute 'get'" with Python and Tkinkter? from tkinter import * app=Tk() app.title(" BRAIN SYNCRONIZATION SOFTWARE ") e1=Entry(app).pack() t1=Text(app).pack() def InputFun(): file=open("acad.txt","a") file.write("%s;%s"%(t1.get("0.1",E...
Why I am getting AttributeError: "'NoneType' object has no attribute 'get'" with Python and Tkinkter?
from tkinter import * app=Tk() app.title(" BRAIN SYNCRONIZATION SOFTWARE ") e1=Entry(app).pack() t1=Text(app).pack() def InputFun(): file=open("acad.txt","a") file.write("%s;%s"%(t1.get("0.1",END),e1.get())) file.close() b1=Button(app,text="INPUT",command=InputFun,height=3,width=4).pack(side...
[ "t1=Text(app).pack()\n\nshould be\nt1=Text(app)\nt1.pack()\n\nThe Tkinkter pack() method returns None, you can't run .get() on it, but need to keep t1 referring to the text object itself.\n", "I don't think that Entry(app).pack() will return anything. Do you mean e1=Entry(app); e1.pack()?\n" ]
[ 9, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006319942_python.txt
Q: python decompose a list I remember I once seen a operator which is able to decompose a list in python. for example [[1],[2],[3]] by applying that operator, you get [1], [2], [3] what is that operator, any help will be appreciated. A: If you want to pass a list of arguments to a function, you can use *, the s...
python decompose a list
I remember I once seen a operator which is able to decompose a list in python. for example [[1],[2],[3]] by applying that operator, you get [1], [2], [3] what is that operator, any help will be appreciated.
[ "If you want to pass a list of arguments to a function, you can use *, the splat operator. Here's how it works:\nlist = [1, 2, 3]\nfunction_that_takes_3_arguments(*list)\n\nIf you want to assign the contents of a list to a variable, you can list unpacking:\na, b, c = list # a=1, b=2, c=3\n\n", "You can use the tu...
[ 19, 2, 1, 0 ]
[]
[]
[ "list", "operators", "python" ]
stackoverflow_0006319612_list_operators_python.txt
Q: urllib2 gives HTTP Error 400: Bad Request for certain urls, works for others I'm trying to do a simple HTTP get request with Python's urllib2 module. It works sometimes, but other times I get HTTP Error 400: Bad Request. I know it's not an issue with the URL, because if I use urllib and simply do urllib.urlopen(...
urllib2 gives HTTP Error 400: Bad Request for certain urls, works for others
I'm trying to do a simple HTTP get request with Python's urllib2 module. It works sometimes, but other times I get HTTP Error 400: Bad Request. I know it's not an issue with the URL, because if I use urllib and simply do urllib.urlopen(url) it works fine - but when I add headers and do urllib2.urlopen() I get Bad Req...
[ "You've got an extra colon in your headers.\nheaders = { 'User-Agent:': 'Mozilla/5.0' }\n\nShould be:\nheaders = { 'User-Agent': 'Mozilla/5.0' }\n\n" ]
[ 8 ]
[]
[]
[ "http", "python", "url", "urllib2" ]
stackoverflow_0006319890_http_python_url_urllib2.txt
Q: What is the best way to use os.makedirs() when mode is ignored On a linux server I'm working on I need to create directories with the following structure: /dir1/dir2/dir3/YYYY/MM/DD/file.ext There are certain cases (since the directories depend on the date) that I need to create more than a single directory at a t...
What is the best way to use os.makedirs() when mode is ignored
On a linux server I'm working on I need to create directories with the following structure: /dir1/dir2/dir3/YYYY/MM/DD/file.ext There are certain cases (since the directories depend on the date) that I need to create more than a single directory at a time, such as .../2011/01/01/, all of them needing the permission 0o2...
[ "From the mkdir(2) man page:\n\nNOTES\n Under Linux apart from the permission bits, only the S_ISVTX mode bit\n is honored. That is, under Linux the created directory actually gets\n mode (mode & ~umask & 01777).\n\n\nSo yes, SGID is ignored. Set it after the fact.\n" ]
[ 0 ]
[]
[]
[ "linux", "permissions", "python" ]
stackoverflow_0006320058_linux_permissions_python.txt
Q: Initializing classes in module for namespace There is a module car.py. There are engine and tires, and I want them (theirs methods and properties) to be accessible as car.engine.data # and car.tires.data So file parts.py looks like class engineClass(object): def __init__(self): self.data = 'foo dat...
Initializing classes in module for namespace
There is a module car.py. There are engine and tires, and I want them (theirs methods and properties) to be accessible as car.engine.data # and car.tires.data So file parts.py looks like class engineClass(object): def __init__(self): self.data = 'foo data 1' class tiresClass(object): def __init__(s...
[ "Sure... I'm not quite sure what you're asking... \nThere's nothing wrong with what you're doing, but you could skip initializing the classes in the case you've shown. Just do:\nclass type1(object):\n data = 'foo 1'\n\nclass type2(object):\n data = 'foo 2'\n\nWhether or not that makes sense in the context of ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006320092_python.txt
Q: creating elevation/height field gdal numpy python I would like to create some elevation/heightfield rasters using python, gdal and numpy. I'm stuck on numpy (and probably python and gdal.) In numpy, I've been attempting the following: >>> a= numpy.linspace(4,1,4, endpoint=True) >>> b= numpy.vstack(a) >>> c=numpy....
creating elevation/height field gdal numpy python
I would like to create some elevation/heightfield rasters using python, gdal and numpy. I'm stuck on numpy (and probably python and gdal.) In numpy, I've been attempting the following: >>> a= numpy.linspace(4,1,4, endpoint=True) >>> b= numpy.vstack(a) >>> c=numpy.repeat(b,4,axis=1) >>> c array([[ 4., 4., 4., 4.], ...
[ "You aren't too far off. Your only problem is the syntax issues with the GDAL creation options. Replace:\n['MINUSERPIXELVALUE = 1','MAXUSERPIXELVALUE= 4']\n\nwith no spaces before or after the key/value pairs:\n['MINUSERPIXELVALUE=1', 'MAXUSERPIXELVALUE=4']\n\nCheck type(dst_ds) and it should be <class 'osgeo.gdal....
[ 5 ]
[]
[]
[ "gdal", "numpy", "python", "terrain" ]
stackoverflow_0006319889_gdal_numpy_python_terrain.txt
Q: appengine: NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query While using django.core.paginator import ObjectPaginator, I'm getting this error: NeedIndexError: The built-in indices are not efficient enough for this query and ...
appengine: NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query
While using django.core.paginator import ObjectPaginator, I'm getting this error: NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query. The original query is written in this form: query = models.Cdr.all() query.filter("var1 =", v...
[ "The general procedure recommended to fix NeedIndexError occurrences is this one. I expect the composite index may not have been built on your development depending on the amount and structure of the data (which can change depending on var1 value) but turns out to be needed (to avoid aborting the query for efficien...
[ 2, 1 ]
[]
[]
[ "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001363531_django_google_app_engine_google_cloud_datastore_python.txt
Q: Multiple threads, each with different proxy settings Is it possible to run multiple simultaneous thread with different proxy settings. Would calling this in the thread be ok: proxy_support = urllib.request.ProxyHandler({'http': http_proxy}) opener = urllib.request.build_opener(proxy_support) urllib.request.install...
Multiple threads, each with different proxy settings
Is it possible to run multiple simultaneous thread with different proxy settings. Would calling this in the thread be ok: proxy_support = urllib.request.ProxyHandler({'http': http_proxy}) opener = urllib.request.build_opener(proxy_support) urllib.request.install_opener(opener) If you called that same code in a functio...
[ "You can call those in a thread, but their behaviour would affect all threads, so you wouldn't get the result you want.\nHowever, if you use opener.urlopen(...) instead of urllib.request.install_opener(opener) and urllib.request.urlopen(...), it should work fine, with or without threads.\n" ]
[ 2 ]
[]
[]
[ "multithreading", "proxy", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0006320245_multithreading_proxy_python_python_3.x_python_multithreading.txt
Q: UnicodeDecodeError: 'gbk' codec can't decode bytes I'm trying to load an object (of a custom class Area) from a file using pickler. I'm using python 3.1. The file was made with pickle.dump(area, f) I get the following error, and I would like help trying to understand and fix it. File "editIO.py", line 12, in lo...
UnicodeDecodeError: 'gbk' codec can't decode bytes
I'm trying to load an object (of a custom class Area) from a file using pickler. I'm using python 3.1. The file was made with pickle.dump(area, f) I get the following error, and I would like help trying to understand and fix it. File "editIO.py", line 12, in load area = pickle.load(f) File "C:\Python31\lib\pic...
[ "It's hard to say without you showing your code, but it looks like you opened the file in text mode with a \"gbk\" encoding. It should probably be opened in binary mode. If that doesn't happen, make a small code example that fails, and paste it in here.\n" ]
[ 2 ]
[]
[]
[ "decode", "pickle", "python", "python_3.x", "unicode" ]
stackoverflow_0006320415_decode_pickle_python_python_3.x_unicode.txt
Q: Creating a connection to Vertica database in python using adodbapi Does anyone know what are the parameters for creating a connection string to Vertica database using adodbapi? I cannot use pyodbc, because it does not work with IronPython. I have tried: connectorsver = ["DRIVER=Vertica ODBC Driver 4.1"] co...
Creating a connection to Vertica database in python using adodbapi
Does anyone know what are the parameters for creating a connection string to Vertica database using adodbapi? I cannot use pyodbc, because it does not work with IronPython. I have tried: connectorsver = ["DRIVER=Vertica ODBC Driver 4.1"] connectorsver.append("SERVER=1.1.1.1\xx") connectorsver.append ("DATAB...
[ "Looking at the Unit Tests for ADODBAPO, connect() will raise an adodbapi.DatabaseError on failure. You should check for this exception:\ntry:\n con = adodbapi.connect(\";\".join (connectorsver))\nexcept adodbapi.DatabaseError, e:\n print e\n\nWatch your indentation, too. It looks like you're mixing tabs and ...
[ 1 ]
[]
[]
[ "adodbapi", "connection_string", "ironpython", "python", "vertica" ]
stackoverflow_0006320396_adodbapi_connection_string_ironpython_python_vertica.txt
Q: question about IDLE debugger in Python This is a simple question, is it possible to view an entire list in the locals box of the IDLE debugger? Because right now, if a list becomes too long, the debugger will put an ellipsis and not show the entire list. I also tried typing in the name of the list in the actual py...
question about IDLE debugger in Python
This is a simple question, is it possible to view an entire list in the locals box of the IDLE debugger? Because right now, if a list becomes too long, the debugger will put an ellipsis and not show the entire list. I also tried typing in the name of the list in the actual python shell, but nothing happened. here is w...
[ "If you need to dump out large quantities of debug information, import the logging module and invoke it like so:\nimport logging\nlogging.debug(str(axyz))\n\nPython's logging module is tremendously versatile, and can be used for logging to any device in any format you desire.\nOther severity levels can be logged (l...
[ 1 ]
[]
[]
[ "debugging", "ellipsis", "list", "python", "python_idle" ]
stackoverflow_0006320510_debugging_ellipsis_list_python_python_idle.txt
Q: function for getting instance of class VS calling class directly http://doc.qt.io/qt-5/qdesktopwidget.html#obtaining-a-desktop-widget The QApplication::desktop() function is used to get an instance of QDesktopWidget. I don't understand why should you use QApplication::desktop(), when you can just directly call Q...
function for getting instance of class VS calling class directly
http://doc.qt.io/qt-5/qdesktopwidget.html#obtaining-a-desktop-widget The QApplication::desktop() function is used to get an instance of QDesktopWidget. I don't understand why should you use QApplication::desktop(), when you can just directly call QDesktopWidget() class. What is the difference between desktop = QAppl...
[ "They may look the same but are not. On the C++ side the static desktop() function is using a singleton pattern - there is only one desktop and it is represented by a static variable, which may (or may not) be created on request. QDesktopWidget() is a constructor, which is not accessible for the \"outside world\" t...
[ 0 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0006319813_pyqt_python_qt.txt
Q: django-taggit: make the tags not required in the admin I've started using django-taggit and it seems to fit the bill. But for me there is still an issue with the admin site: I included the tags attribute in the ModelAdmin like this: class MyModel(db.models.Model): name = models.CharField(max_length=200) ...
django-taggit: make the tags not required in the admin
I've started using django-taggit and it seems to fit the bill. But for me there is still an issue with the admin site: I included the tags attribute in the ModelAdmin like this: class MyModel(db.models.Model): name = models.CharField(max_length=200) tags = TaggableManager() class MyModelAdmin(admin.ModelAdmi...
[ "Did you try tags = TaggableManager(blank=True)?\n\nblank – Controls whether this field is\n required\n\n... at least that's what the docs say.\n" ]
[ 47 ]
[]
[]
[ "django", "django_taggit", "python" ]
stackoverflow_0006320686_django_django_taggit_python.txt
Q: Django + js Framework I want to develop a web application using Django, but I can't decide which javascript framework to use. May be some of you guys has developed Django + JS Framework application? I personally prefer JQuery because it is easy and fast, but other libraries like Dojo has so cool features and widge...
Django + js Framework
I want to develop a web application using Django, but I can't decide which javascript framework to use. May be some of you guys has developed Django + JS Framework application? I personally prefer JQuery because it is easy and fast, but other libraries like Dojo has so cool features and widgets. That I want to switch t...
[ "If you already have experience with jQuery, then go on with jQuery!\nI use Django + jQuery + Postgresql for all my projects and couldn't be any happier with this powerful combination.\n", "jQuery and Scriptaculous are good choices,\nBut if you want to develop desktop like functionality over the web Qooxdoo helps...
[ 3, 2, 1 ]
[]
[]
[ "django", "frameworks", "javascript", "python" ]
stackoverflow_0006314746_django_frameworks_javascript_python.txt
Q: Write gzipped-already data into a file I have a database with some of the data is binary (blob datatype in MySQL), which was actually webpages scrapped and gzipped. Now I want to extract them and write each record into a gzip file, which I'd assume to be doable - after all they are gzipped-data right? The question...
Write gzipped-already data into a file
I have a database with some of the data is binary (blob datatype in MySQL), which was actually webpages scrapped and gzipped. Now I want to extract them and write each record into a gzip file, which I'd assume to be doable - after all they are gzipped-data right? The question is, however, how would I do that? By search...
[ "You said it yourself: extract them and then write them into a gzip file. There is nothing special about writing \"from gzipped data\": you un-gzip the data to get the original data, and then write the original data as if it were original data (because it is). The documentation shows you how to do these things.\nHo...
[ 0 ]
[]
[]
[ "gzip", "python", "unicode" ]
stackoverflow_0006321366_gzip_python_unicode.txt
Q: Return well-formed numbers I found this in an interview questions forum: Write a function to return well formed numbers of size n. A well formed number is one in which digit i is less than digit i+1, for example 123, 246, 349 etc So here's how I would do it in Python: input number of digits (x) loop over ...
Return well-formed numbers
I found this in an interview questions forum: Write a function to return well formed numbers of size n. A well formed number is one in which digit i is less than digit i+1, for example 123, 246, 349 etc So here's how I would do it in Python: input number of digits (x) loop over all the numbers of x digits for...
[ "How about this solution?\n[int(\"\".join(x)) for x in itertools.combinations(\"123456789\", n)]\n\n", "In my opinion, you've already lost if you're checking every number.\nI'd implement this with a stack. Start by putting 1-9 on the stack. When you take a number off of the stack, add another number to it if you ...
[ 7, 2, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "performance", "python" ]
stackoverflow_0006319583_algorithm_performance_python.txt
Q: Hide Mac OS X development tools from virtualenv environment I'm working on a set of Python scripts for a client and am looking to recreate their environment locally. We're both running OS X Snow Leopard. I have Python 2.7.1 installed, they have the default 2.6.1. I have the developer tools installed, they don't. T...
Hide Mac OS X development tools from virtualenv environment
I'm working on a set of Python scripts for a client and am looking to recreate their environment locally. We're both running OS X Snow Leopard. I have Python 2.7.1 installed, they have the default 2.6.1. I have the developer tools installed, they don't. To make deployment as simple possible, I'm coding for 2.6.1 and lo...
[ "Have you tried modifying the PATH, LD_LIBRARY_PATH etc. environmental variables? \n\nPATH - is a list of paths where OS searches for default executables. So, if you need specific version of gcc,python etc. just put the directory that contains that executable at the beginning of the list, e.g. \nexport PATH=/Users/...
[ 1 ]
[]
[]
[ "deployment", "developer_tools", "macos", "python", "virtualenv" ]
stackoverflow_0006321729_deployment_developer_tools_macos_python_virtualenv.txt
Q: Storing image data (fonts) in hexadecimal format in Python I'm trying to modify this code (http://code.google.com/p/pypng/source/browse/trunk/code/texttopng) so that it can render extended ASCII symbols. Currently I'm trying to figure out how storing the fonts in hexadecimal format works, but after extensive googl...
Storing image data (fonts) in hexadecimal format in Python
I'm trying to modify this code (http://code.google.com/p/pypng/source/browse/trunk/code/texttopng) so that it can render extended ASCII symbols. Currently I'm trying to figure out how storing the fonts in hexadecimal format works, but after extensive googling around I haven't been able to understand it, nor extend it. ...
[ "Basically, don't do that. It is somewhat obscure, esoteric, hard to read and very limited, as you have noticed yourself. The Python Imaging Library offers text rendering to PNG and JPEG using Freetype2, which is a much saner and feature-complete approach.\nNow we have that out of the way, the representation is qui...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006321700_python.txt
Q: Dynamic form generation I have a model for event invitations: class EventInvitation(models.Model): from_user = models.ForeignKey(User, related_name="inviters") to_user = models.ForeignKey(User, related_name="invited") text = models.CharField(max_length= 150) event = models.ForeignKey(Event) se...
Dynamic form generation
I have a model for event invitations: class EventInvitation(models.Model): from_user = models.ForeignKey(User, related_name="inviters") to_user = models.ForeignKey(User, related_name="invited") text = models.CharField(max_length= 150) event = models.ForeignKey(Event) sent = models.DateTimeField(aut...
[ "As I understand, you want a logged in user, from an event page, click on a \"Invite Others\" button, which shows him a form, where he can select specific users and groups, specify some text, and click on \"Send\". Then your app should create many instances of the invitation (one per user) and send them, tracking ...
[ 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006318826_django_django_forms_python.txt
Q: Pickle problem writing to file I have a problem writing a file with Pickle in Python Here is my code: test = "TEST" f1 = open(path+filename, "wb", 0) pickle.dump(test,f1,0) f1.close() return This gives me the output in the .txt file as VTESTp0. I'm not sure why this is? Shouldn't it just have been saved as TEST?...
Pickle problem writing to file
I have a problem writing a file with Pickle in Python Here is my code: test = "TEST" f1 = open(path+filename, "wb", 0) pickle.dump(test,f1,0) f1.close() return This gives me the output in the .txt file as VTESTp0. I'm not sure why this is? Shouldn't it just have been saved as TEST? I'm very new to pickle and I didn'...
[ "No, pickle does not write strings just as strings. Pickle is a serialization protocol, it turns objects into strings of bytes so that you can later recreate them. The actual format depends on which version of the protocol you use, but you should really treat pickle data as an opaque type.\nIf you want to write the...
[ 5, 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0006321749_pickle_python.txt
Q: Uploading files to Google docs programmatically I have many many pdf files around 50GB in my Ebooks folder. Now i want to upload them in Google docs like Rsync of Linux. Is it possible to have the script in php or python which uploads all pdf files in Ebooks folder and subfolders to Google docs. Now the problem is...
Uploading files to Google docs programmatically
I have many many pdf files around 50GB in my Ebooks folder. Now i want to upload them in Google docs like Rsync of Linux. Is it possible to have the script in php or python which uploads all pdf files in Ebooks folder and subfolders to Google docs. Now the problem is i need to restart computer many times and i want tha...
[ "You'd use the Google Documents API to upload them using a simple HTTP POST with the data. Here's an explanation how to upload and convert documents: http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs\nThe link will provide you will examples and all you need to do what you w...
[ 7 ]
[]
[]
[ "google_docs", "php", "python" ]
stackoverflow_0006322201_google_docs_php_python.txt
Q: Python script can retrieve value from memcache, but PHP script gets empty result i run a python script whitch cache some data self.cache.set('test', 'my sample data', 300) data = self.cache.get('test') self.p(data) this program will result in print of 'my sample data' ... everything its good, but when i try to ac...
Python script can retrieve value from memcache, but PHP script gets empty result
i run a python script whitch cache some data self.cache.set('test', 'my sample data', 300) data = self.cache.get('test') self.p(data) this program will result in print of 'my sample data' ... everything its good, but when i try to access this key from php $data = $this->cache->get('test'); print_r($test); i only get ...
[ "Could it be that the hashes don't match between PHP and Python? A solution is here: http://www.ruturaj.net/python-php-memcache-hash\nAdd the following to your Python script to change how hashes are calculated...\nimport memcache\nimport binascii\nm = memcache.Client(['192.168.28.7:11211', '192.168.28.8:11211\n', '...
[ 2 ]
[]
[]
[ "memcached", "php", "python" ]
stackoverflow_0006322425_memcached_php_python.txt
Q: Choosing a Python webscraping framework for handling pure Javascript based sites I'm a Python programmer specializing in web-scraping, I had to ask this question as I found nothing relevant. I want to know what are the popular, well documented frameworks that are available for Python for scraping pure Javascript ...
Choosing a Python webscraping framework for handling pure Javascript based sites
I'm a Python programmer specializing in web-scraping, I had to ask this question as I found nothing relevant. I want to know what are the popular, well documented frameworks that are available for Python for scraping pure Javascript based sites? Currently I know Mechanize and Beautiful Soup but they do not interact wi...
[ "Before using tools like Selenium that are designed for front end testing and not for scraping, you should have a look at where the data on the site comes from. Find out what XHR requests are made, what parameters they take and what the result is.\nFor example the site you mentioned in your comment does a POST requ...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "windmill" ]
stackoverflow_0006321696_python_selenium_selenium_webdriver_web_scraping_windmill.txt
Q: pack/unpack a generator I have a two generators. First generator sometimes needs to call second generator and yield back values it got from there: def a(): for _b in b(): yield _b def b(): yield 1 yield 2 for _a in a(): print _a Is there a more elegant way to do this: for _b in b(): ...
pack/unpack a generator
I have a two generators. First generator sometimes needs to call second generator and yield back values it got from there: def a(): for _b in b(): yield _b def b(): yield 1 yield 2 for _a in a(): print _a Is there a more elegant way to do this: for _b in b(): yield _b I've tried this: yi...
[ "I think you mean PEP380. It's available from Python 3.3. It looks like:\n yield from b()\n\nThere is no special syntax for that in Python2. You just use a for-loop.\nThe a function in your question is actually completely useless. You can just use b in it's place.\n", "You can use a generator expression. It's ab...
[ 6, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006322478_python.txt
Q: Problem with feedparser entry decoding I have the following atom doc, which I'm attempting to parse. However, when I do the following: parsed = feedparser.parse(doc) entries = [a[content][0]['value'].encode('utf-8') for a in parsed] j = [json.loads(e) for e in entries] I get a UnicodeDecodeError for the second en...
Problem with feedparser entry decoding
I have the following atom doc, which I'm attempting to parse. However, when I do the following: parsed = feedparser.parse(doc) entries = [a[content][0]['value'].encode('utf-8') for a in parsed] j = [json.loads(e) for e in entries] I get a UnicodeDecodeError for the second entry: 'utf-8', '\x9d\xa9\x9e\x00\xc8\x9d\xb2\...
[ "The feedparser team answered your question. Please mention on SO if you post your issues elsewhere. It would have saved me time.\n" ]
[ 0 ]
[]
[]
[ "atom_feed", "python" ]
stackoverflow_0006312191_atom_feed_python.txt
Q: Django's Querydict bizarre behavior: bunches POST dictionary into a single key I'm experiencing a really bizarre behavior when using the test client in django. I'm using a POST to send data to my django app. I usually do this from an iPhone app and/or a test html form. On the server side, this is how I handle it: ...
Django's Querydict bizarre behavior: bunches POST dictionary into a single key
I'm experiencing a really bizarre behavior when using the test client in django. I'm using a POST to send data to my django app. I usually do this from an iPhone app and/or a test html form. On the server side, this is how I handle it: def handle_query(request): print request q = con.QueryLog() q.ID = request....
[ "The problem is that you're supplying a content_type. Since you did so, the client is expecting a urlencoded string like\n\"username=hi&password=there&this_is_the_login_form=1\"\n\ninstead of a dictionary like\n{'username': 'hi', 'password': 'there', 'this_is_the_login_form': 1}\n\nIf you remove the content_type kw...
[ 7, 1, 0 ]
[]
[]
[ "django", "post", "python", "rest" ]
stackoverflow_0006315960_django_post_python_rest.txt
Q: wxpython passing information, pointers? I'm trying to code up an application to help me keep track of my students. Basically a customized notebook/gradebook. I hacked something together last summer that worked for this past year, but I need something better. I'm going to pull each students record from a database...
wxpython passing information, pointers?
I'm trying to code up an application to help me keep track of my students. Basically a customized notebook/gradebook. I hacked something together last summer that worked for this past year, but I need something better. I'm going to pull each students record from a database, display it on my main page and have element...
[ "There are not pointers in Python, but there are mutable structures. You can share state between objects by handing the same state-object to multiple instances. \nWhat that state-object should be depends entirely on what you're trying to do (I still have no idea). It could be anything mutable, a module, class, inst...
[ 2, 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006316754_python_wxpython.txt
Q: Python: (sub) String equivalence vs List fast membership testing Can somebody explain to me the following (python 2.7) Two string numbers, from a parsed file: '410.9' '410.9 ' (Notice the trailing space) A_LIST = ['410.9 '] '410.9' in '410.9 ' True '410.9' in A_LIST False No problem working around this - just t...
Python: (sub) String equivalence vs List fast membership testing
Can somebody explain to me the following (python 2.7) Two string numbers, from a parsed file: '410.9' '410.9 ' (Notice the trailing space) A_LIST = ['410.9 '] '410.9' in '410.9 ' True '410.9' in A_LIST False No problem working around this - just trying to understand why it is so. Thanks!
[ "in with two strings checks or a substring, whereas in with a list checks for membership.\nWhat you want is something like [x for x in A_LIST if '419' in x]\n", "The first test is testing whether the first string is a substring of the second, and the second test is testing whether the string is a member of the gi...
[ 7, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006322698_python.txt
Q: Satchmo Gift Certificates. Purchasing multipal gift certificates and only receive one code So I am using Satchmo Store and I have a gift certificate module set up as a way to purchase coupons on my website. However, when I purchase more than 1 on the select quantity page it will only email me one Gift Certificate,...
Satchmo Gift Certificates. Purchasing multipal gift certificates and only receive one code
So I am using Satchmo Store and I have a gift certificate module set up as a way to purchase coupons on my website. However, when I purchase more than 1 on the select quantity page it will only email me one Gift Certificate, not multiple ones according to how many I purchased. Here is the listener to how the gift cert...
[ "i'm far from an expert on the field and have no experience with listeners... but I would say that the listener is called only once because the form is posted/saved only once too. So maybe you should look for the amount of coupons purchased on the model-instance and then go on from there to send multiple mails... o...
[ 0 ]
[]
[]
[ "certificate", "django", "python", "satchmo" ]
stackoverflow_0005865696_certificate_django_python_satchmo.txt
Q: Set today date as default value in the model How can I set the default value as today date in a model? My model: vote_date = models.DateField(_('vote date'), null=False, blank=False) A: None of the answers solve the original problem. Restating the problem, how can I set the default value of a date field to...
Set today date as default value in the model
How can I set the default value as today date in a model? My model: vote_date = models.DateField(_('vote date'), null=False, blank=False)
[ "None of the answers solve the original problem. Restating the problem, how can I set the default value of a date field to todays date and still let the user override the default.\nFrom the DJango docs:\n\nDateField.auto_now \n Automatically set the field to now every time the object\n is saved. Useful for \"las...
[ 3, 1, 0, 0 ]
[]
[]
[ "date", "default", "django", "python" ]
stackoverflow_0005023788_date_default_django_python.txt
Q: decoding ctypes structures I'm trying to get my head around ctypes in python, and I'm able to get some simple things working, but when it comes to unpacking c structs I find myself running into some difficulties. I decided that to learn this I should play around a bit, and while I know the socket standard library ...
decoding ctypes structures
I'm trying to get my head around ctypes in python, and I'm able to get some simple things working, but when it comes to unpacking c structs I find myself running into some difficulties. I decided that to learn this I should play around a bit, and while I know the socket standard library implements gethostbyname_ex(), I...
[ "You need to define what the return type of gethostbyname is:\n>>> libc.gethostbyname.restype = POINTER(hostent)\n>>> he = libc.gethostbyname(\"www.google.com\")[0]\n>>> he.h_aliases[0]\n'www.google.com'\n\nAlso, h_addr_list should not be declared as POINTER(c_char_p), because c_char_p is used for null-terminated s...
[ 4 ]
[]
[]
[ "ctypes", "python", "structure" ]
stackoverflow_0006322781_ctypes_python_structure.txt
Q: Rotate image uploaded via email using PIL for Django website My website allows users to upload photos to their gallery via email and it works perfectly. However, photos taken on the iPhone in portrait mode do NOT rotate correctly. I would like to rotate the photo using PIL during the "mail filtering" process. H...
Rotate image uploaded via email using PIL for Django website
My website allows users to upload photos to their gallery via email and it works perfectly. However, photos taken on the iPhone in portrait mode do NOT rotate correctly. I would like to rotate the photo using PIL during the "mail filtering" process. Here is the code that I am using to successfully retrieve the image...
[ "http://effbot.org/imagingbook/image.htm\nclearly states that rotate() returns an new image instance. \nThere is nothing in the documentation about in-place operations. Or?\n" ]
[ 1 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0006322830_django_python_python_imaging_library.txt
Q: Strace: how to debug invalid argument error I am writing a python program to mount the fuse filesystem through mount system call using ctypes. Now its giving invalid argument error in mount system call. I have checked all the arguments and they seem to be correct. I heard from a friend that strace can be used to d...
Strace: how to debug invalid argument error
I am writing a python program to mount the fuse filesystem through mount system call using ctypes. Now its giving invalid argument error in mount system call. I have checked all the arguments and they seem to be correct. I heard from a friend that strace can be used to debug these type of errors. Can someone guide me h...
[ "Using strace is pretty easy, but it might not give you the information you want.\nSince you know what system call you're after, the simplest thing would be to do:\nstrace -fv -e trace=mount mount /dev/sda1 /tmp\n\n(replace mount /dev/... with your python script).\nThe -f is to follow children (probably unnecessary...
[ 1 ]
[]
[]
[ "c", "python", "strace" ]
stackoverflow_0006322158_c_python_strace.txt
Q: cannot import ipaddr in app engine server In the dev_appserver we can import ipaddr successfully, while when I deploy the codes to app engine server side ,it tells that No module named ipaddr Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__....
cannot import ipaddr in app engine server
In the dev_appserver we can import ipaddr successfully, while when I deploy the codes to app engine server side ,it tells that No module named ipaddr Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 700, in __call__ handler.get(*gr...
[ "If you're trying to use http://code.google.com/p/ipaddr-py/ , then you have to include it (ipaddr.py) as part of your app.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006321863_google_app_engine_python.txt
Q: Code after threads is executed early, why? from threading import Thread import time print 'start of script' class MyThread(Thread): def run(self): for i in xrange(10): print 'thread->', '['+self.name+']', '('+str(i)+')' time.sleep(2) for i in range(3): my_thread = MyThread...
Code after threads is executed early, why?
from threading import Thread import time print 'start of script' class MyThread(Thread): def run(self): for i in xrange(10): print 'thread->', '['+self.name+']', '('+str(i)+')' time.sleep(2) for i in range(3): my_thread = MyThread() my_thread.name = i my_thread.start()...
[ "That's perfectly normal. You're not waiting for the threads to finish, so there is no reason for your code to block after the for loop.\nYou'll need a second loop in which you call .join() on each thread if you want to wait for them.\n\nYet, 'end of script' gets printed right after I execute the first thread, inst...
[ 7, 5, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006323176_python_windows.txt
Q: Google app engine Channel API for COMET on non Javascript clients How to use Google app engine Channel API for COMET on non JavaScript clients. I shall be writing a client in python or any other language, and can do HTTP or Socks from client. How shall I proceed, I want to know what is happening in backed of Java...
Google app engine Channel API for COMET on non Javascript clients
How to use Google app engine Channel API for COMET on non JavaScript clients. I shall be writing a client in python or any other language, and can do HTTP or Socks from client. How shall I proceed, I want to know what is happening in backed of JavaScript client? Is JS using Long Polling or what to talk to GAE server. ...
[ "The asynchronous message passing is done by embedding a hidden iframe in the page, then using the goog.net.CrossPageChannel classes from the Google Closure javascript library to send messages from the iframe to the host page.\nThe Closure CrosspageChannel code is documented here: http://closure-library.googlecode....
[ 8, 4, 3, 3, 0 ]
[]
[]
[ "channel_api", "google_app_engine", "python" ]
stackoverflow_0004721205_channel_api_google_app_engine_python.txt
Q: Simple python question: accessing class data member I have a class which defines data attributes. class channel: def __init(self,var1, var2): self.var1 = var1 self.var2 = var1 #etc So far so simple. But what I'd like to do is to have a method that specifies which data attribute to use ...
Simple python question: accessing class data member
I have a class which defines data attributes. class channel: def __init(self,var1, var2): self.var1 = var1 self.var2 = var1 #etc So far so simple. But what I'd like to do is to have a method that specifies which data attribute to use so that I can generically use it to do the same thing wit...
[ "You can use getattr like this:\ndef fun(list_of_channels, attr_name):\n for chan in list_of_channels:\n attr = getattr(chan, attr_name)\n ...\n\n", "Is the getattr function what you need?\n" ]
[ 9, 3 ]
[]
[]
[ "class", "python" ]
stackoverflow_0006323209_class_python.txt
Q: Pycap not working in script i m trying to capture ethernet packet using pycap http://pycap.sourceforge.net/. when i use following command on python prompt with root privileges, it is working >>>import pycap.capture >>>p = pycap.capture.capture("wlan0") >>>p.next() (Ethernet(type=0x608, 00:1b:b1:46:53:5d -> ff:ff:f...
Pycap not working in script
i m trying to capture ethernet packet using pycap http://pycap.sourceforge.net/. when i use following command on python prompt with root privileges, it is working >>>import pycap.capture >>>p = pycap.capture.capture("wlan0") >>>p.next() (Ethernet(type=0x608, 00:1b:b1:46:53:5d -> ff:ff:ff:ff:ff:ff), ARP(op=0x1, protocol...
[ "Your script using pycap is called pycap itself, so import pycap imports itself (. is usually the first directory on the import path). Because imports are caches, this doesn't lead to infinite recursion but instead gives you a reference to your own module, which of course doesn't define capture or anything else. Re...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0006323337_python.txt
Q: Video Output In Tkinter From GStreamer? does anyone know how i would go about using a tkinter window as an output from a videosink/pipeline from within python? i have found methods for lots of other GUI systems, but i dont want to have to use tkinter and something else together xxx thanks in advance x A: This wo...
Video Output In Tkinter From GStreamer?
does anyone know how i would go about using a tkinter window as an output from a videosink/pipeline from within python? i have found methods for lots of other GUI systems, but i dont want to have to use tkinter and something else together xxx thanks in advance x
[ "This works for me on Windows 32-bit. I get a seg fault on Linux or Windows 64-bit. Sorry, I don't know about Mac.\nYou have to use bus.connect(\"sync-message::element\", on_sync_message) and pass a Tk widget ID (winfo_id), as you can see in the following code. The container can be any Tk widget, but a solid black ...
[ 2 ]
[]
[]
[ "gstreamer", "python", "tkinter" ]
stackoverflow_0004937955_gstreamer_python_tkinter.txt
Q: How does this line work in this python script food = dict(line.split(":", 1) for line in open("file") if line.strip()) I know what this code does but I don't understand why it was put together like this, So can someone explain to me the logic of adding the "if" statement at the end. How does telling the script to...
How does this line work in this python script
food = dict(line.split(":", 1) for line in open("file") if line.strip()) I know what this code does but I don't understand why it was put together like this, So can someone explain to me the logic of adding the "if" statement at the end. How does telling the script to make a dictionary using iteration from a file work...
[ "The if statement is a filter for the generator expression. At the end of a generator expression, you can have an if statement to specify conditions that each item needs to meet to be included in the final generator.\nYou might better understand a more simple example:\n(i for i in range(100) if i % 3 == 0)\n\nretur...
[ 6, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006323663_python.txt
Q: Some problem in search specific value in specific key I wants to search specific value in specific key. example: x = [12, {"hello":"world",}] if x["hello"] == "world": print "Found!" My example above is wrong. What to do? A: My example above is wrong. What to do? Correct it, maybe? Honestly, I feel compelle...
Some problem in search specific value in specific key
I wants to search specific value in specific key. example: x = [12, {"hello":"world",}] if x["hello"] == "world": print "Found!" My example above is wrong. What to do?
[ "\nMy example above is wrong. What to do?\n\nCorrect it, maybe? Honestly, I feel compelled to link to this:\nHow to ask questions the smart way?\nThat being said, the problem is you are trying to index a list with a string, which is not possible. Either do\nx[1][\"hello\"] == \"world\"\n\n...or simply get rid of th...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006321795_python.txt
Q: Make a 2D pixel plot with matplotlib I got the following data from some calculations: x, y, temp where x and y are the coordinates of a point in a 2D box of dimensions 10x10. Spacing is equal to 0.1. So there are 10000 different points and the resulting file looks like: 0.0 0.0 5.6 0.1 0.0 3.2 0.2 0.0 4.1 ... 9....
Make a 2D pixel plot with matplotlib
I got the following data from some calculations: x, y, temp where x and y are the coordinates of a point in a 2D box of dimensions 10x10. Spacing is equal to 0.1. So there are 10000 different points and the resulting file looks like: 0.0 0.0 5.6 0.1 0.0 3.2 0.2 0.0 4.1 ... 9.9 9.9 2.1 I would like to prepare kind of...
[ "Based on the way it looks like your x,y,temp triples are ordered (listed out in rows), you can just reshape the \"temp\" column.\nE.g.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nx,y,temp = np.loadtxt('data.txt').T #Transposed for easier unpacking\nnrows, ncols = 100, 100\ng...
[ 35 ]
[]
[]
[ "grid", "matplotlib", "pixel", "plot", "python" ]
stackoverflow_0006323737_grid_matplotlib_pixel_plot_python.txt
Q: /bin/sh - non interactive usage from Python I am invoking cmd from Python like this: subpocess.Popen(['coffee'], shell=True) which I belive is translated to: /bin/sh -c "coffee" From docs I have read that in non-interactive mode files like /etc/profile, /etc/bash.bashrc are not read and default $PATH is used (in...
/bin/sh - non interactive usage from Python
I am invoking cmd from Python like this: subpocess.Popen(['coffee'], shell=True) which I belive is translated to: /bin/sh -c "coffee" From docs I have read that in non-interactive mode files like /etc/profile, /etc/bash.bashrc are not read and default $PATH is used (init $PATH). Am I right? Is there the only way to a...
[ "No, the shell will inherit the PATH from the Python interpreter, i.e. it will be os.getenv('PATH'). Also, you can set the path within the command:\nsubprocess.Popen(['PATH=/where/ever/bin:$PATH coffee'], shell=True)\n\nthough I'd really advise you to either use the full path to coffee, or set the PATH before execu...
[ 2, 2 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0006323909_python_shell.txt
Q: Python : Hangmangame IndexError: list assignment index out of range I am having a look at python but I seem to have ran into a problem : I have two arrays, one with every letter of a string I randomly got from a file and another array that is is filled with '_' for every letter in the word that the user needs to ...
Python : Hangmangame IndexError: list assignment index out of range
I am having a look at python but I seem to have ran into a problem : I have two arrays, one with every letter of a string I randomly got from a file and another array that is is filled with '_' for every letter in the word that the user needs to find. However it seems that my while loop does not end, even when the wo...
[ "In this line:\nwhile(incorrectGuesses <= 6 or self.correctArray != self.randomWoord ):\n\nor should be and. Also, correctArray is a list, but randomWord is a string, so they will never compare equal. Parentheses are unnecessary as well. Try this:\nwhile incorrectGuesses <= 6 and ''.join(self.correctArray) != se...
[ 3, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0006323731_arrays_python.txt
Q: Django: using the manager of the child model from an abstract parent model class PositionModel(models.Model): xpos = models.IntegerField() ypos = models.IntegerField() def relative(self, x, y): self.__class__.objects.filter(xpos = self.xpos + x, ypos = self...
Django: using the manager of the child model from an abstract parent model
class PositionModel(models.Model): xpos = models.IntegerField() ypos = models.IntegerField() def relative(self, x, y): self.__class__.objects.filter(xpos = self.xpos + x, ypos = self.ypos + y) class Meta: abstract = True This example allows you to i...
[ "Proxy Models are meant to add extra methods or funcionality to the models, without messing with the fields/db... but as you want to inherit this method on more than one model, and Proxy-models are connected to one non-abstract class only, and xpos + ypos are being inherited too, I guess an abstract class could be ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006324077_django_python.txt
Q: Pyramid Framework (SQL Alchemy) - Making the tables globally available Could someone please tell me how one can make table classes and 'dbsession()' created using sqlalchemy in pyramid available globally, so I can query those tables within my templates. Thanks. A: Given you should query in viewsand not in templa...
Pyramid Framework (SQL Alchemy) - Making the tables globally available
Could someone please tell me how one can make table classes and 'dbsession()' created using sqlalchemy in pyramid available globally, so I can query those tables within my templates. Thanks.
[ "Given you should query in viewsand not in templates you can do something like this:\nfrom myproject import models\n\ndef my_view(request):\n return {'models': models}\n\nand in template access DBSession and your model classes with models.DBSession and models.MyClass\n" ]
[ 2 ]
[]
[]
[ "pylons", "pyramid", "python", "sqlalchemy" ]
stackoverflow_0006324336_pylons_pyramid_python_sqlalchemy.txt
Q: Yield item from a thread from threading import Thread import time print 'start of script' class MyThread(Thread): def __init__(self, start, end): self.start = start self.end = end def run(self): for i in xrange(self.start,self.end): yield i my_threads = [] my_thread =...
Yield item from a thread
from threading import Thread import time print 'start of script' class MyThread(Thread): def __init__(self, start, end): self.start = start self.end = end def run(self): for i in xrange(self.start,self.end): yield i my_threads = [] my_thread = MyThread(1,6) my_thread.st...
[ "Threads don't return values, so you won't be able to yield values back to your main thread as you hope to. If you were to get your script to run (you would need to change the name of your start variable to something else since you're shadowing the start method), you would observe that the return value of t.join() ...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006324318_python.txt
Q: Django TemplateSyntaxError I'm following a Django tutorial and suddenly when I try to access http://127.0.0.1:8000/admin/ it gives me a TemplateSyntaxError. TemplateSyntaxError at /admin/ Caught ViewDoesNotExist while rendering: Tried results in module polls.views. Error was: 'module' object has no attribute 'resu...
Django TemplateSyntaxError
I'm following a Django tutorial and suddenly when I try to access http://127.0.0.1:8000/admin/ it gives me a TemplateSyntaxError. TemplateSyntaxError at /admin/ Caught ViewDoesNotExist while rendering: Tried results in module polls.views. Error was: 'module' object has no attribute 'results' It highlights this line: {%...
[ "Caught ViewDoesNotExist while rendering: Tried results in module polls.views. \nError was: 'module' object has no attribute 'results'\n\nThat's pretty much all you need. Ignore the TemplateSyntaxError, it's not related to the template at all. Django is telling you that you don't have this:\ndef results(request):\n...
[ 15 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006324799_django_python.txt
Q: What's the difference between the {% include ... %} tag and and the {% ssi ... parsed %} tag in Django templates? They seem to be basically the same EXCEPT that you have to give ssi an absolute path for "security reasons". Except for keyword arguments (which are new since version 1.3), the two seem to have exactly...
What's the difference between the {% include ... %} tag and and the {% ssi ... parsed %} tag in Django templates?
They seem to be basically the same EXCEPT that you have to give ssi an absolute path for "security reasons". Except for keyword arguments (which are new since version 1.3), the two seem to have exactly the same capabilities. Are they really redundant?
[ "Without the parsed parameter to {% ssi %} the included file won't be treated as a Django template, it will just be included as normal text. This means that if the included file had template tags/filters, they would not be interpreted.\nWhen you do include the parsed parameter, the differences become more like what...
[ 6 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0006324575_django_django_templates_python.txt
Q: Python Unknown pattern finding Okay, basically what I want is to compress a file by reusing code and then at runtime replace missing code. What I've come up with is really ugly and slow, at least it works. The problem is that the file has no specific structure, for example 'aGVsbG8=\n', as you can see it's base64 ...
Python Unknown pattern finding
Okay, basically what I want is to compress a file by reusing code and then at runtime replace missing code. What I've come up with is really ugly and slow, at least it works. The problem is that the file has no specific structure, for example 'aGVsbG8=\n', as you can see it's base64 encoding. My function is really slow...
[ "The easiest way to compress base64-encoded data is to first convert it to binary data -- this will already save 25 percent of the storage space:\n>>> s = \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=\\n\"\n>>> t = s.decode(\"base64\")\n>>> len(s)\n37\n>>> len(t)\n26\n\nIn most cases, you can compress the string even furt...
[ 2, 1 ]
[]
[]
[ "design_patterns", "find", "python" ]
stackoverflow_0006324682_design_patterns_find_python.txt
Q: Please advise on Ruby vs Python, for someone who likes LISP a lot I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a cri...
Please advise on Ruby vs Python, for someone who likes LISP a lot
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can'...
[ "Peter Norvig, a famous and great lisper, converted to Python. He wrote the article Python for Lisp Programmers, which you might find interesting with its detailed comparison of features.\nPython looks like executable pseudo-code. It's easy to pick up, and often using your intuition will just work. Python allows y...
[ 31, 26, 17, 12, 8, 5, 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "lisp", "python", "ruby" ]
stackoverflow_0000405165_lisp_python_ruby.txt
Q: Issue installing Python module on OSX 10.6 and with gcc 4.0 and 4.2 I run sudo python setup.py install to install the Mongrel2 Python support, but it fails with this :- > Installed > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- > packages/m2py-1.0beta7-py2.7.egg > Processing dependencies f...
Issue installing Python module on OSX 10.6 and with gcc 4.0 and 4.2
I run sudo python setup.py install to install the Mongrel2 Python support, but it fails with this :- > Installed > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- > packages/m2py-1.0beta7-py2.7.egg > Processing dependencies for > m2py==1.0beta7 Searching for storm > Reading > http://pypi.python.or...
[ "It appears you have installed Xcode 4 and you've installed a traditional 32-bit-only, backward-compatible Python 2.7.1, possibly from python.org. Unfortunately, the two don't mix well; that Python was built with and requires Xcode 3. You can either backup to Xcode 3 or, better, install a 64-bit/32-bit Python 2.7...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006324912_python.txt
Q: Are there any techniques to separate code and markup in WordPress? I generally work with Python to create web apps and love how I can work separately with the code and presentation layers. I really like working with Jinja2. But, I sometimes have to work with WordPress for my clients. So, I wonder, if there are any...
Are there any techniques to separate code and markup in WordPress?
I generally work with Python to create web apps and love how I can work separately with the code and presentation layers. I really like working with Jinja2. But, I sometimes have to work with WordPress for my clients. So, I wonder, if there are any ways to make developing for WordPress a less headache with all its head...
[ "Agreed with Denis, Wordpress simply is spaghetti, and there's nothing you can do about that. Nonetheless, if you're writing your own code for Wordpress (we make themes and plugins for our customers), there's nothing stopping you from splitting the concerns out into different files, and we found that it's much easi...
[ 3, 1, 1, 0 ]
[]
[]
[ "model_view_controller", "php", "python", "wordpress" ]
stackoverflow_0006280067_model_view_controller_php_python_wordpress.txt
Q: Python win32print changing advanced printer options I am using python 2.7 and win32print. I can successfully change the orientation between portrait and landscape: PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter('300LN1', PRINTER_DEFAULTS) properties = win32p...
Python win32print changing advanced printer options
I am using python 2.7 and win32print. I can successfully change the orientation between portrait and landscape: PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter('300LN1', PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) pDevModeObj.Orientation = 2...
[ "from ctypes import windll\nwindll['winspool.drv'].AdvancedDocumentPropertiesA(None, pHandle.handle, '300LN1', None, None)\n\n" ]
[ 1 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0005555453_python_winapi.txt
Q: AppEngine - trying to redirect to new page after OpenID login I'm using Google App Engine (Python), and using OpenID for login. Specifically, I'm playing with the GitHub project from "metachris" here: https://github.com/metachris/appengine-boilerplate I believe the relevant section of code (App Handler for Login)...
AppEngine - trying to redirect to new page after OpenID login
I'm using Google App Engine (Python), and using OpenID for login. Specifically, I'm playing with the GitHub project from "metachris" here: https://github.com/metachris/appengine-boilerplate I believe the relevant section of code (App Handler for Login) is here: class LogIn(webapp.RequestHandler): def get(self): ...
[ "You didn't say, are you setting the 'continue' query parameter on your login url? If not, try /login?continue=/logged-in.\nFirst time around target_url is being set from the query parameter, it's then being fed into your form using continue_to. The result of it being in the form is that the query parameter will pe...
[ 3 ]
[]
[]
[ "google_app_engine", "openid", "python" ]
stackoverflow_0006324271_google_app_engine_openid_python.txt
Q: In test cases(unit-testing), Django pre_save signal can not be caught In Django, my code on catching pre_save signal works well. However, in testcases in tests.py, the signal handler cannot receive anything. Is there any hint for this problem? It seems that my testcases and signal handler are in different apps. I...
In test cases(unit-testing), Django pre_save signal can not be caught
In Django, my code on catching pre_save signal works well. However, in testcases in tests.py, the signal handler cannot receive anything. Is there any hint for this problem? It seems that my testcases and signal handler are in different apps. Is this the cause of the problem?
[ "\nIt seems that my testcases and signal handler are in different apps. Is this the cause of the problem?\n\nYes. Each app's tests.py is atomic. import your signal registration code or connect them manually somewhere in your test to make sure they are listening:\n\nYou can put signal handling and\n registration co...
[ 5 ]
[]
[]
[ "django", "django_models", "django_signals", "python", "unit_testing" ]
stackoverflow_0006281168_django_django_models_django_signals_python_unit_testing.txt
Q: How to use regex in python in getting a string between two characters? I have this as my input content = 'abc.zip'\n I want to take out abc out of it . How do I do it using regex in python ? Edit : No this is not a homework question . I am trying to automate something and I am stuck at a certain point so that I ...
How to use regex in python in getting a string between two characters?
I have this as my input content = 'abc.zip'\n I want to take out abc out of it . How do I do it using regex in python ? Edit : No this is not a homework question . I am trying to automate something and I am stuck at a certain point so that I can make the automate generic to any zip file I have . os.system('python u...
[ "As I implied in my comment, regular expressions are unlikely to be the best tool for the job (unless there is some artificial restriction on the problem, or it is far more complex than your example). The standard string and/or path libraries provide functions which should do what you are after. To better illustrat...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006325331_python.txt
Q: Naming not unique result error in python? Maybe this is a little unconventional question but I'd like to hear an answer to it. Since english is not my native language I thought I'd ask for a second opinion. I want to raise an Error in python and was wondering how to name it. class AmbiguousResultError(Exception): ...
Naming not unique result error in python?
Maybe this is a little unconventional question but I'd like to hear an answer to it. Since english is not my native language I thought I'd ask for a second opinion. I want to raise an Error in python and was wondering how to name it. class AmbiguousResultError(Exception): pass class NoResultFoundError(Exception): pass ...
[ "I'd prefer AmbiguousStringError to AmbiguousResultError. After all, it's not the result that has multiple meanings, it's the string the user provided.\nOr possibly MultipleResultsFoundError. I think your suggestion of NoUniqueResultFoundError is as good as anything though. If you're as thorough and thoughtful wi...
[ 4 ]
[]
[]
[ "exception", "naming_conventions", "python" ]
stackoverflow_0006325466_exception_naming_conventions_python.txt
Q: Search for a string in a text After answering a question here on SO about finding a city in a user-supplied question, I started thinking about the best way to search for a string in a text when you have a limited data-set as this one. in and find matches against a substring, which is not wanted. Reqular expression...
Search for a string in a text
After answering a question here on SO about finding a city in a user-supplied question, I started thinking about the best way to search for a string in a text when you have a limited data-set as this one. in and find matches against a substring, which is not wanted. Reqular expressions using "word boundaries" works but...
[ "Interesting, Prebuild regex for all cities (ie. one regex for all cities) seems to be winning at performance. I used the same test case and here is the result.\n#!/usr/bin/env python\n\nimport time\nimport re\n\ndef timing(f, n):\n print f.__name__,\n r = range(n)\n t1 = time.clock()\n for i in r:\n ...
[ 1, 1 ]
[]
[]
[ "algorithm", "python", "search", "text" ]
stackoverflow_0006324412_algorithm_python_search_text.txt
Q: Prevent scrollbars from showing up when placing a drawing area inside a scrolled window I'm working on a project using Python and pyGTK. I have a window whose only purpose is showing an image. Unless the image is too big to fit the screen, the window should show no scrollbars by default. So what I do is something ...
Prevent scrollbars from showing up when placing a drawing area inside a scrolled window
I'm working on a project using Python and pyGTK. I have a window whose only purpose is showing an image. Unless the image is too big to fit the screen, the window should show no scrollbars by default. So what I do is something like this: window = gtk.Window() window.resize(image.size[0], image.size[1]) scrolled = gt...
[ "I figured it out :). \nIf you put a DrawingArea inside a ScrolledWindow, things just won't work as they should. Instead, you have to put the DrawingArea in a Viewport, and the Viewport in the ScrolledWindow. gtk.ScrolledWindow provides a method, gtk.ScrolledWindow.add_with_viewport, that does this automatically, ...
[ 5 ]
[]
[]
[ "pygtk", "python", "scrolledwindow" ]
stackoverflow_0006300816_pygtk_python_scrolledwindow.txt
Q: How one define name of fixture in fixtures other then by class name I'd like to use multiple fixtures in the same test suite to test SQLAlchemy model in various situations. What is the easiest way? A: I use fixture methods that are invoked within a test: class TestMyStuff(TestCase): def setUp(self): ...
How one define name of fixture in fixtures other then by class name
I'd like to use multiple fixtures in the same test suite to test SQLAlchemy model in various situations. What is the easiest way?
[ "I use fixture methods that are invoked within a test:\nclass TestMyStuff(TestCase):\n def setUp(self):\n self.Session = Session(bind=engine)\n\n def tearDown(self):\n self.Session.rollback()\n self.Session.close()\n\n def _fixture_one(self):\n self.Session.add_all([\n ...
[ 1 ]
[]
[]
[ "fixtures", "python", "sqlalchemy", "turbogears2" ]
stackoverflow_0006256960_fixtures_python_sqlalchemy_turbogears2.txt
Q: Mark a single row in a table in SQLAlchemy Imagine a table with two columns, id (Integer) and mark (Boolean). This table can have an arbitrary number of rows, but exactly one of this rows should have the column mark set to True. If I modify the database to mark another entry's mark to True, then the system should...
Mark a single row in a table in SQLAlchemy
Imagine a table with two columns, id (Integer) and mark (Boolean). This table can have an arbitrary number of rows, but exactly one of this rows should have the column mark set to True. If I modify the database to mark another entry's mark to True, then the system should first un-mark the previous entry and then mark ...
[ "The two comments above both have truth to them. A trigger is a good way to do this, and also the \"many false, one true\" pattern suggests that perhaps a different table can be used to reference the \"true\" row, or even that the entire \"true\" row might be elsewhere. The usual model here is that your table is ...
[ 4 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006269469_python_sqlalchemy.txt
Q: Python remove anything that is not a letter or number I'm having a little trouble with Python regular expressions. What is a good way to remove all characters in a string that are not letters or numbers? Thanks! A: [\w] matches (alphanumeric or underscore). [\W] matches (not (alphanumeric or underscore)), which ...
Python remove anything that is not a letter or number
I'm having a little trouble with Python regular expressions. What is a good way to remove all characters in a string that are not letters or numbers? Thanks!
[ "[\\w] matches (alphanumeric or underscore).\n[\\W] matches (not (alphanumeric or underscore)), which is equivalent to (not alphanumeric and not underscore)\nYou need [\\W_] to remove ALL non-alphanumerics.\nWhen using re.sub(), it will be much more efficient if you reduce the number of substitutions (expensive) by...
[ 41, 10, 9, 4, 3, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0006323296_python_regex_string.txt
Q: Flask error handling I'm trying to catch an error generated by flask-sqlalchemy. My code unfortunately can't handle the error because the debugger catches it first. It happens when I try to insert a record into a database with a field that's supposed to be unique but is duplicated.Is there any way around this? Thi...
Flask error handling
I'm trying to catch an error generated by flask-sqlalchemy. My code unfortunately can't handle the error because the debugger catches it first. It happens when I try to insert a record into a database with a field that's supposed to be unique but is duplicated.Is there any way around this? This is the traceback. sqlalc...
[ "You need to put a try/catch in your create_user function (masterpieces_of_code/app.py) in the block of code which does the db.session.commit(), and handle the exception there.\nUpdate: If you are getting a NameError for IntegrityError then it means you are likely to be missing a\nfrom sqlalchemy.exc import Integri...
[ 10 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0006325822_flask_flask_sqlalchemy_python.txt
Q: Efficient way to move an object in Tkinter Canvas I need some help for an assignment, I asked a question related to it this evening, but I recognize it was very poorly stated and written. I'll try to be a little more specific this time. I have the following piece of code, it's inside a Game class (that inherits fr...
Efficient way to move an object in Tkinter Canvas
I need some help for an assignment, I asked a question related to it this evening, but I recognize it was very poorly stated and written. I'll try to be a little more specific this time. I have the following piece of code, it's inside a Game class (that inherits from the Canvas class): def move_ball(self): if s...
[ "Twenty milliseconds seems like a short schedule time which might tweak some platform dependency that I don't know of. It is also not clear from your code snippet what values balldir may be assigned. If you expect balldir to only ever be 0 or 1 you might find this helpful:\ndef move_ball(self):\n assert 0 <= sel...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006325981_python_tkinter.txt