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:
Remote debugging with WingIDE
Using WingIDE to debug a web application, I have set a breakpoint in some Python code which runs when a web-form is submitted. Just before the breakpoint I have inserted 'import wingdbstub' to activate remote deubgging. However, execution does not stop at the breakpoint. I know the... | Remote debugging with WingIDE | Using WingIDE to debug a web application, I have set a breakpoint in some Python code which runs when a web-form is submitted. Just before the breakpoint I have inserted 'import wingdbstub' to activate remote deubgging. However, execution does not stop at the breakpoint. I know the code is running because if I inser... | [
"Under Windows, I've experienced the same behavior you mention, i.e., remote debugging sometimes works, but often 'gets stuck'. I've found a few things helpful in resolving this situation:\n\nMake sure your firewall isn't blocking traffic to/from the ports being used by WingIDE and the process being debugged. (In... | [
2
] | [] | [] | [
"python",
"remote_debugging"
] | stackoverflow_0004063482_python_remote_debugging.txt |
Q:
GAE - Secure data Connector and Taskqueue/Cron
Is it possible to use the Secure Data Connector (SDC) to access internal resources in Tasks/Cron Jobs on the Google AppEngine?
The documentation speaks about the currently logged in user but does not further elaborate this scenario.
A:
'Offline' requests such as Tas... | GAE - Secure data Connector and Taskqueue/Cron | Is it possible to use the Secure Data Connector (SDC) to access internal resources in Tasks/Cron Jobs on the Google AppEngine?
The documentation speaks about the currently logged in user but does not further elaborate this scenario.
| [
"'Offline' requests such as Task Queue tasks and Cron jobs have no 'user' as far as systems like SDC are concerned. If your SDC connection requires a logged in user, you will not be able to access it from a cron/task queue job.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004296830_google_app_engine_python.txt |
Q:
Managing seed data with SqlAlchemy and SqlAlchemy-migrate
I'm using SqlAlchemy in my Pylons application to access data and SqlAlchemy-migrate to maintain the database schema.
It works fine for managing the schema itself. However, I also want to manage seed data in a migrate-like way. E.g. when ProductCategory tabl... | Managing seed data with SqlAlchemy and SqlAlchemy-migrate | I'm using SqlAlchemy in my Pylons application to access data and SqlAlchemy-migrate to maintain the database schema.
It works fine for managing the schema itself. However, I also want to manage seed data in a migrate-like way. E.g. when ProductCategory table is created it would make sense to seed it with categories dat... | [
"Well what format is your seed data starting out in? The migrate calls are just python methods so you're free to open some csv, create SA object instances, loop, etc. I usually have my seed data as a series of sql insert statements and just loop over them executing a migate.execute(query) for each one. \nSo I'll fi... | [
2
] | [] | [] | [
"pylons",
"python",
"sqlalchemy",
"sqlalchemy_migrate"
] | stackoverflow_0004298886_pylons_python_sqlalchemy_sqlalchemy_migrate.txt |
Q:
Python - Saving an image from a url
Is there a way to save a picture from a url using urllib or Beautiful Soup?
-Thanks
A:
You want urllib.urlretrieve().
A:
no need of Beautiful Soup as i assume you need to read a binary file.
Just read the stream and store it as a file.
import urllib ... | Python - Saving an image from a url | Is there a way to save a picture from a url using urllib or Beautiful Soup?
-Thanks
| [
"You want urllib.urlretrieve().\n",
"no need of Beautiful Soup as i assume you need to read a binary file.\nJust read the stream and store it as a file.\nimport urllib \nurl = \"http://example.com/file.pdf\"\nuopen = urllib.urlopen(url)\nstream = uopen.read()\nfile = open('fi... | [
5,
3,
0,
-1
] | [] | [] | [
"beautifulsoup",
"python",
"urllib"
] | stackoverflow_0004300042_beautifulsoup_python_urllib.txt |
Q:
VirtualEnv cannot import name wraps
I'm trying to figure out why my Djagno wsgi script won't run. It runs fine under normal python but virtualenv produces the following stack trace:
(virtualenv)... [~]# python djangosites/test1.wsgi
Traceback (most recent call last):
File "djangosites/test1.wsgi", line 13, in <... | VirtualEnv cannot import name wraps | I'm trying to figure out why my Djagno wsgi script won't run. It runs fine under normal python but virtualenv produces the following stack trace:
(virtualenv)... [~]# python djangosites/test1.wsgi
Traceback (most recent call last):
File "djangosites/test1.wsgi", line 13, in <module>
from django.core.handlers.wsg... | [
"Created a new virtualenv as this one was broken. No problems now.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"wsgi"
] | stackoverflow_0004300102_django_python_wsgi.txt |
Q:
Background image removal component
I'm looking for an API/Library/Component to use in my Django app that takes an image as an input and returns the same image with transparent background. I'm looking for something smarter than ImageMagick's floodfill http://www.imagemagick.org/Usage/channels/#mask_floodfill that d... | Background image removal component | I'm looking for an API/Library/Component to use in my Django app that takes an image as an input and returns the same image with transparent background. I'm looking for something smarter than ImageMagick's floodfill http://www.imagemagick.org/Usage/channels/#mask_floodfill that detects the color of the background.
Any ... | [
"In PIL you have im.save(filename, transparency=some_palette_index) for mode P images or putalpha method for RGB images.\n"
] | [
0
] | [] | [] | [
"api",
"django",
"image_processing",
"python"
] | stackoverflow_0004300286_api_django_image_processing_python.txt |
Q:
Django: is_authenticated and is_anonymous both return true after logout
I am using django-registration, and just set it up.
{{user.is_authenticated }}
is true, even though i went already to /accounts/logout/ and logged the user out.
{{user.is_anonymous }}
returns true also. According to django docs, those two... | Django: is_authenticated and is_anonymous both return true after logout | I am using django-registration, and just set it up.
{{user.is_authenticated }}
is true, even though i went already to /accounts/logout/ and logged the user out.
{{user.is_anonymous }}
returns true also. According to django docs, those two should be different:
is_anonymous: Always returns False. This is a way of d... | [
"It seems like you are trying to figure out two things at once; what is the correct way to use jinja templates and what is the deal with User/AnonymousUser. Maybe try to figure out these problems one at a time.\nI have no experience with jinja but you may want to check and make sure that you are taking differences... | [
11,
4
] | [] | [] | [
"authentication",
"django",
"django_registration",
"python",
"templates"
] | stackoverflow_0004298387_authentication_django_django_registration_python_templates.txt |
Q:
Help building a mac application from python using py2app?
I have a Tkinter app written in python, and I want to make "native" (easy to run) mac and windows executables of it. I've successfully built a windows .exe using py2exe, but the equivalent process with py2app isn't working.
Here's my setup.py:
from setuptoo... | Help building a mac application from python using py2app? | I have a Tkinter app written in python, and I want to make "native" (easy to run) mac and windows executables of it. I've successfully built a windows .exe using py2exe, but the equivalent process with py2app isn't working.
Here's my setup.py:
from setuptools import setup
import sys
MAIN_SCRIPT = "myapp.py"
WINDOWS_IC... | [
"Turns out it was a problem with using Snow Leopard. I tried it on a Leopard machine at school and it builds fine.\n"
] | [
0
] | [] | [] | [
"py2app",
"python",
"tkinter"
] | stackoverflow_0004294060_py2app_python_tkinter.txt |
Q:
Delete() an instance
In my view:
def delete_payment(request, id):
thePayment = Payment.objects.filter(id=id)
thePayment.delete()
return HttpResponseRedirect('/invoices/open/')
In my model:
def delete(self, *args, **kwargs):
raise Exception('foo')
super(Payment, self).delete(*args, **kwargs)
I... | Delete() an instance | In my view:
def delete_payment(request, id):
thePayment = Payment.objects.filter(id=id)
thePayment.delete()
return HttpResponseRedirect('/invoices/open/')
In my model:
def delete(self, *args, **kwargs):
raise Exception('foo')
super(Payment, self).delete(*args, **kwargs)
I'm finding that the except... | [
"Manager.filter() returns a QuerySet, not a Model. QuerySet.delete() doesn't invoke Model.delete() but rather operates directly on the database.\n"
] | [
4
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0004300933_django_model_python.txt |
Q:
Whats the pythonic way to handle empty *args when creating a set?
Defining a function,
MyFunction(argument, *args):
[do something to argument[arg] for arg in *args]
if *args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of *args == 0'
def Export(... | Whats the pythonic way to handle empty *args when creating a set? | Defining a function,
MyFunction(argument, *args):
[do something to argument[arg] for arg in *args]
if *args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of *args == 0'
def Export(source, target, *args, sep=','):
for item in source:
Subset... | [
"Is there a way to pass an \"entire set\" argument to SubsetOutput, so you can bury the conditional inside its call rather than have an explicit if? This could be None or [], for example.\n# Pass None to use full subset.\ndef Export(source, target, *args, sep=','):\n for item in source:\n SubsetOutput(Wri... | [
5,
4,
1
] | [] | [] | [
"arguments",
"default",
"function",
"function_signature",
"python"
] | stackoverflow_0004300979_arguments_default_function_function_signature_python.txt |
Q:
Highly scalable tags on Google App Engine (Python)
I have a lot of (e.g.) posts, that marked with one or more tags. Post can be created or deleted, and also user can make search request for one or more tags (combined with logical AND).
First idea that came to my mind was a simple model
class Post(db.Model):
#bla... | Highly scalable tags on Google App Engine (Python) | I have a lot of (e.g.) posts, that marked with one or more tags. Post can be created or deleted, and also user can make search request for one or more tags (combined with logical AND).
First idea that came to my mind was a simple model
class Post(db.Model):
#blahblah
tags = db.StringListProperty()
Implementation o... | [
"To further Nick's questioning. If it is a logical AND using multiple tags in they query. Use tags = tag1 AND tags = tag2 ... set membership in a single query is one of datastore's shining features. You can achieve your result in one query.\nhttp://code.google.com/appengine/docs/python/datastore/queriesandindexes... | [
1,
0
] | [] | [] | [
"google_app_engine",
"high_load",
"microblogging",
"python",
"tags"
] | stackoverflow_0004280460_google_app_engine_high_load_microblogging_python_tags.txt |
Q:
How to improve performance of this code?
Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in Python). The example run in the bottom of the code takes a long time to be solved in ... | How to improve performance of this code? | Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in Python). The example run in the bottom of the code takes a long time to be solved in my machine:
dumrat@dumrat:~/programming/python... | [
"First let me tell you how to find the problem. Then I'll tell you where it is:\nI haven't even bothered to try to figure out your code. I just ran it and took 3 random-time stack samples. I did that by typing control-C and looking at the resulting stacktrace.\nOne way to look at it is: if a statement appears on X%... | [
78,
39,
9,
4,
3,
3,
0
] | [] | [] | [
"optimization",
"performance",
"python",
"time_complexity"
] | stackoverflow_0004295799_optimization_performance_python_time_complexity.txt |
Q:
How does jsfiddle mark up code? Is there a library for this?
If you've ever used www.jsfiddle.net, you might notice that it marks up code with proper colorings, and various other helpers like translating tabs to four spaces or shift-tab. With Firebug I see that it's doing this with an iFrame. Is there an open so... | How does jsfiddle mark up code? Is there a library for this? | If you've ever used www.jsfiddle.net, you might notice that it marks up code with proper colorings, and various other helpers like translating tabs to four spaces or shift-tab. With Firebug I see that it's doing this with an iFrame. Is there an open source library to do this? I want to let people write Python on a w... | [
"Check out CodeMirror.\n",
"Look here (SyntaxHighlighter)\nHere you can find a simple tutorial.\n"
] | [
7,
2
] | [] | [] | [
"javascript",
"jquery",
"jsfiddle",
"mootools",
"python"
] | stackoverflow_0004301347_javascript_jquery_jsfiddle_mootools_python.txt |
Q:
Python wont remove items from list
filtered_list = ['PerezHilton', 'tomCruise', 'q', 'p']
#BIO[user]['follows'] is just a list of strings say ['a', 'b', 'katieh']
#specs is also a string say eg. 'katieh'
for user in filtered_list:
if specs not in BIO[user]['follows']:
filtered_list.remove(user)
The ab... | Python wont remove items from list | filtered_list = ['PerezHilton', 'tomCruise', 'q', 'p']
#BIO[user]['follows'] is just a list of strings say ['a', 'b', 'katieh']
#specs is also a string say eg. 'katieh'
for user in filtered_list:
if specs not in BIO[user]['follows']:
filtered_list.remove(user)
The above code for some reson gives this error... | [
"The list comprehension that does this correctly in one line is at the bottom of the post. Here's some insight into the problem first.\nDon't do things like:\nfor item in list_:\n list_.remove(item)\n\nbecause bad and confusing things happen.\n>>> list_ = range(10)\n>>> for item in list_:\n... list_.remove(i... | [
7,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004301634_list_python.txt |
Q:
How to upload through django admin
documents = models.FileField(upload_to=settings.FILE_PATH, verbose_name=
_('Attach Your Documents'), help_text=_('.pdf file not exceeding 5 mb.'),
null=True, blank=True)
By this way i am creating a models for the upload of a file in django admin. Now I want to upload this f... | How to upload through django admin | documents = models.FileField(upload_to=settings.FILE_PATH, verbose_name=
_('Attach Your Documents'), help_text=_('.pdf file not exceeding 5 mb.'),
null=True, blank=True)
By this way i am creating a models for the upload of a file in django admin. Now I want to upload this file to S3 when some one click save on dj... | [
"You could try django-storages\n"
] | [
3
] | [] | [] | [
"django",
"python",
"upload"
] | stackoverflow_0004301824_django_python_upload.txt |
Q:
python boolean expression not "short-circuit"?
For example:
def foo():
print 'foo'
return 1
if any([f() for f in [foo]*3]):
print 'bar'
I thought the above code should output:
foo
bar
instead of :
foo
foo
foo
bar
Why ? how can I make the "short-circuit" effect ?
A:
Deconstruct your program to see w... | python boolean expression not "short-circuit"? | For example:
def foo():
print 'foo'
return 1
if any([f() for f in [foo]*3]):
print 'bar'
I thought the above code should output:
foo
bar
instead of :
foo
foo
foo
bar
Why ? how can I make the "short-circuit" effect ?
| [
"Deconstruct your program to see what is happening:\n>>> [f() for f in [foo]*3]\nfoo\nfoo\nfoo\n[1, 1, 1]\n>>> \n\nYou are already creating a list and passing to any and have printed it 3 times.\n>>> any ([1, 1, 1])\nTrue\n\nThis is fed to if statement:\n>>> if any([1, 1, 1]):\n... print 'bar'\n... \nbar\n>>> \... | [
18,
5
] | [] | [] | [
"python",
"short_circuiting"
] | stackoverflow_0004301921_python_short_circuiting.txt |
Q:
Merging items in a list - Python
Say I have a list in python, like such:
list=[1,2,3,4,5]
How would I merge the list so that it becomes:
list= [12345]
If anyone has a way to do this, it would be greatly appreciated!!
A:
reduce(lambda x,y:10*x+y, [1,2,3,4,5])
# returns 12345
A:
This probably better:
"%s" * le... | Merging items in a list - Python | Say I have a list in python, like such:
list=[1,2,3,4,5]
How would I merge the list so that it becomes:
list= [12345]
If anyone has a way to do this, it would be greatly appreciated!!
| [
"reduce(lambda x,y:10*x+y, [1,2,3,4,5])\n# returns 12345\n\n",
"This probably better:\n\"%s\" * len(L) % tuple(L)\n\nwhich can handle:\n>>> L=[1, 2, 3, '456', '7', 8]\n>>> \"%s\"*len(L) % tuple(L)\n'12345678'\n\n",
">>> list=[1,2,3,4,5]\n>>> k = [str(x) for x in list]\n>>> k\n['1', '2', '3', '4', '5']\n>>> \"\"... | [
15,
9,
8,
3,
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004299741_list_python.txt |
Q:
Python 3 Online Interpreter / Shell
Is there an online interpreter like http://codepad.org/ or http://www.trypython.org/ which uses Python 3?
Answer
Since the question is closed, I give another answer here.
Wandbox offers online REPLs for many languages, including Python 2.x and 3.x, C++ and Java.
A:
Ideone supp... | Python 3 Online Interpreter / Shell | Is there an online interpreter like http://codepad.org/ or http://www.trypython.org/ which uses Python 3?
Answer
Since the question is closed, I give another answer here.
Wandbox offers online REPLs for many languages, including Python 2.x and 3.x, C++ and Java.
| [
"Ideone supports Python 2.6 and Python 3\n",
"I recently came across Python 3 interpreter at CompileOnline.\n"
] | [
49,
3
] | [] | [] | [
"interpreter",
"python",
"python_3.x",
"shell"
] | stackoverflow_0002737539_interpreter_python_python_3.x_shell.txt |
Q:
Installing Python 2.5.2 on OS X 10.6
I am installing Python 2.5.2 on my Mac (OSX 10.6).
I downloaded the source, ran ./configure, and then ran make. I received this error:
gcc -c -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -... | Installing Python 2.5.2 on OS X 10.6 | I am installing Python 2.5.2 on my Mac (OSX 10.6).
I downloaded the source, ran ./configure, and then ran make. I received this error:
gcc -c -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -o Modules/py... | [
"See my answer here. While you can build it from scratch with the suggested patches, it may be a lot easier to just download a prebuilt installer from python.org as suggested there.\n"
] | [
0
] | [] | [] | [
"gcc",
"installation",
"macos",
"python"
] | stackoverflow_0004301891_gcc_installation_macos_python.txt |
Q:
Can you explain the following signal handling behavior in python?
I have the following program:
import socket
import sys
import threading
import signal
class serve(threading.Thread):
def __init__(self):
super(serve, self).__init__()
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... | Can you explain the following signal handling behavior in python? | I have the following program:
import socket
import sys
import threading
import signal
class serve(threading.Thread):
def __init__(self):
super(serve, self).__init__()
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = ''
self.port = int(sys.argv[1])
def run(s... | [
"If a system call is executing when a signal arrives, the system call is interrupted. I believe this is in part to prevent escalation attacks and in part to keep the process in a consistent state when the signal handler is invoked. It also would allow you to wake up a process that's hung on a system call.\nTo inste... | [
1
] | [] | [] | [
"freebsd",
"python",
"signal_handling",
"signals"
] | stackoverflow_0004301796_freebsd_python_signal_handling_signals.txt |
Q:
Is there an order in which models are generated into database?
In my project I need to change the location where files are being uploaded. This is done using a FileSystemStorage. The path were the files are uploaded should be easy to configure, for example using the Django Admin.
from django.core.files.storage im... | Is there an order in which models are generated into database? | In my project I need to change the location where files are being uploaded. This is done using a FileSystemStorage. The path were the files are uploaded should be easy to configure, for example using the Django Admin.
from django.core.files.storage import FileSystemStorage
from django.db import models
class Setti... | [
"That won't solve your problem, since the Settings table still won't be populated. Move it into a class attribute that gets initialized the first time it's instantiated.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004302058_django_django_models_python.txt |
Q:
Omit last element in comma-separated list
I'm writing a tagging system. The user enters a number of tags:
abc, def, ghi,
But if they use a trailing comma, the code thinks there are 4 tags, not three.
In my code, I write:
if "tags" in request.POST:
tags = request.POST["tags"]
tag_list = [Tag.objects.get_o... | Omit last element in comma-separated list | I'm writing a tagging system. The user enters a number of tags:
abc, def, ghi,
But if they use a trailing comma, the code thinks there are 4 tags, not three.
In my code, I write:
if "tags" in request.POST:
tags = request.POST["tags"]
tag_list = [Tag.objects.get_or_create(name = tag.lstrip())[0] for tag in tag... | [
">>> x = \"first, second, third,\"\n>>> y = [ele for ele in x.split(',') if ele]\n>>> y\n['first', ' second', ' third']\n\nUsing the fact that non empty strings return True.\n",
"for tag in tags.split(\",\") if tag.strip()\n\n",
"Use filter(), like so:\ndef f(x): return x != ''\n\nfilter( f, tag_list )\n\n",
... | [
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004298415_django_python.txt |
Q:
gtk.treeviewcolumn not sorting
I've gotten a sortable treeview working. Clicking on the columns makes it sort by ascending order, and clicking it again makes it sort by descending order. However, if I click on the column header a third time, it goes to some "unsorted" state, instead of back to ascending. I connect... | gtk.treeviewcolumn not sorting | I've gotten a sortable treeview working. Clicking on the columns makes it sort by ascending order, and clicking it again makes it sort by descending order. However, if I click on the column header a third time, it goes to some "unsorted" state, instead of back to ascending. I connected a function to the clicked signal ... | [
"The self.hsModelSort.set_default_sort_func(None) works, but you will lose the original state (previous any sort), if is that what you want then thats the solution, if you want to keep the original form you must set the default function to some function that sort the column to the original state.\nMost likely you ... | [
1,
0
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003929086_gtk_gtktreeview_pygtk_python.txt |
Q:
How do I access the AUTH_PROFILE_MODULE in Django's template?
I can do this...and it prints the username.
{{ user.username }}
How can I print one of the field in my UserDetails model? (that's my AUTH_PROFILE_MODULE)
{{ user.get_profile().avatar_link }}???
A:
{{ user.get_profile.avatar_link }}
| How do I access the AUTH_PROFILE_MODULE in Django's template? | I can do this...and it prints the username.
{{ user.username }}
How can I print one of the field in my UserDetails model? (that's my AUTH_PROFILE_MODULE)
{{ user.get_profile().avatar_link }}???
| [
"{{ user.get_profile.avatar_link }}\n"
] | [
4
] | [] | [] | [
"django",
"html",
"python",
"templates"
] | stackoverflow_0004301925_django_html_python_templates.txt |
Q:
How to find lat long values from the POINT
i have Point value which is POINT(24.3 80.2) which is stored in variable pnt
I want to have the lat and long values seperately. is there any simple way to get that using python
POINT here is geographical location which meanse POINT(longitude latitude)
A:
[Edit: Ignacio ... | How to find lat long values from the POINT | i have Point value which is POINT(24.3 80.2) which is stored in variable pnt
I want to have the lat and long values seperately. is there any simple way to get that using python
POINT here is geographical location which meanse POINT(longitude latitude)
| [
"[Edit: Ignacio Vazquez-Abrams is spot on!]\n\nYou are using geos django. \n\nCheck out the docs.\n>>> pnt = Point(5, 23)\n>>> [coord for coord in pnt]\n[5.0, 23.0]\n>>> pnt.coords\n(5.0, 23.0)\n\nThe following is not relevant but can be used. Kept for other references.\nCheck out the following project : pyproj\n\n... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004302475_django_python.txt |
Q:
Problem related to forms using Models
I have model Person or say Profile and this class Person has a genericRelationship with the phonenumber class.Now I wanted to generate a ModelForm which displays the option of adding two or three contact numbers at a time in a single form. Is this possible ?
My models look lik... | Problem related to forms using Models | I have model Person or say Profile and this class Person has a genericRelationship with the phonenumber class.Now I wanted to generate a ModelForm which displays the option of adding two or three contact numbers at a time in a single form. Is this possible ?
My models look like :
class Person(models.Model):
"""Pe... | [
"As per Django Doc\n\nGeneric Relations : let an object have\n a foreign key to any object through a\n content-type/object-id field. A\n GenericForeignKey field can point to\n any object, be it animal, vegetable,\n or mineral.\n\nThis means you can do what you are saying you want to do.\nUPDATE: Adding some co... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004302504_django_python.txt |
Q:
Trouble with Django, request and logging in?
Hey All-
I'm completely new to Django/python and am going through a tutorial for a class, located here. I've got most of this working, but I'm having trouble. I can register a user, but seemingly cannot login. For the relevant part of the tutorial, search for the line... | Trouble with Django, request and logging in? | Hey All-
I'm completely new to Django/python and am going through a tutorial for a class, located here. I've got most of this working, but I'm having trouble. I can register a user, but seemingly cannot login. For the relevant part of the tutorial, search for the line We’ll need one more form, a login form: which exp... | [
"In real life, you'd use django.contrub.auth for login/authentication.\nIt looks you don't set request.session[\"user_id\"] to user.pk. As I see, this is done in the login view in the tutorial. Is your login view exactly the same as in tutorial? Do you have method=\"post\" in your login form?\n",
"Have you added ... | [
0,
0
] | [] | [] | [
"django",
"python",
"request"
] | stackoverflow_0004302404_django_python_request.txt |
Q:
If a python iterator returns iterable objects, how can I chain those objects into one big iterator?
I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them toget... | If a python iterator returns iterable objects, how can I chain those objects into one big iterator? | I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them together into one long iterator. Is there a standard utility to make this possible?
Here is a contrived exampl... | [
"You can use itertools.chain.from_iterable\n>>> import itertools\n>>> x = iter([ xrange(0,5), xrange(5,10)])\n>>> a = itertools.chain.from_iterable(x)\n>>> list(a)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nIf that's not available on your version (apparently, it's new in 2.6), you can just do it manually:\n>>> x = iter([ x... | [
10,
3
] | [] | [] | [
"iterator",
"lazy_evaluation",
"python"
] | stackoverflow_0004302201_iterator_lazy_evaluation_python.txt |
Q:
Calling gcc from python script gives me 'Undefined symbols: "_main"
I am trying to write a code generator script in Python, that generates a C-source file, compiles it and runs it. However, I am having trouble calling gcc from my script.
A simple hello world example:
import subprocess
basename = "CodeGenTest"; ... | Calling gcc from python script gives me 'Undefined symbols: "_main" | I am trying to write a code generator script in Python, that generates a C-source file, compiles it and runs it. However, I am having trouble calling gcc from my script.
A simple hello world example:
import subprocess
basename = "CodeGenTest";
execname = basename;
srcname = basename + ".c";
codeList = [];
c... | [
"Change this\noutfile.close;\n\nto this:\noutfile.close()\n\nYou're not actually closing the file, so Python isn't flushing its buffers, so all that's in the source file is an empty file. When gcc compiles an empty file, it complains that there's no main function to serve as the program's entry point.\nI'd also su... | [
6,
1,
1
] | [] | [] | [
"c",
"code_generation",
"gcc",
"python"
] | stackoverflow_0004293297_c_code_generation_gcc_python.txt |
Q:
searching for a foreign object via manytomanyfield
Hay i have a model
def Friends(models.Model):
user = models.ManyToManyField(User)
def User(models.Model):
and i can add "users" to the "friend" model by using
friend = Friends.objects.get(pk=1)
user = User.objects.get(pk=2)
friend.add(user)
However, how can... | searching for a foreign object via manytomanyfield | Hay i have a model
def Friends(models.Model):
user = models.ManyToManyField(User)
def User(models.Model):
and i can add "users" to the "friend" model by using
friend = Friends.objects.get(pk=1)
user = User.objects.get(pk=2)
friend.add(user)
However, how can i check to see if the Friend object has a certain User?... | [
"If you just want to delete the user if it's present, but don't actually care whether it exists or not, you can just do this:\nfriend.users.filter(pk=user.pk).delete()\n\n"
] | [
1
] | [] | [] | [
"django",
"manytomanyfield",
"python",
"search"
] | stackoverflow_0004303086_django_manytomanyfield_python_search.txt |
Q:
Create an object before calling the save method
I want to create an object in Django before calling the save method. This object will be created from a ForeignKey Value, I've changed the foreignkey field to look like an input field in order to write a value instead of selecting it.
I have 2 classes in 2 different ... | Create an object before calling the save method | I want to create an object in Django before calling the save method. This object will be created from a ForeignKey Value, I've changed the foreignkey field to look like an input field in order to write a value instead of selecting it.
I have 2 classes in 2 different model files
class Category(models.Model):
title =... | [
"The save is performed after the form validation, you can make the category obj creation during the validation.\nHave a look at the form fields' clean methods that you can override on django docs http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other\n",
... | [
1,
1,
-1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004293290_django_django_models_python.txt |
Q:
How to get MacVim to recognize python_fn.vim?
I downloaded python_fn.vim from http://www.vim.org/scripts/script.php?script_id=30
The instructions say: "Save this file to $VIMFILES/ftplugin/python.vim. You can have multiple
" python ftplugins by creating $VIMFILES/ftplugin/python and saving your
" ftplugins in that... | How to get MacVim to recognize python_fn.vim? | I downloaded python_fn.vim from http://www.vim.org/scripts/script.php?script_id=30
The instructions say: "Save this file to $VIMFILES/ftplugin/python.vim. You can have multiple
" python ftplugins by creating $VIMFILES/ftplugin/python and saving your
" ftplugins in that directory."
So would I put it into ~/.vimfiles/ftp... | [
"Never used it, but I'd suggest putting it at ~/.vim/ftplugin/python/python_fn.vim and see if it works. This will allow you to have multiple python ftplugins.\nNote that $VIMFILES is not ~/.vimfiles.\n"
] | [
1
] | [] | [] | [
"macvim",
"python",
"vim"
] | stackoverflow_0004300901_macvim_python_vim.txt |
Q:
Most efficient way to extract PyTables table with stored colnames as variable names
The following code provides my needed functionality; but, takes a bit more than 10 seconds for a table that includes 200 variables with 64000 rows. Is there a more efficient way to create a variable namespace that matches the colum... | Most efficient way to extract PyTables table with stored colnames as variable names | The following code provides my needed functionality; but, takes a bit more than 10 seconds for a table that includes 200 variables with 64000 rows. Is there a more efficient way to create a variable namespace that matches the column names?
strExec = "a = table[:]"
for colobj in table.description._f_walk(type="Col"): ... | [
"As suggested by unutbu, the table copy a=table[:] is the time consumer. The code suggested does otherwise provide access to the tablename variables without a prefix. It's acknowledged that using this method of simplifying the variable namespace is questionable as it may not lend itself to self-evident code.\n"
] | [
1
] | [] | [] | [
"exec",
"pytables",
"python"
] | stackoverflow_0003762580_exec_pytables_python.txt |
Q:
How can i access the current user outside a request in django
I'm working on a medium sized project in django and i want to be able to access the current user from within my query manager. I need to be able to design a custom manager to limit the results and querysets so that the current user only get's informati... | How can i access the current user outside a request in django | I'm working on a medium sized project in django and i want to be able to access the current user from within my query manager. I need to be able to design a custom manager to limit the results and querysets so that the current user only get's information related to him/her.
I've received a few suggestions, I've also s... | [
"you can store the user object in the session object and get it out when needed\nrefer to how-to-lookup-django-session-for-a-particular-user\n",
"There is no sane way to get the user outside of the request. If the current user matters then pass it to any functions that need it.\n"
] | [
4,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004303897_django_python.txt |
Q:
Python loop (insert items in a list at dermined places)
I have this code:
number = 2
size = 5
list_b = [("b","b","b")]
list_a = [("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a"... | Python loop (insert items in a list at dermined places) | I have this code:
number = 2
size = 5
list_b = [("b","b","b")]
list_a = [("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a","a"),("a","a",... | [
"For the sake of the argument, I'll call the ('a', 'a', 'a') => a and ('b', 'b', 'b') => b.\nnumber=2\nsize=5\nlist_a=[\"a\"]*20\nlist_b=[\"b\"]\n\nworkfor=len(list_a)+(len(list_a)/size)*number*len(list_b)\ni=0\nwhile i<workfor:\n i+=size\n for times in range(number):\n for elem in list_b:\n ... | [
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004299606_python.txt |
Q:
Django: Linking a class to another class with foreign key when created by form
I'll try to give as much info as I can without giving more than I need.
I have a class 'Book' which, among other fields, is linked to another class 'User', like so:
from users.models import User
class Book(models.Model):
title = mo... | Django: Linking a class to another class with foreign key when created by form | I'll try to give as much info as I can without giving more than I need.
I have a class 'Book' which, among other fields, is linked to another class 'User', like so:
from users.models import User
class Book(models.Model):
title = models.CharField(max_length=150)
owner = models.ForeignKey('users.User')
This... | [
"You need to set the user on the book object that is created by saving the form, not on the form itself. The code should be:\n if form.is_valid():\n book = form.save(commit=False)\n book.owner = request.user\n book.save()\n\nDoing form.save(commit=False) returns an unsaved book instance, whi... | [
1
] | [] | [] | [
"class",
"django",
"foreign_keys",
"python"
] | stackoverflow_0004304545_class_django_foreign_keys_python.txt |
Q:
Python - which is the better way of calling superclass' method?
All the while I have been using:
SuperClass.__init__(self, *args, **kwargs)
My reason is that this shows explicitly which superclass is used, especially in the case of multiple inheritance.
However, other codes I came across use
super(MyClass, self).... | Python - which is the better way of calling superclass' method? | All the while I have been using:
SuperClass.__init__(self, *args, **kwargs)
My reason is that this shows explicitly which superclass is used, especially in the case of multiple inheritance.
However, other codes I came across use
super(MyClass, self).__init__(*args, **kwargs)
instead.
This could become ambigious when ... | [
"The reason that super is prefereable for modern (new style) classes is that it allows cooperative multiple inheritance. Here's an example. \n>>> class Foo(object):\n... def display(self):\n... print \"In Foo\"\n... \n>>> class Foo2(Foo):\n... def display(self):\n... print \"In Foo2\"\n... ... | [
21,
6,
3
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0004300738_class_oop_python.txt |
Q:
Currency Conversion in django
I have a quick question, more theory then actual code. I am building a small program that will interact with activeCollab. Anyways, I want to store the value of a quote in canadian dollars but I want to also be able to view it as USD as well. My question is, should I create a field... | Currency Conversion in django | I have a quick question, more theory then actual code. I am building a small program that will interact with activeCollab. Anyways, I want to store the value of a quote in canadian dollars but I want to also be able to view it as USD as well. My question is, should I create a field to store the american price or sho... | [
"As the currency rates change, you should either do it via javascript or (I would recommend) doing it in your view function. Storing it in a database would not make much sense, as the conversion rates change from day to day, and every time they changed, you would have to update the values in the database. If data i... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004304899_django_django_models_python.txt |
Q:
search form with django+python
I have just started to do a website with django + python and I want to implement a search form to be able to search on all my database objects. What I want is; when I write for an example S I want the search field to display all my objects that starts with the letter S in a list, jus... | search form with django+python | I have just started to do a website with django + python and I want to implement a search form to be able to search on all my database objects. What I want is; when I write for an example S I want the search field to display all my objects that starts with the letter S in a list, just like the Tags field below on this ... | [
"For a decent django search implementation, I would recommend looking at djapian. However, for what you are doing, I would recommend a query using the ISTARTSWITH parameter. Consider the following:\nviews.py\ndef search(req):\n if req.GET:\n search_term = req.GET['term']\n results = ModelToSearch.o... | [
6
] | [] | [] | [
"django",
"python",
"search"
] | stackoverflow_0004304837_django_python_search.txt |
Q:
Django - Reading Excel File
User will upload the Excel file from client machine
Retrieve all the available sheets and need to show in the drop down list
User has to choose the specific sheet
Need to send an email for each available row in that particular sheet.
I just explored openpyxl and planning to use the sa... | Django - Reading Excel File |
User will upload the Excel file from client machine
Retrieve all the available sheets and need to show in the drop down list
User has to choose the specific sheet
Need to send an email for each available row in that particular sheet.
I just explored openpyxl and planning to use the same. I believe that it may consum... | [
"Your lucky there is a website dedicated to your plight \nhttp://www.python-excel.org/\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004305119_django_python.txt |
Q:
Django: Changing a field type in a model form and then applying it to the model class
I have a class Book:
from django.db import models
from users.models import User
class Book(models.Model):
title = models.CharField(max_length=150)
authors = models.ManyToManyField("Author")
which links to the Author cla... | Django: Changing a field type in a model form and then applying it to the model class | I have a class Book:
from django.db import models
from users.models import User
class Book(models.Model):
title = models.CharField(max_length=150)
authors = models.ManyToManyField("Author")
which links to the Author class:
class Author(models.Model):
name = models.CharField(max_length=150)
birthday = ... | [
"To stop django automaticly creating the <select> form entry, remove the 'authors' from the fields list:\nclass BookForm(forms.ModelForm):\n authors = CharField()\n class Meta:\n model = Book\n fields = [\"title\"]\n\nDjango was overriding the authors entry that you created with the one it autom... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004305234_django_django_forms_django_models_python.txt |
Q:
PHP and Python interfacing
I have a Python application (command line tool running on a machine M1) that has input I1 and output O2. Also, I have a PHP application (website running on a machine M2) that feeds the Python application with input I1 and expects to read the output O1. My question is what's the best appr... | PHP and Python interfacing | I have a Python application (command line tool running on a machine M1) that has input I1 and output O2. Also, I have a PHP application (website running on a machine M2) that feeds the Python application with input I1 and expects to read the output O1. My question is what's the best approach to solve this problem? (the... | [
"Like others above, I'd do it by implementing a web service rather than fiddling with SSH. You're right that the SSH solution is inelegant.\nThe obvious answer for what to build your Python web application on top of: Django. If you want to use something lighter, look at a microframework like Flask.\nFor data interc... | [
1,
0,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004305070_php_python.txt |
Q:
No speed gains from Cython
I am trying to define a function that contains an inner loop for simulating an integral.
The problem is speed. Evaluating the function once can take up to 30 seconds on my machine. Since my ultimate goal is to minimize this function, some extra speed would be nice.
As such, I have tried ... | No speed gains from Cython | I am trying to define a function that contains an inner loop for simulating an integral.
The problem is speed. Evaluating the function once can take up to 30 seconds on my machine. Since my ultimate goal is to minimize this function, some extra speed would be nice.
As such, I have tried to get Cython to work, but I mus... | [
"Cython can produce an html file to help with this:\ncython -a MODULE.py\n\nThis shows each line of source code colored white through various shades of yellow. The darker the yellow color, the more dynamic Python behaviour is still being performed on that line. For each line that contains some yellow, you need to a... | [
34,
17,
11,
6,
1,
1
] | [
"The \"fundamental mistake\" is that you expect good performance in long loops from Python. It's an interpreted language, and switching between implementations and ctyping does nothing to this. There are a few numeric Python libraries for fast computing, mosly written in C. For example, if you already use numpy for... | [
-7
] | [
"cython",
"numpy",
"optimization",
"python"
] | stackoverflow_0004264229_cython_numpy_optimization_python.txt |
Q:
Twisted multiple protocols
I am looking to learn twisted for a project I am working on. The project would require the server to respond to HTTP requests as well as other protocols over a TCP connection. Is twisted capable of handling multiple protocols at the same time? I want to use Twisted Web to help with the H... | Twisted multiple protocols | I am looking to learn twisted for a project I am working on. The project would require the server to respond to HTTP requests as well as other protocols over a TCP connection. Is twisted capable of handling multiple protocols at the same time? I want to use Twisted Web to help with the HTTP, but at the same time need t... | [
"Definitely, yes. Twisted is a really good choice for this kind of needs, when multiple protocols need to work together.\nLook at this question for great learning references.\n"
] | [
3
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0004306256_networking_python_twisted.txt |
Q:
python ssh connection problem
I tried this code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.222', username='sshuser', password='pass')
stdin, stdout, stderr = ssh.exec_command("pwd")
stdout.readlines()
and the ssh connectio... | python ssh connection problem | I tried this code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.222', username='sshuser', password='pass')
stdin, stdout, stderr = ssh.exec_command("pwd")
stdout.readlines()
and the ssh connection works, but as soon as I use:
std... | [
"try:\n stdin, stdout, stderr = ssh.exec_command(\"pwd\")\nexcept SSHException:\n ssh.close()\n\nThat will keep it from crashing like that, but won't fix your problem. Make sure you can connect with a regular ssh client and run pwd. Then make sure your login credentials are correct.\n"
] | [
0
] | [] | [] | [
"python",
"ssh"
] | stackoverflow_0004304362_python_ssh.txt |
Q:
Python method/function arguments starting with asterisk and dual asterisk
I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly.
Ex:
def method(self,... | Python method/function arguments starting with asterisk and dual asterisk | I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly.
Ex:
def method(self, *links, **locks):
#some foo
#some bar
return
I know i could have ... | [
"The *args and **keywordargs forms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function like this:\ndef printlist(*args):\n for x in args:\n print(x)\n\nI could call it like this:\nprintlist(1, 2, 3, 4, 5) # or as many more arguments as I'd like\n\nF... | [
125
] | [] | [] | [
"python"
] | stackoverflow_0004306574_python.txt |
Q:
App Engine, Cross reference between two entities
i will like to have two types of entities referring to each other.
but python dont know about name of second entity class in the body of first yet.
so how shall i code.
class Business(db.Model):
bus_contact_info_ = db.ReferenceProperty(reference_class=Business_Inf... | App Engine, Cross reference between two entities | i will like to have two types of entities referring to each other.
but python dont know about name of second entity class in the body of first yet.
so how shall i code.
class Business(db.Model):
bus_contact_info_ = db.ReferenceProperty(reference_class=Business_Info)
class Business_Info (db.Model):
my_business_ = ... | [
"Queries are a little slower, and so they do use a bit more resources. ReferenceProperty does not require reference_class. So you could always define Business like: \nclass Business(db.Model):\n bus_contact_info_ = db.ReferenceProperty()\n\nThere may also be better options for your datastructure too. Check out ... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004306547_google_app_engine_google_cloud_datastore_python.txt |
Q:
List of minimal pairs from a pair of lists
Given two lists of integers, generate the shortest list of pairs where every value in both lists is present. The first of each pair must be a value from the first list, and the second of each pair must be a value from the second list. The first of each pair must be less t... | List of minimal pairs from a pair of lists | Given two lists of integers, generate the shortest list of pairs where every value in both lists is present. The first of each pair must be a value from the first list, and the second of each pair must be a value from the second list. The first of each pair must be less than the second of the pair.
A simple zip will no... | [
"I had many ideas to solve this (see edit history ;-/) but none of them quite worked out or did it in linear time. It took me a while to see it, but I had a similar problem before so I really wanted to figure this out ;-)\nAnyways, in the end the solution came when I gave up on doing it directly and started drawing... | [
1,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004304976_algorithm_python.txt |
Q:
Python subclass tuple object with ability to reinstantiate self internally
I understand the concept of mutable v. immutable objects in Python, no problem. While any immutable object's intrinsic value cannot be modified directly, any instance of an immutable object can be reinstantiated with different values. What ... | Python subclass tuple object with ability to reinstantiate self internally | I understand the concept of mutable v. immutable objects in Python, no problem. While any immutable object's intrinsic value cannot be modified directly, any instance of an immutable object can be reinstantiated with different values. What I would like to do is build an internal function on a subclass of tuple that can... | [
"If you want a mutable tuple, use a list.\nedit:\ntry this\nclass FrankenList(object):\n def __init__(self, init=None):\n self.__data = init or []\n\n def __getitem__(self, key):\n return self.__data[key]\n\n def __repr__(self):\n return repr(self.__data)\n\n def __str__(self):\n ... | [
2,
1
] | [] | [] | [
"mutable",
"python",
"tuples"
] | stackoverflow_0004306557_mutable_python_tuples.txt |
Q:
Catching PyGTK RuntimeWarning on gtk.Builder.connect_signals
gtk.Builder.connect_signals() issues a RuntimeWarning when a signal handler is not present:
__init__.py:16: RuntimeWarning: missing handler 'on_window_destroy'
self.builder.connect_signals(self)
How do I keep it from issuing the warning and handle it ... | Catching PyGTK RuntimeWarning on gtk.Builder.connect_signals | gtk.Builder.connect_signals() issues a RuntimeWarning when a signal handler is not present:
__init__.py:16: RuntimeWarning: missing handler 'on_window_destroy'
self.builder.connect_signals(self)
How do I keep it from issuing the warning and handle it myself?
I'd like the warning to not be printed (without requiring ... | [
"You could use the warnings module.\nHowever, in this case I think it would be easier to check the return value of connect_signals. From the documentation:\n\nAlso, if there is at least one such missing handler, connect_signals will return a list of their names, else return value is None.\n\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004306760_gtk_pygtk_python.txt |
Q:
How does Python keep track of modules installed with eggs?
If I have a module, foo, in Lib/site-packages, I can just import foo and it will work. However, when I install stuff from eggs, I get something like blah-4.0.1-py2.7-win32.egg as a folder, with the module contents inside, yet I still only need do import fo... | How does Python keep track of modules installed with eggs? | If I have a module, foo, in Lib/site-packages, I can just import foo and it will work. However, when I install stuff from eggs, I get something like blah-4.0.1-py2.7-win32.egg as a folder, with the module contents inside, yet I still only need do import foo, not anything more complicated. How does Python keep track of ... | [
"If you use the easy_install script provided by setuptools (or the Distribute fork of it) to install packages as eggs, you will see that, by default, it creates a file named easy-install.pth in the site-packages directory of your Python installation. Path configuration files are a standard feature of Python:\n\nA ... | [
19,
3
] | [] | [] | [
"easy_install",
"egg",
"installation",
"module",
"python"
] | stackoverflow_0004305610_easy_install_egg_installation_module_python.txt |
Q:
Python libxml2 XPath/Namespace Help
I'm trying to learn how to do XPath queries from Python using this sample XML file: http://pastie.org/1333021 I just added a namespace to it because my actual application uses it.
Basically, I want to execute a top level query that returns a subset of nodes and then query the su... | Python libxml2 XPath/Namespace Help | I'm trying to learn how to do XPath queries from Python using this sample XML file: http://pastie.org/1333021 I just added a namespace to it because my actual application uses it.
Basically, I want to execute a top level query that returns a subset of nodes and then query the subset (on a much larger scale than this ex... | [
"I don't normally use libxml2, I much prefer lxml.etree.\nHad a play around. The xpathEval method on your node creates a new context each time, apparently without the namespace you registered.\nYou can reset your context to different locations like this:\n>>> import libxml2\n>>> from urllib2 import urlopen\n>>> dat... | [
5
] | [] | [] | [
"libxml2",
"python"
] | stackoverflow_0004306856_libxml2_python.txt |
Q:
Encode keys of dictionaries inside a list from unicode to ascii
I have sample response with friends list from facebook:
[{u'uid': 513351886, u'name': u'Mohammed Hossein', u'pic_small': u'http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs643.snc3/27383_513351886_4933_t.jpg'},
{u'uid': 516583220, u'name': u'Sim Sal... | Encode keys of dictionaries inside a list from unicode to ascii | I have sample response with friends list from facebook:
[{u'uid': 513351886, u'name': u'Mohammed Hossein', u'pic_small': u'http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs643.snc3/27383_513351886_4933_t.jpg'},
{u'uid': 516583220, u'name': u'Sim Salabim', u'pic_small': u'http://profile.ak.fbcdn.net/hprofile-ak-snc4/h... | [
"First: do you really need to do this? The strings are in Unicode for a reason: you simply can't represent everything in plain ASCII that you can in Unicode. This probably won't be a problem for your dictionary keys 'uid', 'name' and 'pic_small'; but it probably won't be a problem to leave them as Unicode, either. ... | [
11,
6
] | [] | [] | [
"dictionary",
"django",
"encoding",
"python",
"unicode"
] | stackoverflow_0004303324_dictionary_django_encoding_python_unicode.txt |
Q:
Class decorators in Python 2.5?
Is there a way I can make class decorators work on Google App Engine, which is limited to Python 2.5?
Or let me rephrase that: is it possible to alter the behavior of Python's parser from the same process that it is already executing? Example:
good.py:
alter_python_parser()
import b... | Class decorators in Python 2.5? | Is there a way I can make class decorators work on Google App Engine, which is limited to Python 2.5?
Or let me rephrase that: is it possible to alter the behavior of Python's parser from the same process that it is already executing? Example:
good.py:
alter_python_parser()
import bad
bad.py:
@decorated
class Foo(obje... | [
"Decorators are just syntactic sugar. Just change instances of decorator usage, that is, \n@decorated\nclass Foo(object): pass\n\nbecomes\nclass Foo(object): pass\nFoo = decorated(Foo)\n\nYou can't, realistically, change the parser.\nThough, you could automate the above process using the ast module (in a new versio... | [
9
] | [] | [] | [
"google_app_engine",
"python",
"python_2.5"
] | stackoverflow_0004307419_google_app_engine_python_python_2.5.txt |
Q:
Would IronPython allow me to use Python in a C# Project without adding new requirements for deployment?
I have looked at the IronPython website and done various Google searches as well as searching answers on SO and am still not sure about this.
I want to use Python within a C# ASP.NET MVC project such that once t... | Would IronPython allow me to use Python in a C# Project without adding new requirements for deployment? | I have looked at the IronPython website and done various Google searches as well as searching answers on SO and am still not sure about this.
I want to use Python within a C# ASP.NET MVC project such that once the project is deployed I don't need to have Python running on the server that is hosting the application.
I t... | [
"You don't need to have a Python interpreter installed. All you need is the DLR and the IronPython assemblies deployed with your site. Then you could host IronPython inside your application and execute Python scripts and even retrieve the results back in C#.\nAnd here's an example of hosting the DLR in a console ap... | [
5
] | [] | [] | [
"asp.net_mvc",
"c#",
"ironpython",
"python"
] | stackoverflow_0004307475_asp.net_mvc_c#_ironpython_python.txt |
Q:
Is it possible to reset locale to the portable locale?
According to the Python documentation:
"a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale.
After having set the locale with setlocale(LC_ALL, '') is it possible to reset the locale back to the "portable" state? I work o... | Is it possible to reset locale to the portable locale? | According to the Python documentation:
"a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale.
After having set the locale with setlocale(LC_ALL, '') is it possible to reset the locale back to the "portable" state? I work on a library which includes some misbehaved components which ... | [
"You could try: locale.setlocale(locale.LC_ALL, loc).\n>>> locale.getlocale(locale.LC_ALL)\n(None, None)\n>>> locale.setlocale(locale.LC_ALL, \"\") \n'en_US.utf8'\n>>> locale.getlocale(locale.LC_ALL)\n('en_US', 'UTF8')\n>>> locale.setlocale(locale.LC_ALL, \"C\") ... | [
4,
2
] | [] | [] | [
"locale",
"python",
"python_2.4"
] | stackoverflow_0004305410_locale_python_python_2.4.txt |
Q:
Override all default resources / responses from Twisted.web
For a super-basic http twisted front-end.
How can I make sure no html is ever written back unless I tell it to.
So, I have my /zoo url below.
For any tracebacks, or 'No Such Resource' responses, I want to just drop the connection or return an empty respon... | Override all default resources / responses from Twisted.web | For a super-basic http twisted front-end.
How can I make sure no html is ever written back unless I tell it to.
So, I have my /zoo url below.
For any tracebacks, or 'No Such Resource' responses, I want to just drop the connection or return an empty response.
I guess it's a super-simple one but can't figure it out :)
I ... | [
"\nSome basics first\n\nThe way twisted.web works is \nThere is class called Site which is a HTTP factory. \nThis is called for every request. In fact, a function called getResourceFor is called to obtain the appropriate resource that will serve this request. \nThis Site class is initialized with root resource. And... | [
2
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0004307294_python_twisted_twisted.web.txt |
Q:
Google App Engine - Datastore get_or_insert key_name confusion
I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:
class Person(db.model)
name = db.StringProperty(required=True)
Assume that no two people can have the same name. Say I want to get or insert a ... | Google App Engine - Datastore get_or_insert key_name confusion | I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:
class Person(db.model)
name = db.StringProperty(required=True)
Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement lo... | [
"The possibly confusing thing here is that the key doesn't show up directly in your model declaration, so that name = db.StringProperty bit in your example isn't needed. get_or_insert takes the keyname as its first (required) argument, so you're looking for code like:\nperson = Person.get_or_insert('Peter')\n# othe... | [
5,
1
] | [] | [] | [
"database",
"google_app_engine",
"key",
"python"
] | stackoverflow_0004308002_database_google_app_engine_key_python.txt |
Q:
Python2.6+ code parser
Is there a parser that:
is able to parse Python2.6+ code, and
can be run in Python2.5 (python-only, no C extensions allowed)?
NOTE: This is somewhat related to my previous quostion about class decorators.
A:
Yes, lib2to3 can, all you need to do is to provide it with the right Grammar fil... | Python2.6+ code parser | Is there a parser that:
is able to parse Python2.6+ code, and
can be run in Python2.5 (python-only, no C extensions allowed)?
NOTE: This is somewhat related to my previous quostion about class decorators.
| [
"Yes, lib2to3 can, all you need to do is to provide it with the right Grammar file (get the source code for the Python you want and copy Grammar/Grammar).\n"
] | [
2
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0004308120_python_python_2.5.txt |
Q:
How to organize the directory used for a distributable Python module?
I'm creating a Python module. My question is how can I organize the distribution such that it has a directory structure similar to most of the standard Python modules. Is there anything similar to MakeFile in Python which has setup.py file name?... | How to organize the directory used for a distributable Python module? | I'm creating a Python module. My question is how can I organize the distribution such that it has a directory structure similar to most of the standard Python modules. Is there anything similar to MakeFile in Python which has setup.py file name?
Directory Structure:
pymodule_x-y.tar.gz/
+ pymodule/
... | [
"You have several options, including distributing egg files, tarballs, etc. A great resource on distributing Python packages is The Hitchhiker's Guide to Packaging (still under development, but good nonetheless).\n"
] | [
7
] | [] | [] | [
"module",
"python"
] | stackoverflow_0004308301_module_python.txt |
Q:
"Splitting" the output of a RLE (groupby) depending on a defined value ( the "character" to split the RLE on )
Consider the "string" ( treat it as an array of digits )
0 0 1 8 8 8 1 0
The RLE ( "groupby" ) is:
[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
We then enrich the above RLE with the sum of the run lengths of ... | "Splitting" the output of a RLE (groupby) depending on a defined value ( the "character" to split the RLE on ) | Consider the "string" ( treat it as an array of digits )
0 0 1 8 8 8 1 0
The RLE ( "groupby" ) is:
[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
We then enrich the above RLE with the sum of the run lengths of the previous elements.
Hence, the enriched version of the above becomes:
[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)),... | [
"import itertools\n\ndef get_rle(list_of_digits, split_on=None):\n count = 0\n rle = []\n active_group = []\n rle_app = rle.append\n for item, group in itertools.groupby(list_of_digits):\n L = len(list(group))\n if item == split_on:\n rle_app(active_group)\n active... | [
1,
1
] | [] | [] | [
"arrays",
"functional_programming",
"list_comprehension",
"python",
"run_length_encoding"
] | stackoverflow_0004308528_arrays_functional_programming_list_comprehension_python_run_length_encoding.txt |
Q:
Function arithmetic library for python
I'm searching for a library that will let me manipulate functions with the standard operators (*, -, *, /, etc.).
Lets suppose you have a function f(x) = x ** 2 and g(x) = x + 2. I'd like to be able to write f * g and get a new functor that is essentialy x ** 2 * (x + 2) or f... | Function arithmetic library for python | I'm searching for a library that will let me manipulate functions with the standard operators (*, -, *, /, etc.).
Lets suppose you have a function f(x) = x ** 2 and g(x) = x + 2. I'd like to be able to write f * g and get a new functor that is essentialy x ** 2 * (x + 2) or f(g) and get (x + 2) ** 2.
I know this is not... | [
"Sympy should do what you want.\n",
"I don't completely understand what you're after, but does the operator module (in the standard library) help at all? It defines functions for all the standard arithmetic operators.\n"
] | [
5,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0004308790_function_python.txt |
Q:
Give me some awesome Web2py Tip & Tricks which makes you more productive
I have been working with web2py following its official web2py book and got to learn too many things. But a book never teaches a productive workflow. I would like to know what workflow you people use to increase you productivity and understand... | Give me some awesome Web2py Tip & Tricks which makes you more productive | I have been working with web2py following its official web2py book and got to learn too many things. But a book never teaches a productive workflow. I would like to know what workflow you people use to increase you productivity and understanding of the framework as a whole.
Ex:
I often use Web2py interactive shell to ... | [
"I use Komodo Edit for development and Google App Engine for hosting.\nTo better understand web2py have a look at the files in gluon/ - for example tools.py is fairly straightforward.\n"
] | [
3
] | [] | [] | [
"python",
"web2py",
"workflow"
] | stackoverflow_0004297064_python_web2py_workflow.txt |
Q:
Sphinx: Putting a code segment at the first line of an unordered list item
I'm using Sphinx to manage my project's documentation.
I have an unordered list, and I want the first line of every item to be a code segment. (Not inline, a paragraph.)
How can I do that?
A:
Looking at my own documentation I found a simi... | Sphinx: Putting a code segment at the first line of an unordered list item | I'm using Sphinx to manage my project's documentation.
I have an unordered list, and I want the first line of every item to be a code segment. (Not inline, a paragraph.)
How can I do that?
| [
"Looking at my own documentation I found a similar scenario, however I can't guarantee that it will work with the documentation as the first text in the list:\n#. **Defining the Model Class**\n\n All models must inherit from |LrbBaseModel| either directly or\n indirectly and have the |LrbModelInit| decorator... | [
2
] | [] | [] | [
"python",
"python_sphinx",
"restructuredtext"
] | stackoverflow_0004308619_python_python_sphinx_restructuredtext.txt |
Q:
problem with scons in windows
I tried to build an executable for a python script using scons, which is failing with the following trace:
C:\WORKAREA\study>C:\Python26\Scripts\scons
scons: Reading SConscript files ...
scons: warning: No installed VCs
File "C:\WORKAREA\study\SConstruct", line 1, in <module>
scons:... | problem with scons in windows | I tried to build an executable for a python script using scons, which is failing with the following trace:
C:\WORKAREA\study>C:\Python26\Scripts\scons
scons: Reading SConscript files ...
scons: warning: No installed VCs
File "C:\WORKAREA\study\SConstruct", line 1, in <module>
scons: warning: No version of Visual Stud... | [
"You're trying to build a .exe file from a .py file right? In that case, you don't need the VC++ compiler, you will need a tool like py2exe. And if you want to use SCons as a build system, you will need to create a SCons builder for py2exe.exe. Something along the lines as:\nenv = Environment()\n\ndef py2exe_action... | [
3
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0004304559_python_scons.txt |
Q:
Creating class instances
Could someone please explain to me how to create class instances from a list (or a string that might be fetched from excel). I always seem to run into this problem. I want to create many instances of classes and then save them in a shelve later.
This sample code doesn't work, but illustrat... | Creating class instances | Could someone please explain to me how to create class instances from a list (or a string that might be fetched from excel). I always seem to run into this problem. I want to create many instances of classes and then save them in a shelve later.
This sample code doesn't work, but illustrates the approach I'm trying.
cl... | [
"Few issues in your code includes naming of variables. It can confuse you.\nclass test:\n # I guess you want to provide the name to initialize the object attribute\n def __init__(self, name): \n # self.name is the attribute where the name is stored.\n # I prefer it to self.A \n self.nam... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004309502_python.txt |
Q:
String manipulation of type String substitution in mathematical expression
Imagine something like
exp(49/200)+(x-49/200)
I want to pass as argument of the function "roundn" whatever operation that is not a addtion or a subtraction
So my expression became
roundn(exp(roundn(49/200, n)), n) + (x - roundn(49/200, n)
... | String manipulation of type String substitution in mathematical expression | Imagine something like
exp(49/200)+(x-49/200)
I want to pass as argument of the function "roundn" whatever operation that is not a addtion or a subtraction
So my expression became
roundn(exp(roundn(49/200, n)), n) + (x - roundn(49/200, n)
Well the expression I want to manipulate is this:
exp(49/200)+exp(49/200)*(x-49... | [
"Maybe you think you want to do this, but you don't really want to do this. New Pythoners usually think they need to round floating point numbers because when evaluated they get unexpected results (like 1.0/10 = 0.100000000000001). Rather than do some goofy string substitution on your expression, I just created a v... | [
6,
2,
1,
0
] | [] | [] | [
"parsing",
"python",
"string",
"string_substitution"
] | stackoverflow_0004254420_parsing_python_string_string_substitution.txt |
Q:
Compile subsection of Jinja2 AST
Can one compile or revert a portion of the Jinja2 AST?
For example, is it possible to call a function or method from jinja2.environment or jinja2.compiler.generate or some equivalent on a list of nodes extracted from within a template?
For example, given a template y.html:
avant-ta... | Compile subsection of Jinja2 AST | Can one compile or revert a portion of the Jinja2 AST?
For example, is it possible to call a function or method from jinja2.environment or jinja2.compiler.generate or some equivalent on a list of nodes extracted from within a template?
For example, given a template y.html:
avant-tag
{% xyz %}
tag content {{ 3 + 5 }}
{%... | [
"Compiling to unicode is not yet possible in the parse() method since you don't have the context available at that point. You can hack around it ofcourse but it would probably not be the best way to go.\nNote that the parse() step is normally only executed once on a html file, after that it will use the parsed byte... | [
1
] | [] | [] | [
"abstract_syntax_tree",
"jinja2",
"python"
] | stackoverflow_0004309266_abstract_syntax_tree_jinja2_python.txt |
Q:
Is there a more agile way to re-factor the following string formating code
I need to format a string as bellow :
print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')
Since the number of cat is a variable, here is what I code.
values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()... | Is there a more agile way to re-factor the following string formating code | I need to format a string as bellow :
print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')
Since the number of cat is a variable, here is what I code.
values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()
for cat in range(house.get_cat_count()):
format = format + '%-' + str(widt... | [
"How about:\nresult = ' ' * 8\nwidth = house.get_width() - 4 # subtract 4 to allow for 'CAT '\nfor i in range(house.get_cat_count()): # or xrange\n result += 'CAT %-*c' % (width, ord('A') + i)\n\nNote the use of * to indicate a variable width specifier, and the %c format specifier for a single character to avoid... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004309672_python.txt |
Q:
How to read a string one letter at a time in python
I need to convert a string inputed by a user into morse code. The way our professor wants us to do this is to read from a morseCode.txt file, seperate the letters from the morseCode into two lists, then convert each letter to morse code (inserting a new line when... | How to read a string one letter at a time in python | I need to convert a string inputed by a user into morse code. The way our professor wants us to do this is to read from a morseCode.txt file, seperate the letters from the morseCode into two lists, then convert each letter to morse code (inserting a new line when there is a space).
I have the beginning. What it does is... | [
"Why not just iterate through the string?\na_string=\"abcd\"\nfor letter in a_string:\n print letter\n\nreturns\na\nb\nc\nd\n\nSo, in pseudo-ish code, I would do this:\nuser_string = raw_input()\nlist_of_output = []\nfor letter in user_string:\n list_of_output.append(morse_code_ify(letter))\n\noutput_string = ... | [
21,
4,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002633942_python.txt |
Q:
Fetching language detection from Google api
I have a CSV with keywords in one column and the number of impressions in a second column.
I'd like to provide the keywords in a url (while looping) and for the Google language api to return what type of language was the keyword in.
I have it working manually. If I enter... | Fetching language detection from Google api | I have a CSV with keywords in one column and the number of impressions in a second column.
I'd like to provide the keywords in a url (while looping) and for the Google language api to return what type of language was the keyword in.
I have it working manually. If I enter (with the correct api key):
http://ajax.googleap... | [
"Try to add referrer, userip as described in the docs:\n\nAn area to pay special attention to\n relates to correctly identifying\n yourself in your requests.\n Applications MUST always include a\n valid and accurate http referer header\n in their requests. In addition, we\n ask, but do not require, that each\... | [
1
] | [] | [] | [
"api",
"python"
] | stackoverflow_0004309599_api_python.txt |
Q:
Evaluate string from user to comma separated words string
Let's say I have a string given by user in the following form:
"single, single, double word, single word, also single"
How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator a... | Evaluate string from user to comma separated words string | Let's say I have a string given by user in the following form:
"single, single, double word, single word, also single"
How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ',', and each single is replaced with %20 ? So... | [
"This does what you ask:\ndef repl(m):\n if m.group(0) == ' ':\n return '%20'\n else:\n return ','\n\nre.sub(',? +', repl, \"single, single, double word, single word, also single\")\n\nHowever, if your goal is to end up with proper URL escaping I'd advise that you actually use a library function desig... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004310122_python_regex.txt |
Q:
Django paging with slicing
I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first. All the examples I've seen with QuerySets will get all the records first like below.
tickets = Ticket.objects.filter(site=site.id)
paginator = Pa... | Django paging with slicing | I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first. All the examples I've seen with QuerySets will get all the records first like below.
tickets = Ticket.objects.filter(site=site.id)
paginator = Paginator(tickets, settings.PAGE_S... | [
"Underlying queries for the QuerySet objects are not executed until you explicitly evaluate them. Explicit evaluation occurs whenever you iterate through them, which includes calling str() or unicode().\nThus, the above code snippet is indeed efficient. The line tickets = Ticket.objects.filter(site=site.id) creates... | [
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004310339_django_django_templates_python.txt |
Q:
How to setup application icon that shows up in Alt-Tab dialog when switching tasks on Windows?
How do I setup icon, for wxpython application on Windows, that shows up in the Alt-Tab dialog when I'm switching between applications?
The application icon in the menu bar and the corner of the running app shows my icon ... | How to setup application icon that shows up in Alt-Tab dialog when switching tasks on Windows? | How do I setup icon, for wxpython application on Windows, that shows up in the Alt-Tab dialog when I'm switching between applications?
The application icon in the menu bar and the corner of the running app shows my icon but when I switch between applications using Alt-Tab I can see the default square with blue outline ... | [
"This works for me:\nself.icon = wx.Icon(fn, wx.BITMAP_TYPE_ICO)\nself.SetIcon(self.icon)\n\nwhere the icon in fn has several resolutions (16, 32, and 48, I think).\nLooks like you at least want to change\n wx.Frame.SetIcon(self,favicon)\n\nto\n self.SetIcon(favicon)\n\nAlso, try removing the 16's from the wx... | [
5
] | [] | [] | [
"icons",
"python",
"windows",
"wxpython"
] | stackoverflow_0004310341_icons_python_windows_wxpython.txt |
Q:
How do I get same result without using enumerate?
I do not need char in this example, but I include it to get my desired results.
charlist = [strval[0:count+1] for count, char in enumerate(strval)]
How do I get the same result without using enumerate?
A:
xrange(len(strval))
A:
If you do not want to use enum... | How do I get same result without using enumerate? | I do not need char in this example, but I include it to get my desired results.
charlist = [strval[0:count+1] for count, char in enumerate(strval)]
How do I get the same result without using enumerate?
| [
"xrange(len(strval))\n\n",
"If you do not want to use enumerate, use range since all you want is count value\n>>> strval = \"abcd\"\n>>> for count, char in enumerate(strval): print count, char\n... \n0 a\n1 b\n2 c\n3 d\n>>> for count in range(len(strval)): print count\n... \n0\n1\n2\n3\n>>>\n\n",
"How about rep... | [
6,
1,
0
] | [] | [] | [
"enumerate",
"for_loop",
"python"
] | stackoverflow_0004310503_enumerate_for_loop_python.txt |
Q:
Pydev Showing Errors for @staticmethod Reimplementation
I have wanted to create a python decorator that performs a particular task, but also does what @staticmethod does. I have accomplished this, but using PyDev, it tells me that the usage is incorrect, because the method does not have the self parameter.
My sim... | Pydev Showing Errors for @staticmethod Reimplementation | I have wanted to create a python decorator that performs a particular task, but also does what @staticmethod does. I have accomplished this, but using PyDev, it tells me that the usage is incorrect, because the method does not have the self parameter.
My simplified implementation is below:
class Service(object):
... | [
"As usual, found it before anybody could answer.\nBut if anybody in the future wants to know:\nWindow > Preferences > Pydev > Editor > Code Analysis > Others\nThis window is self-explanatory.\n"
] | [
1
] | [] | [] | [
"decorator",
"methods",
"python",
"static"
] | stackoverflow_0004310588_decorator_methods_python_static.txt |
Q:
Remove lines from a text file which do not contain a certain string with python
I am trying to form a quotes file of a specific user name in a log file. How do I remove every line that does not contain the specific user name in it? Or how do I write all the lines which contain this user name to a new file?
A:
... | Remove lines from a text file which do not contain a certain string with python | I am trying to form a quotes file of a specific user name in a log file. How do I remove every line that does not contain the specific user name in it? Or how do I write all the lines which contain this user name to a new file?
| [
"with open('input.txt', 'r') as rfp:\n with open('output.txt', 'w') as wfp:\n for line in rfp:\n if ilikethis(line):\n wfp.write(line)\n\n",
"with open(logfile) as f_in:\n lines = [l for l in f_in if username in l]\nwith open(outfile, 'w') as f_out:\n f_out.writelines(lines)\n\nOr if you don... | [
3,
3,
2,
1
] | [] | [] | [
"file",
"file_io",
"python",
"string",
"text"
] | stackoverflow_0004310659_file_file_io_python_string_text.txt |
Q:
How do I convert the time stamps from a PostgreSQL DB into user-time-zone times?
I'm using SQLAlchemy and PostgreSQL here, in a web application.
My SQLA model is defined (roughly) as follows:
class MyModel(Base):
ts_field = Column(DateTime(timezone=True))
# more here, obviously
My web app users have a tim... | How do I convert the time stamps from a PostgreSQL DB into user-time-zone times? | I'm using SQLAlchemy and PostgreSQL here, in a web application.
My SQLA model is defined (roughly) as follows:
class MyModel(Base):
ts_field = Column(DateTime(timezone=True))
# more here, obviously
My web app users have a timezone property whose format I have not yet specified (that's part of this question) th... | [
"OK, when you create a timestamp with timezone (shortcut name timestamptz) pg creates a timestamp, and converts between the current timezone to GMT when storing it.\nWhen you pull it out, you change the timezone setting to whatever you want to change it to some other offset. For example:\n smarlowe=# set timezone=... | [
1,
0
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy",
"timestamp",
"timezone"
] | stackoverflow_0004308812_postgresql_python_sqlalchemy_timestamp_timezone.txt |
Q:
print last '\n' char using print method in python
Imagine I have the following code in file test.py:
for x in range(1,11):
print x
This will print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
However, I want it to print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
Notice the last '\n' ... | print last '\n' char using print method in python | Imagine I have the following code in file test.py:
for x in range(1,11):
print x
This will print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
However, I want it to print:
$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
Notice the last '\n' char, that is missing in the normal case. How do I get ... | [
"Nothing is missing; if there wasn't a newline at the end the last line would look like 10$myuser:\nPerhaps you want:\nfor x in range(1,11):\n print x\nprint\n\n",
"Just put a bare print after the loop.\n",
"That's why I love python3:\nprint(*range(5), sep='\\n',end='\\n\\n')\n\nactually this is ugly:\nfor i i... | [
8,
3,
1
] | [] | [] | [
"newline",
"printing",
"python",
"stdout"
] | stackoverflow_0004310987_newline_printing_python_stdout.txt |
Q:
Using a channel for multiple commands, replys, and interactive commands?
I'm beginning to learn twisted.conch to automate some tasks over SSH.
I tried to modify the sample sshclient.py from http://www.devshed.com/c/a/Python/SSH-with-Twisted/4/ . It runs 1 command after login and prints captured output.
What I wa... | Using a channel for multiple commands, replys, and interactive commands? | I'm beginning to learn twisted.conch to automate some tasks over SSH.
I tried to modify the sample sshclient.py from http://www.devshed.com/c/a/Python/SSH-with-Twisted/4/ . It runs 1 command after login and prints captured output.
What I wanted to do is to run a series commands, and maybe decide what to do based on t... | [
"\nShould I just open multiple channels for multiple commands?\n\nYep. That's how SSH works.\n\nSSHChannel.dataReceived never gets called\n\nThis doesn't sound like what should happen. Perhaps you can include a minimal example which reproduces the behavior.\n"
] | [
2
] | [] | [] | [
"python",
"ssh",
"twisted"
] | stackoverflow_0004310513_python_ssh_twisted.txt |
Q:
django remove source files and generate pyc files
I want to remove all .py files in my django project.But pyc files are not generated as yet..
What is the settings that needs to be changed to generate the .pyc files
A:
compileall can be used to compile all Python scripts in the project directory.
python -m compi... | django remove source files and generate pyc files | I want to remove all .py files in my django project.But pyc files are not generated as yet..
What is the settings that needs to be changed to generate the .pyc files
| [
"compileall can be used to compile all Python scripts in the project directory.\npython -m compileall path/to/project\n\n"
] | [
10
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004311265_django_django_models_django_templates_django_views_python.txt |
Q:
Python subprocess Popen parameter difference
What's the difference between
subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
and
subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not ... | Python subprocess Popen parameter difference | What's the difference between
subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
and
subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not hang, but it's significantly slower.
The second is... | [
"The first one is actually only running cat (because of the way that the command is parsed if you use shell = True), and thus hanging because it's waiting for input. The second one is running cat /path/to/file. You can see this by doing:\n>>> subprocess.Popen(['ls', '-l'])\n<subprocess.Popen object at 0x10048bdd0... | [
4,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004311316_python_subprocess.txt |
Q:
python regex of a date in some text
How can I find as many date patterns as possible from a text file by python? The date pattern is defined as:
dd mmm yyyy
^ ^
| |
+---+--- spaces
where:
dd is a two digit number
mmm is three-character English month name (e.g. Jan, Mar, Dec)
yyyy is four digit year
the... | python regex of a date in some text | How can I find as many date patterns as possible from a text file by python? The date pattern is defined as:
dd mmm yyyy
^ ^
| |
+---+--- spaces
where:
dd is a two digit number
mmm is three-character English month name (e.g. Jan, Mar, Dec)
yyyy is four digit year
there are two spaces as separators
Thanks!
| [
"Here's a way to find all dates matching your pattern\nre.findall(r'\\d\\d\\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s\\d{4}', text)\n\nBut after WilhelmTell's comment on your question, I'm also wondering whether this it what you were really asking for...\n",
"Use the calendar module to give you a li... | [
11,
9,
5,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002770040_python_regex.txt |
Q:
mod_wsgi WSGI script for non-frameworked Python web development
Most guides I saw for creating the WSGI file for use with mod_wsgi either sets it up for Django or Pylons. However, I would like to create the wsgi file without setting it up for any particular framework. How do I do this. The following is a code from... | mod_wsgi WSGI script for non-frameworked Python web development | Most guides I saw for creating the WSGI file for use with mod_wsgi either sets it up for Django or Pylons. However, I would like to create the wsgi file without setting it up for any particular framework. How do I do this. The following is a code from the wsgi script for use with Django:
import os, sys
sys.path.append(... | [
"For the simple wsgi application in PEP 333:\ndef simple_app(environ, start_response):\n status = '200 OK'\n response_headers = [('Content-type', 'text/plain')]\n start_response(status, response_headers)\n return ['Hello world!\\n']\n\napplication = simple_app\n\nIn other words, you don't have to do any... | [
3
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0004311590_apache_django_mod_wsgi_python_virtualenv.txt |
Q:
AMQP implementations with Celery
I wanted to get your opinions on the merits of different AMQP implementations to be used with celery. I am looking particularly at message prioritization and job queue sizes.
What are your thoughts?
A:
After reading some docs and trying out a few options, I have found that Rab... | AMQP implementations with Celery | I wanted to get your opinions on the merits of different AMQP implementations to be used with celery. I am looking particularly at message prioritization and job queue sizes.
What are your thoughts?
| [
"After reading some docs and trying out a few options, I have found that RabbitMQ suffices for most purposes.\n"
] | [
0
] | [] | [] | [
"amqp",
"celery",
"python"
] | stackoverflow_0003809440_amqp_celery_python.txt |
Q:
how to download in python
I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in ... | how to download in python | I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in python at client side?
| [
"If the script runs on your server, its purpose is to serve a document, not to download it (the latter would be the urllib solution).\nDepending on your needs you can:\n\nSet up static file serving with e.g. Apache\nMake the script execute on a certain URL (e.g. with mod_wsgi), then the script should set the Conten... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004311347_python.txt |
Q:
Using izip over second dimension of numpy array
I have the following:
for i in xrange(n):
label = labels[i]
frame = data[:, i]
dostuff()
Where data is a 2-D numpy array. I'd like to rewrite it using izip.
for label, frame in izip(labels, ???):
dostuff()
What do I replace ??? with to get this to ... | Using izip over second dimension of numpy array | I have the following:
for i in xrange(n):
label = labels[i]
frame = data[:, i]
dostuff()
Where data is a 2-D numpy array. I'd like to rewrite it using izip.
for label, frame in izip(labels, ???):
dostuff()
What do I replace ??? with to get this to work?
| [
"If you really want to use izip(), you can do it like this:\nfor label, frame in izip(labels, data.T):\n dostuff()\n\nIt is generally advisable not to iterate over a NumPy array using a Python loop, but rather use NumPy ufuncs to do the loops in C code. How to do this, depends on what dostuff() actually does.\n... | [
3,
1
] | [] | [] | [
"izip",
"numpy",
"python"
] | stackoverflow_0004310401_izip_numpy_python.txt |
Q:
Is this string Base64? How can I tell what is the encoding used?
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!
I use a software that stores the password in an oracle database. The password field is o... | Is this string Base64? How can I tell what is the encoding used? | This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!
I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes th... | [
"It is actually Base64 encoded. However, it is not the password itself that is encoded, but its SHA-1 hash.\nfrom sha import sha\nprint 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex')\nprint sha('1234').hexdigest()\n\nor for newer versions of Python:\nfrom hashlib import sha1\nprint 'cRDtpNCeBiql5KOQs... | [
13,
6
] | [] | [] | [
"base64",
"encoding",
"encryption",
"oracle",
"python"
] | stackoverflow_0004312492_base64_encoding_encryption_oracle_python.txt |
Q:
Django: order by field of many-to-many relation
Given django models A and B:
class A(models.Model):
things = models.ManyToManyField('B')
class B(models.Model):
score = models.FloatField()
text = models.CharField(max_length=100)
How do I get a list of A entities ordered by the text of the highest-scor... | Django: order by field of many-to-many relation | Given django models A and B:
class A(models.Model):
things = models.ManyToManyField('B')
class B(models.Model):
score = models.FloatField()
text = models.CharField(max_length=100)
How do I get a list of A entities ordered by the text of the highest-scoring B in things?
| [
"This sort of thing is really hard. Aggregation can help you if you want to sort by the score:\nfrom django.db.models import Max\nA.objects.annotate(highest_b=Max(B__score)).order_by('highest_b')\n\nBut in effect you want to do two operations: aggregate by the highest score, then sort by the text of the item with t... | [
3,
2
] | [] | [] | [
"django",
"django_models",
"python",
"sorting"
] | stackoverflow_0004309062_django_django_models_python_sorting.txt |
Q:
pymssql problem - INSERT does not work with parameters
I'm using pymssql to do database programming with Python on Linux.
I'm having problems with passing parameters to queries. This problem only seems to exist with INSERT queries.
This works:
query = "SELECT col1, col2 FROM table WHERE col3=%s"
cur.execute(query,... | pymssql problem - INSERT does not work with parameters | I'm using pymssql to do database programming with Python on Linux.
I'm having problems with passing parameters to queries. This problem only seems to exist with INSERT queries.
This works:
query = "SELECT col1, col2 FROM table WHERE col3=%s"
cur.execute(query, (value,))
But this doesn't:
query = "INSERT INTO table (co... | [
"Turns out one of the values I was trying to insert was of type unicode. When I converted it to string, using str(value1), the query worked.\n"
] | [
1
] | [
"How about this:\ncur.execute(query % (value1, value2))\n\n"
] | [
-1
] | [
"linux",
"pymssql",
"python",
"sql_server"
] | stackoverflow_0004285052_linux_pymssql_python_sql_server.txt |
Q:
python: is there a disadvantage to from package import * besides namespace collision
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need. I've been careful about avoiding namespace conflicts in my code, so, does
from package impor... | python: is there a disadvantage to from package import * besides namespace collision | I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need. I've been careful about avoiding namespace conflicts in my code, so, does
from package import *
create problems besides name conflicts?
Is it better to examine the class's input a... | [
"In order:\n\nIt does not create other problems - however, name conflicts can be much more of a problem than you'd expect.\nDefinitely defer your imports if you can. Even though Python variable scoping is simplistic, you also gain the benefit of not having to import the module if the functionality that needs it nev... | [
7,
2,
0,
0
] | [] | [] | [
"import",
"namespaces",
"python"
] | stackoverflow_0004313124_import_namespaces_python.txt |
Q:
Problem with creating a 2D interface in a 3D openGL world
I am working on a project that requires that I create a 2D interface rendered "on top" or a 3D world. On some other forums, I read that you could use "GluOrtho2D()" for the job, and switch back to GluPerspective() once you were done. The only thing is, my t... | Problem with creating a 2D interface in a 3D openGL world | I am working on a project that requires that I create a 2D interface rendered "on top" or a 3D world. On some other forums, I read that you could use "GluOrtho2D()" for the job, and switch back to GluPerspective() once you were done. The only thing is, my test code I wrote for it only displays the 3D world, not the 2D ... | [
"It looks like you don't call glLoadIdentity() after switching to GL_MODELVIEW. The simplest way to remember is to call it every time you change the projection matrix, switch to GL_MODELVIEW and call glLoadIdentity() (unless you really want to retain the old one).\n",
"A lot of people get it wrong how to use glVi... | [
4,
2,
1
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004289095_opengl_pyglet_python.txt |
Q:
Why this url pattern is not working?
from views import login
from django.conf.urls.defaults import *
urlpatterns = patterns('',
*** (r'([a-zA-Z0-9]+)/login/$', login, name='login'),
)
showing me the syntax error in line ***.
http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it... | Why this url pattern is not working? | from views import login
from django.conf.urls.defaults import *
urlpatterns = patterns('',
*** (r'([a-zA-Z0-9]+)/login/$', login, name='login'),
)
showing me the syntax error in line ***.
http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. ... | [
"tuple literals don't have named arguments. Try url() instead.\n url(r'([a-zA-Z0-9]+)/login/$', login, name='login'),\n\n",
"You need to use the url() function if you're using the name keyword:\nurl(r'([a-zA-Z0-9]+)/login/$', login, name='login'),\n\nAnd the order of parameters to the {% url %} tag has the url... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004313932_django_python.txt |
Q:
Equivalent of 'in' for comparing two Numpy arrays
In pure, unvectorised, Python I can use,
>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False
I would like to do something similar for arrays in Numpy i.e.
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, ... | Equivalent of 'in' for comparing two Numpy arrays | In pure, unvectorised, Python I can use,
>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False
I would like to do something similar for arrays in Numpy i.e.
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])
... | [
"You are looking for in1d:\n>>> import numpy as np\n>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n>>> b = np.array([5, 7, 12])\n>>> np.in1d( a, b)\narray([False, False, False, False, True, False, True, False, False, False], dtype=bool)\n\n",
"You're comparing two very different things. With the pure Python... | [
8,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004313986_numpy_python.txt |
Q:
How can I install a python .egg file
I am trying to install twisted on python 2.6 and it seems that the Zop interface is missing.
Also it seems that it is a .egg file. I downloaded this .egg file, now how can I install it?
A:
Install virtualenv, which includes pip. Then you can simply run:
pip install twisted
... | How can I install a python .egg file | I am trying to install twisted on python 2.6 and it seems that the Zop interface is missing.
Also it seems that it is a .egg file. I downloaded this .egg file, now how can I install it?
| [
"Install virtualenv, which includes pip. Then you can simply run:\npip install twisted\n\npip will handle installing the zope.interface.\nInstructions for installing virtualenv and pip on OS X\nThis is how I installed virtualenv and pip on OS X:\ncurl -O http://peak.telecommunity.com/dist/ez_setup.py\nsudo python e... | [
4
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0004314376_python_twisted.txt |
Q:
Extend Django User model (make it work in request.user), Django 1.2.3
I'd like to extend the User model, so I can put in some extra fields and functions (not only fields, keep in mind, or else (well, still) I could use get_profile(), which I think is ugly).
Also I would like to use that new extended User model in ... | Extend Django User model (make it work in request.user), Django 1.2.3 | I'd like to extend the User model, so I can put in some extra fields and functions (not only fields, keep in mind, or else (well, still) I could use get_profile(), which I think is ugly).
Also I would like to use that new extended User model in request.user, like this:
Extended User model:
# imports etc
class CustomUs... | [
"You're on the right track with adjusting the Authentication Backend.\nAuthentication backends can be pretty simple, here is a snip of ours we use in our project.\nclass LocalAccount(object):\n def authenticate(self, system=None, username=None, password=None):\n try:\n user = User.objects.get(s... | [
2
] | [] | [] | [
"django",
"django_1.2",
"model",
"python"
] | stackoverflow_0004314068_django_django_1.2_model_python.txt |
Q:
How to work on this particular situation in django admin?
class Foo(models.Model):
bar_protected = models.BooleanField(default=False)
bar = models.CharField(max_length=50
Here I am customizing django admin. Now I have two field in the model. By Default I want that 'bar' remains disabled. (Not Hide). And b... | How to work on this particular situation in django admin? | class Foo(models.Model):
bar_protected = models.BooleanField(default=False)
bar = models.CharField(max_length=50
Here I am customizing django admin. Now I have two field in the model. By Default I want that 'bar' remains disabled. (Not Hide). And bar_protected unchecked. When some one checked bar_protected , b... | [
"You should either use editable = False in the model for that field or put it in readonly_fields while registering the model in the admin.py file. This should work.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004314293_django_python.txt |
Q:
PHP and Python static methods in objects, two different worlds...?
i'm php coder, trying to get into python world, and it's very hard for me.
Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor param... | PHP and Python static methods in objects, two different worlds...? | i'm php coder, trying to get into python world, and it's very hard for me.
Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)
<?php
class Foo {
function __constructor__(){
... | [
"static methods in PHP are not as you believe, they can't access to instance members. No $this! with them.\n<?php\nclass Foo {\n\n public static $var = 'foo ';\n\n function __construct(){\n echo 'constructing ';\n $this->var = 'blah ';\n }\n\n public function aMethod() {\n return $t... | [
4,
3,
2
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004314423_php_python.txt |
Q:
Decorate GET URL using forms
I have some question:
I use django form, and fields like MultipleChoiceField
in view.py I clean data and get GET URL like this
http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=
Give me advise, can I regroup brand field and hide empty.
I w... | Decorate GET URL using forms | I have some question:
I use django form, and fields like MultipleChoiceField
in view.py I clean data and get GET URL like this
http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=
Give me advise, can I regroup brand field and hide empty.
I want getting something like this:
h... | [
"For empty label in forms you could do this - \nclass SomeForm(forms.Form):\n h=forms.CharField(label=u'',widget=forms.TextInput(attrs={'value':'Search'}))\n\nBy keeping label as '', you get the label as empty. The attrs are basically the HTML attributes of the form text field.\nUPDATE: I didn't understand the f... | [
0,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004313160_django_django_forms_python.txt |
Q:
How can I implement a makefile-style algorithm in python
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stage... | How can I implement a makefile-style algorithm in python | I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.
The input to this feature extraction system will be a graph... | [
"Topological sorting\n",
"blocks is basically an adjacency list representation of the (acyclic) dependency graph. Hence, to get the correct order to process the blocks, you can perform a topological sort.\n",
"As the other helpful answerers have already pointed out, what I'm after is a topological sort, but I t... | [
5,
0,
0,
0
] | [] | [] | [
"algorithm",
"makefile",
"python"
] | stackoverflow_0004310607_algorithm_makefile_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.