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:
Change Flash source by Python
I have flash with big image library inside, is there way to manipulate this content by python?
A:
Python Flash Tools intended to be a level up from the Ming SWF library and a step down from a Flash GUI see http://pyswftools.sourceforge.net/
| Change Flash source by Python | I have flash with big image library inside, is there way to manipulate this content by python?
| [
"Python Flash Tools intended to be a level up from the Ming SWF library and a step down from a Flash GUI see http://pyswftools.sourceforge.net/\n"
] | [
0
] | [] | [] | [
"flash",
"python"
] | stackoverflow_0001171170_flash_python.txt |
Q:
How to solve this complex recursive problem, pyramid point system
I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this ... | How to solve this complex recursive problem, pyramid point system | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the poin... | [
"I think your problem could be that you aren't setting the child(s) of profile to now have parent as it's/their parent, unless children with parents can't also be parents in your system (which I do not believe to be the case).\nAlternatively (or possibly together with the previous), you may want to just do parent =... | [
1,
1
] | [] | [] | [
"django",
"python",
"recursion"
] | stackoverflow_0001171926_django_python_recursion.txt |
Q:
How can I run telnet command in the python GUI?
How can I run telnet command in the python GUI?
A:
Sounds like you need telnetlib
A:
You may also be interested in Scapy, though it may be too low-level for what you want.
| How can I run telnet command in the python GUI? | How can I run telnet command in the python GUI?
| [
"Sounds like you need telnetlib \n",
"You may also be interested in Scapy, though it may be too low-level for what you want.\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001170713_python.txt |
Q:
django - circular import problem when executing a command
I'm developing a django application. Modules of importance to my problem are given below:
globals.py --> contains constants that are used throughout the application. SITE_NAME and SITE_DOMAIN are two of those and are used to fill some strings. Here is how I... | django - circular import problem when executing a command | I'm developing a django application. Modules of importance to my problem are given below:
globals.py --> contains constants that are used throughout the application. SITE_NAME and SITE_DOMAIN are two of those and are used to fill some strings. Here is how I define them:
from django.contrib.sites.models import Site
...
... | [
"Is there any particular reason you need to store SITE_DOMAIN and SITE_NAME in globals.py? These are already available directly from the sites framework.\nAccording to the docs, the site object is cached the first time you access it, so importing it and using it there directly doesn't hurt.\n"
] | [
1
] | [] | [] | [
"circular_reference",
"django",
"import",
"python"
] | stackoverflow_0001172386_circular_reference_django_import_python.txt |
Q:
Django-admin : How to display link to object info page instead of edit form , in records change list?
I am customizing Django-admin for an application am working on . so
far the customization is working file , added some views . but I am
wondering how to change the records link in change_list display to
display an... | Django-admin : How to display link to object info page instead of edit form , in records change list? | I am customizing Django-admin for an application am working on . so
far the customization is working file , added some views . but I am
wondering how to change the records link in change_list display to
display an info page instead of change form ?!
in this blog post :http://www.theotherblog.com/Articles/2009/06/02/
ex... | [
"If I understand your question right you want to add your own link to the listing view, and you want that link to point to some info page you have created.\nTo do that, create a function to return the link HTML in your Admin object. Then use that function in your list. Like this:\nclass ModelAdmin(admin.ModelAdmin)... | [
23,
10
] | [] | [] | [
"admin",
"django",
"django_admin",
"python"
] | stackoverflow_0001172584_admin_django_django_admin_python.txt |
Q:
Tokenizing blocks of code in Python
I have this string:
[a [a b] [c e f] d]
and I want a list like this
lst[0] = "a"
lst[1] = "a b"
lst[2] = "c e f"
lst[3] = "d"
My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '['
and the other with ']' ) but I am... | Tokenizing blocks of code in Python | I have this string:
[a [a b] [c e f] d]
and I want a list like this
lst[0] = "a"
lst[1] = "a b"
lst[2] = "c e f"
lst[3] = "d"
My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '['
and the other with ']' ) but I am sure it can be
done using list comprehen... | [
"Actually this really isn't a recursive data structure, note that a and d are in separate lists. You're just splitting the string over the bracket characters and getting rid of some white space.\nI'm sure somebody can find something cleaner, but if you want a one-liner something like the following should get you c... | [
4,
1,
1
] | [] | [] | [
"list_comprehension",
"python",
"regex",
"tokenize"
] | stackoverflow_0001172738_list_comprehension_python_regex_tokenize.txt |
Q:
Is there a non-GPL Python Library for reading ID3 information from an mp3?
I have found many GPL licensed libraries for reading information from mp3s in Python. Are there any non GPL libraries?
A:
pytagger is using a BSD license.
A:
There's Stagger (new BSD license), pure Python 3.
A:
You could use GStreamer... | Is there a non-GPL Python Library for reading ID3 information from an mp3? | I have found many GPL licensed libraries for reading information from mp3s in Python. Are there any non GPL libraries?
| [
"pytagger is using a BSD license.\n",
"There's Stagger (new BSD license), pure Python 3.\n",
"You could use GStreamer (LGPL), but that might be a bit overkill if you only want the metadata and no playback.\n"
] | [
3,
2,
0
] | [] | [] | [
"gpl",
"id3",
"licensing",
"mp3",
"python"
] | stackoverflow_0001173025_gpl_id3_licensing_mp3_python.txt |
Q:
Python file at GAE
I have added a python file at google app engine. how to send a request to this file. Is this file needed to b executed explicitly?
A:
Your app.yaml file decides which python script to run, depending on the request URL.
See examples at the Google Docs. You can even use regexp.
| Python file at GAE | I have added a python file at google app engine. how to send a request to this file. Is this file needed to b executed explicitly?
| [
"Your app.yaml file decides which python script to run, depending on the request URL.\nSee examples at the Google Docs. You can even use regexp.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001172725_google_app_engine_python.txt |
Q:
Python Server Pages Implementations
I've been a PHP developer for quite awhile, and I've heard good things about using Python for web scripting. After a bit of research, I found mod_python, which integrates with Apache to allow Python Server Pages, which seem very similar to the PHP pages I'm used to. I also found... | Python Server Pages Implementations | I've been a PHP developer for quite awhile, and I've heard good things about using Python for web scripting. After a bit of research, I found mod_python, which integrates with Apache to allow Python Server Pages, which seem very similar to the PHP pages I'm used to. I also found a mod_wsgi which looks similar.
I was wo... | [
"I believe mod_wsgi is the preferred option to mod_python:\nhttp://code.google.com/p/modwsgi/\nSome performance benchmarks seem to suggest that mod_wsgi performs much better also. \nhttp://code.google.com/p/modwsgi/wiki/PerformanceEstimates\n"
] | [
3
] | [] | [] | [
"apache",
"mod_python",
"php",
"python"
] | stackoverflow_0001173184_apache_mod_python_php_python.txt |
Q:
Randomness in Jython
When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?
A:
Python's version is much faster in a simple test on my Mac:
jython -m timeit -s "import random" "random.random()"
1000000 loops, best of 3: 0.266 usec per loop... | Randomness in Jython | When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?
| [
"Python's version is much faster in a simple test on my Mac:\njython -m timeit -s \"import random\" \"random.random()\"\n\n1000000 loops, best of 3: 0.266 usec per loop\nvs\n jython -m timeit -s \"import java.util.Random; random=java.util.Random()\" \"random.nextDouble()\"\n\n1000000 loops, best of 3: 1.65 usec per... | [
9,
4
] | [] | [] | [
"java",
"jython",
"python",
"random"
] | stackoverflow_0001173520_java_jython_python_random.txt |
Q:
Does Python unittest report errors immediately?
Does Python's unittest module always report errors in strict correspondence to the execution order of the lines in the code tested? Do errors create the possibility of unexpected changes into the code's variables?
I was baffled by a KeyError reported by unittest. T... | Does Python unittest report errors immediately? | Does Python's unittest module always report errors in strict correspondence to the execution order of the lines in the code tested? Do errors create the possibility of unexpected changes into the code's variables?
I was baffled by a KeyError reported by unittest. The line itself looks okay. On the last line before e... | [
"I think you're seeing the error at the NEXT leg of your for loop, compared to the one with which you see all the output -- try changing the plain print to print>>stderr, statements so that buffering and possible suppression of output is not a risk.\n"
] | [
1
] | [] | [] | [
"python",
"testing",
"unit_testing"
] | stackoverflow_0001173310_python_testing_unit_testing.txt |
Q:
python namespace hierarchy above object
For example, if this code were contained in a module called some_module
class C:
class C2:
def g(self):
@printNamespaceAbove
def f():
pass
then printNamespaceAbove would be defined so that this code would output something ... | python namespace hierarchy above object | For example, if this code were contained in a module called some_module
class C:
class C2:
def g(self):
@printNamespaceAbove
def f():
pass
then printNamespaceAbove would be defined so that this code would output something like
[some_module,C,C2,g]
| [
"There is no way to make this code, as presented, have any output -- the body of g (including the decorator you'd like to do the printing) simply DOESN'T execute until g is called. I assume you do not literally intend for \"this code\" on its own to output anything, but rather intend to add a call such as C.C2().g(... | [
2
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0001173401_namespaces_python.txt |
Q:
What is a basic example of single inheritance using the super() keyword in Python?
Let's say I have the following classes set up:
class Foo:
def __init__(self, frob, frotz):
self.frobnicate = frob
self.frotz = frotz
class Bar:
def __init__(self, frob, frizzle):
self.frobnica... | What is a basic example of single inheritance using the super() keyword in Python? | Let's say I have the following classes set up:
class Foo:
def __init__(self, frob, frotz):
self.frobnicate = frob
self.frotz = frotz
class Bar:
def __init__(self, frob, frizzle):
self.frobnicate = frob
self.frotz = 34
self.frazzle = frizzle
How can I (if I ca... | [
"Assuming you want class Bar to set the value 34 within its constructor, this would work:\nclass Foo(object):\n def __init__(self, frob, frotz):\n self.frobnicate = frob\n self.frotz = frotz\n\nclass Bar(Foo):\n def __init__(self, frob, frizzle):\n super(Bar, self).__init__(frob, ... | [
29,
26
] | [] | [] | [
"constructor",
"inheritance",
"python",
"super"
] | stackoverflow_0001173992_constructor_inheritance_python_super.txt |
Q:
django comments: how to prevent form errors from redirecting the user to the preview page?
Currently, django.contrib.comments sends the user to the preview page if there is any error on the form.
I am using comments in the context of a blog and I would much rather that the user stayed on the page they were on if ... | django comments: how to prevent form errors from redirecting the user to the preview page? | Currently, django.contrib.comments sends the user to the preview page if there is any error on the form.
I am using comments in the context of a blog and I would much rather that the user stayed on the page they were on if something went wrong with the submission. As far as I can tell though, this is hard-coded in dja... | [
"Looks like you have two real options:\n\nWrite your own view. Possibly copy that view's code to get started.\nPatch that view to take an extra parameter, such as 'preview_on_errors' which defaults to True but can be overridden. Contribute the patch back to Django so other people can benefit from it.\n\n",
"Yes... | [
3,
0
] | [] | [] | [
"django",
"django_contrib",
"python"
] | stackoverflow_0001174140_django_django_contrib_python.txt |
Q:
To calculate the sum of numbers in a list by Python
My data
466.67
465.56
464.44
463.33
462.22
461.11
460.00
458.89
...
I run in Python
sum(/tmp/1,0)
I get an error.
How can you calculate the sum of the values by Python?
A:
f=open('/tmp/1')
print sum(map(float,f))
A:
sum(float(i) for i in open('/tmp/1.0'))
| To calculate the sum of numbers in a list by Python | My data
466.67
465.56
464.44
463.33
462.22
461.11
460.00
458.89
...
I run in Python
sum(/tmp/1,0)
I get an error.
How can you calculate the sum of the values by Python?
| [
"f=open('/tmp/1')\nprint sum(map(float,f))\n\n",
"sum(float(i) for i in open('/tmp/1.0'))\n\n"
] | [
13,
11
] | [] | [] | [
"python"
] | stackoverflow_0001174435_python.txt |
Q:
appengine: cached reference property?
How can I cache a Reference Property in Google App Engine?
For example, let's say I have the following models:
class Many(db.Model):
few = db.ReferenceProperty(Few)
class Few(db.Model):
year = db.IntegerProperty()
Then I create many Many's that point to only one Few... | appengine: cached reference property? | How can I cache a Reference Property in Google App Engine?
For example, let's say I have the following models:
class Many(db.Model):
few = db.ReferenceProperty(Few)
class Few(db.Model):
year = db.IntegerProperty()
Then I create many Many's that point to only one Few:
one_few = Few.get_or_insert(year=2009)
Ma... | [
"The first time you dereference any reference property, the entity is fetched - even if you'd previously fetched the same entity associated with a different reference property. This involves a datastore get operation, which isn't as expensive as a query, but is still worth avoiding if you can.\nThere's a good modul... | [
8,
1
] | [] | [] | [
"database",
"google_app_engine",
"google_cloud_datastore",
"performance",
"python"
] | stackoverflow_0001174075_database_google_app_engine_google_cloud_datastore_performance_python.txt |
Q:
Wxpython: Positioning a menu under a toolbar button
I have a CheckLabelTool in a wx.ToolBar and I want a menu to popup directly beneath it on mouse click. I'm trying to get the location of the tool so I can set the position of the menu, but everything I've tried (GetEventObject, GetPosition, etc) gives me the pos... | Wxpython: Positioning a menu under a toolbar button | I have a CheckLabelTool in a wx.ToolBar and I want a menu to popup directly beneath it on mouse click. I'm trying to get the location of the tool so I can set the position of the menu, but everything I've tried (GetEventObject, GetPosition, etc) gives me the position of the toolbar, so consequently the menu pops under... | [
"Read the section on the PopupMenu method on wxpython.org:\n\n\"Pops up the given menu at the\n specified coordinates, relative to\n this window, and returns control when\n the user has dismissed the menu. If a\n menu item is selected, the\n corresponding menu event is generated\n and will be processed as usu... | [
6
] | [] | [] | [
"menu",
"python",
"toolbar",
"wxwidgets"
] | stackoverflow_0001173642_menu_python_toolbar_wxwidgets.txt |
Q:
How to increase connection pool size for Twisted?
I'm using Twisted 8.1.0 as socket server engine. Reactor - epoll. Database server is MySQL 5.0.67. OS - Ubuntu Linux 8.10 32-bit
in /etc/mysql/my.cnf :
max_connections = 1000
in source code:
adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='... | How to increase connection pool size for Twisted? | I'm using Twisted 8.1.0 as socket server engine. Reactor - epoll. Database server is MySQL 5.0.67. OS - Ubuntu Linux 8.10 32-bit
in /etc/mysql/my.cnf :
max_connections = 1000
in source code:
adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='utf8',
cp_min=3, cp_max=700, cp_... | [
"As you suspect, this is probably a threading issue. cp_max sets an upper limit for the number of threads in the thread pool, however, your process is very likely running out of memory well below this limit, in your case around 200 threads. Because each thread has its own stack, the total memory being used by your ... | [
8
] | [] | [] | [
"connection_pooling",
"python",
"twisted"
] | stackoverflow_0001171519_connection_pooling_python_twisted.txt |
Q:
How to refactor this Python code?
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
tasks_query = Task.all()
tasks = tasks_query.fetch(1000)
if user:
url = users.create_logout_url(self.request.uri)
else:
url = users.create_login_url(self.request... | How to refactor this Python code? | class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
tasks_query = Task.all()
tasks = tasks_query.fetch(1000)
if user:
url = users.create_logout_url(self.request.uri)
else:
url = users.create_login_url(self.request.uri)
template_values = {
'ta... | [
"Really it depends on what you expect to be common between the two classes in future. The purpose of refactoring is to identify common abstractions, not to minimise the number of lines of code.\nThat said, assuming the two requests are expected to differ only in the template:\nclass TaskListPage(webapp.RequestHandl... | [
6,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"refactoring"
] | stackoverflow_0001175043_google_app_engine_python_refactoring.txt |
Q:
python sqlalchemy parallel operation
HI,i got a multi-threading program which all threads will operate on oracle
DB. So, can sqlalchemy support parallel operation on oracle?
tks!
A:
OCI (oracle client interface) has a parameter OCI_THREADED which has the effect of connections being mutexed, such that concurrent ... | python sqlalchemy parallel operation | HI,i got a multi-threading program which all threads will operate on oracle
DB. So, can sqlalchemy support parallel operation on oracle?
tks!
| [
"OCI (oracle client interface) has a parameter OCI_THREADED which has the effect of connections being mutexed, such that concurrent access via multiple threads is safe. This is likely the setting the document you saw was referring to.\ncx_oracle, which is essentially a Python->OCI bridge, provides access to this s... | [
4,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001117538_python_sqlalchemy.txt |
Q:
Using map() to get number of times list elements exist in a string in Python
I'm trying to get the number of times each item in a list is in a string in Python:
paragraph = "I eat bananas and a banana"
def tester(x): return len(re.findall(x,paragraph))
map(tester, ['banana', 'loganberry', 'passion fruit'])
Retu... | Using map() to get number of times list elements exist in a string in Python | I'm trying to get the number of times each item in a list is in a string in Python:
paragraph = "I eat bananas and a banana"
def tester(x): return len(re.findall(x,paragraph))
map(tester, ['banana', 'loganberry', 'passion fruit'])
Returns [2, 0, 0]
What I'd like to do however is extend this so I can feed the paragr... | [
"A closure would be a quick solution:\nparagraph = \"I eat bananas and a banana\"\n\ndef tester(s): \n def f(x):\n return len(re.findall(x,s))\n return f\n\nprint map(tester(paragraph), ['banana', 'loganberry', 'passion fruit'])\n\n",
"targets = ['banana', 'loganberry', 'passion fruit']\nparagraph = ... | [
8,
3,
2,
2,
1,
1,
0
] | [] | [] | [
"mapreduce",
"python",
"regex"
] | stackoverflow_0001168517_mapreduce_python_regex.txt |
Q:
Google Wave Sandbox
Is anyone developing robots and/or gadgets for Google Wave?
I have been a part of the sandbox development for a few days and I was interested in seeing what others have thought about the Google Wave APIs.
I was also wondering what everyone has been working on. Please share your opinions and c... | Google Wave Sandbox | Is anyone developing robots and/or gadgets for Google Wave?
I have been a part of the sandbox development for a few days and I was interested in seeing what others have thought about the Google Wave APIs.
I was also wondering what everyone has been working on. Please share your opinions and comments!
| [
"Go to Google Wave developers and read the blogs, forums and all your questions will be answered including a recent post for a gallery of Wave apps. You will also find other developers to play in the sandbox with.\n",
"I haven't tried the gadgets, but from the little I've looked at them, they seem pretty straight... | [
2,
2,
2
] | [] | [] | [
"google_app_engine",
"google_wave",
"java",
"python"
] | stackoverflow_0001161660_google_app_engine_google_wave_java_python.txt |
Q:
Python equivalent of PropertyUtilsBean
I was wondering, is there a Python equivalent to Apache commons' PropertyUtilsBean?
Edit:
For example, I'd like to be able to make this assignment
x.y[2].z = v
given "y[2].z" as a string.
Please note, I'm asking just because I'd like to not reinvent the wheel :)
A:
Do you ... | Python equivalent of PropertyUtilsBean | I was wondering, is there a Python equivalent to Apache commons' PropertyUtilsBean?
Edit:
For example, I'd like to be able to make this assignment
x.y[2].z = v
given "y[2].z" as a string.
Please note, I'm asking just because I'd like to not reinvent the wheel :)
| [
"Do you mean something like setattr?\nFrom its docstring:\n\nsetattr(object, name, value)\n\nSet a named attribute on an object;\n setattr(x, 'y', v) is equivalent to\n ``x.y = v''.\n\n",
"Why do you need such a thing when there's exec?\n"
] | [
1,
1
] | [] | [] | [
"apache_commons",
"python"
] | stackoverflow_0001176139_apache_commons_python.txt |
Q:
Return files only from specific folder
I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:
def ReturnFile(fileName)
return open("C:\\folder\\" + fileName,"r")
But as fileName you can pass for example: "..\\Windows\\passwords.txt" ... | Return files only from specific folder | I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:
def ReturnFile(fileName)
return open("C:\\folder\\" + fileName,"r")
But as fileName you can pass for example: "..\\Windows\\passwords.txt" or some unicode symbols for dots.
How to fix... | [
"The os.path.normpath function normalizes a given path py resolving things like \"..\". Then you can check if the resulting path is in the expected directory:\ndef ReturnFile(fileName)\n norm = os.path.abspath(\"C:\\\\folder\\\\\" + fileName)\n if not norm.startswith(\"C:\\\\folder\\\\\"):\n raise Exception(\"... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0001176624_python.txt |
Q:
How do I add items to a gtk.ComboBox created through glade at runtime?
I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track.
How do I add strings to the ComboBox at runtime? This is what I h... | How do I add items to a gtk.ComboBox created through glade at runtime? | I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track.
How do I add strings to the ComboBox at runtime? This is what I have so far:
self.tracked_interface = builder.get_object("tracked_interface")... | [
"Hey, I actually get to answer my own question!\nYou have to add gtk.CellRendererText into there for it to actually render:\nself.iface_list_store = gtk.ListStore(gobject.TYPE_STRING)\nself.iface_list_store.append([\"hello, \"])\nself.iface_list_store.append([\"world.\"])\nself.tracked_interface.set_model(self.ifac... | [
6,
6
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0001176748_gtk_pygtk_python.txt |
Q:
Python- about file-handle limits on OS
HI i wrote a program by python , and when i open too many tempfile, i will got an exception: Too many open files ...
Then i figure out that windows OS or C runtime has the file-handle limits, so, i alter my program using StringIO(), but still don`t know whether StringIO also ... | Python- about file-handle limits on OS | HI i wrote a program by python , and when i open too many tempfile, i will got an exception: Too many open files ...
Then i figure out that windows OS or C runtime has the file-handle limits, so, i alter my program using StringIO(), but still don`t know whether StringIO also is limited??
| [
"Python's StringIO does not use OS file handles, so it won't be limited in the same way. StringIO will be limited by available virtual memory, but you've probably got heaps of available memory.\nNormally the OS allows a single process to open thousands of files before running into the limit, so if your program is r... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0001177230_python.txt |
Q:
Why is there module search path instead of typing the directory name + typing the file name?
Is there an advantage? What is it?
A:
So that everyone doesn't need to have exactly the same file structure on their hard drive? import C:\Python\lib\module\ probably wouldn't work too well on my Mac...
Edit: Also, what... | Why is there module search path instead of typing the directory name + typing the file name? | Is there an advantage? What is it?
| [
"So that everyone doesn't need to have exactly the same file structure on their hard drive? import C:\\Python\\lib\\module\\ probably wouldn't work too well on my Mac...\nEdit: Also, what the heck are you talking about with the working directory? You can certainly use modules outside the working directory, as lon... | [
6
] | [] | [] | [
"import",
"module_search_path",
"python"
] | stackoverflow_0001177513_import_module_search_path_python.txt |
Q:
Profiling Python Scripts running on Mod_wsgi
How can I profile a python script running on mod_wsgi on apache
I would like to use cProfile but it seems it requires me to invoke a function manually. Is there a way to enable cProfile globally and have it keep on logging results.
A:
You need to wrap you wsgi applic... | Profiling Python Scripts running on Mod_wsgi | How can I profile a python script running on mod_wsgi on apache
I would like to use cProfile but it seems it requires me to invoke a function manually. Is there a way to enable cProfile globally and have it keep on logging results.
| [
"You need to wrap you wsgi application function inside another function that just calls your function using cProfile and use that as the application. Or you can reuse existing WSGI middleware to do that for you, for example repoze.profile does pretty much what you seem to want.\n",
"Here is the WSGI profile middl... | [
9,
0
] | [] | [] | [
"profiling",
"python",
"wsgi"
] | stackoverflow_0001169833_profiling_python_wsgi.txt |
Q:
Mismatch between MySQL and Python
I know the mismatch between Object Oriented Technology and the Relational Technology, generally here.
But I do not know the mismatch between MySQL and Python, and other tools, not just ORMs, to deal with the issue, missing in the latter article.
Questions:
How is the problem dea... | Mismatch between MySQL and Python | I know the mismatch between Object Oriented Technology and the Relational Technology, generally here.
But I do not know the mismatch between MySQL and Python, and other tools, not just ORMs, to deal with the issue, missing in the latter article.
Questions:
How is the problem dealt between MySQL and Python?
Does App ... | [
"ORM is the standard solution for making the object-oriented world of Python match the Relational world of MySQL.\nThere are at least 3 popular ORM components.\n\nSQLAlchemy\nSQLObject\nDjango's ORM.\n\n",
"As was once said on comp.lang.python ORM's are like morphine -- it can save you pain if you are really hurt... | [
3,
1
] | [] | [] | [
"google_app_engine",
"mismatch",
"mysql",
"python"
] | stackoverflow_0001172790_google_app_engine_mismatch_mysql_python.txt |
Q:
Decoding double encoded utf8 in Python
I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed ... | Decoding double encoded utf8 in Python | I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaro... | [
"\n>>> s = u'Rafa\\xc5\\x82'\n>>> s.encode('raw_unicode_escape').decode('utf-8')\nu'Rafa\\u0142'\n>>>\n\n",
"Yow, that was fun!\n>>> original = \"Rafa\\xc3\\x85\\xc2\\x82\"\n>>> first_decode = original.decode('utf-8')\n>>> as_chars = ''.join([chr(ord(x)) for x in first_decode])\n>>> result = as_chars.decode('utf-... | [
48,
4,
2
] | [] | [] | [
"decode",
"python",
"string",
"utf_8"
] | stackoverflow_0001177316_decode_python_string_utf_8.txt |
Q:
Python file read problem
file_read = open("/var/www/rajaneesh/file/_config.php", "r")
contents = file_read.read()
print contents
file_read.close()
The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in __conifg.php.
A:
Usually,... | Python file read problem | file_read = open("/var/www/rajaneesh/file/_config.php", "r")
contents = file_read.read()
print contents
file_read.close()
The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in __conifg.php.
| [
"Usually, when there is such kind of issues, it is very useful to start the interactive shell and analyze all commands.\nFor instance, it could be that the file does not exists (see comment from freiksenet) or you do not have privileges to it, or it is locked by another process.\nIf you execute the script in some s... | [
4,
2,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0001176988_file_io_python.txt |
Q:
how to search for specific file type with yahoo search API?
Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen... | how to search for specific file type with yahoo search API? | Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen through API?
I'd very much appreciate a sample code in Python, b... | [
"Yes, there is:\nhttp://developer.yahoo.com/search/boss/boss_guide/Web_Search.html#id356163\n",
"Thank you.\nI found myself that something like this works OK (file type is the first argument, and query is the second):\nformat = sys.argv[1]\nquery = \" \".join(sys.argv[2:])\nsrch = create_search(\"Web\", app_id, q... | [
0,
0,
0
] | [] | [] | [
"python",
"yahoo_api",
"yahoo_search"
] | stackoverflow_0000522781_python_yahoo_api_yahoo_search.txt |
Q:
python distutils win32 version question
So you can use distutils to create a file, such as
PIL-1.1.6.win32-py2.5.exe
which you can run and use to easily install something. However, the installation requires user input to proceed (you have to click 'OK' three times). I want to create an easily installable windows ... | python distutils win32 version question | So you can use distutils to create a file, such as
PIL-1.1.6.win32-py2.5.exe
which you can run and use to easily install something. However, the installation requires user input to proceed (you have to click 'OK' three times). I want to create an easily installable windows version that you can just run as a cmd line p... | [
"See this post which describes an idea to modify the stub installer like this:\nIt also mentions another alternative: use setup.py bdist_msi instead, which will produce an msi package, that can be installed unattended\n",
"You get the executable by running \"setup.py bdist_wininst\". You can have something simple... | [
1,
0,
0
] | [] | [] | [
"distutils",
"installation",
"python",
"windows_installer"
] | stackoverflow_0001166503_distutils_installation_python_windows_installer.txt |
Q:
How can I create bound methods with type()?
I am dynamically generating a function and assigning it to a class. This is a simple/minimal example of what I am trying to achieve:
def echo(obj):
print obj.hello
class Foo(object):
hello = "Hello World"
spam = type("Spam", (Foo, ), {"echo":echo})
spam.echo()
... | How can I create bound methods with type()? | I am dynamically generating a function and assigning it to a class. This is a simple/minimal example of what I am trying to achieve:
def echo(obj):
print obj.hello
class Foo(object):
hello = "Hello World"
spam = type("Spam", (Foo, ), {"echo":echo})
spam.echo()
Results in this error
Traceback (most recent cal... | [
"So far, you only have created a class. You also need to create objects, i.e. instances of that class:\nSpam = type(\"Spam\", (Foo, ), {\"echo\":echo})\nspam = Spam()\nspam.echo()\n\nIf you really want this to be a method on the class, rather than an instance method, wrap it with classmethod (instead of staticmetho... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0001178337_python.txt |
Q:
How to store arbitrary number of fields in django model?
I'm new to python/django. I need to store an arbitrary number of fields in a django model. I'm wondering if django has something that takes care of this.
Typically, I would store some XML in a column to do this. Does django offer some classes that makes this... | How to store arbitrary number of fields in django model? | I'm new to python/django. I need to store an arbitrary number of fields in a django model. I'm wondering if django has something that takes care of this.
Typically, I would store some XML in a column to do this. Does django offer some classes that makes this easy to do whether it be XML or some other(better) method?
Th... | [
"There are a lot of approaches to solve this problem, and depending on your situation any of them might work. You could certainly use a TextField to store XML or JSON or any other form of text. In combination with Python's pickle feature you can do some neater stuff.\nYou might look at the Django Pickle Field defin... | [
11,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001178551_django_django_models_python.txt |
Q:
using pyunit on a network thread
I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.
For example: The server it connects ... | using pyunit on a network thread | I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.
For example: The server it connects to could be on any port, and I want to... | [
"I would try to introduce a factory into your existing code that purports to create socket objects. Then in a test pass in a mock factory which creates mock sockets which just pretend they've connected to a server (or not for error cases, which you also want to test, don't you?) and log the message traffic to prov... | [
1,
0,
0,
0
] | [] | [] | [
"networking",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0001173767_networking_python_python_unittest_unit_testing.txt |
Q:
Suggestions for python assert function
I'm using assert multiple times throughout multiple scripts, I was wondering if anyone has any suggestions on a better way to achieve this instead of the functions I have created below.
def assert_validation(expected, actual, type='', message=''):
if type == '==':
... | Suggestions for python assert function | I'm using assert multiple times throughout multiple scripts, I was wondering if anyone has any suggestions on a better way to achieve this instead of the functions I have created below.
def assert_validation(expected, actual, type='', message=''):
if type == '==':
assert expected == actual, 'Expected: %s, A... | [
"Well this is certainly shorter... can you really not just use assert expected == actual or whatever in the scripts themselves?\ndef assert_validation(expected, actual, type='', message='', trans=(lambda x: x)):\n m = { '==': (lambda e, a: e == a),\n '!=': (lambda e, a: e != a),\n '<=': (lambda... | [
11
] | [] | [] | [
"assert",
"python"
] | stackoverflow_0001179096_assert_python.txt |
Q:
In python when passing arguments what does ** before an argument do?
From reading this example and from my slim knowledge of Python it must be a shortcut for converting an array to a dictionary or something?
class hello:
def GET(self, name):
return render.hello(name=name)
# Another way:
... | In python when passing arguments what does ** before an argument do? | From reading this example and from my slim knowledge of Python it must be a shortcut for converting an array to a dictionary or something?
class hello:
def GET(self, name):
return render.hello(name=name)
# Another way:
#return render.hello(**locals())
| [
"In python f(**d) passes the values in the dictionary d as keyword parameters to the function f. Similarly f(*a) passes the values from the array a as positional parameters.\nAs an example:\ndef f(count, msg):\n for i in range(count):\n print msg\n\nCalling this function with **d or *a:\n>>> d = {'count': 2, 'm... | [
11,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001179223_python.txt |
Q:
What does keyword CONSTRAINT do in this CREATE TABLE statement
I'm learning how to use sqlite3 with python. The example in the text book I am following is a database where each Country record has a Region, Country, and Population.
The book says:
The following snippet uses the CONSTRAINT keyword to specify
that... | What does keyword CONSTRAINT do in this CREATE TABLE statement | I'm learning how to use sqlite3 with python. The example in the text book I am following is a database where each Country record has a Region, Country, and Population.
The book says:
The following snippet uses the CONSTRAINT keyword to specify
that no two entries in the table being
created will ever have the same... | [
"Country_key is simply giving a name to the constraint. If you do not do this the name will be generated for you. This is useful when there are several constraints on the table and you need to drop one of them.\nAs an example for dropping the constraint:\nALTER TABLE PopByCountry DROP CONSTRAINT Country_Key\n\n",... | [
16,
3
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0001179352_python_sql.txt |
Q:
Overriding inherited behavior
I am using Multi-table inheritance for an object, and I need to limit the choices of the parent object foreign key references to only the rules that apply the child system.
from schedule.models import Event, Rule
class AirShowRule(Rule):
"""
Inheritance of the schedule.Rule
... | Overriding inherited behavior | I am using Multi-table inheritance for an object, and I need to limit the choices of the parent object foreign key references to only the rules that apply the child system.
from schedule.models import Event, Rule
class AirShowRule(Rule):
"""
Inheritance of the schedule.Rule
"""
rule_type = models.TextF... | [
"I looked into the structure of the classes listed, and you should add this:\nclass AirShow(Event):\n ... your stuff...\n rule = models.ForeignKey(AirShowRule, null = True, blank = True,\n verbose_name=\"VERBOSE NAME\", help_text=\"HELP TEXT\")\n\nthat should get everything straight (... | [
1
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0001179213_django_models_python.txt |
Q:
exit failed script run (python)
I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more th... | exit failed script run (python) | I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests wi... | [
"Are you just looking for the exit() function?\nimport sys\n\nif 1 < 0:\n print >> sys.stderr, \"Something is seriously wrong.\"\n sys.exit(1)\n\nThe (optional) parameter of exit() is the return code the script will return to the shell. Usually values different than 0 signal an error.\n",
"You can use sys.exit(... | [
25,
5,
1,
0
] | [] | [] | [
"exception",
"exit",
"python"
] | stackoverflow_0001178989_exception_exit_python.txt |
Q:
How to generate pdf with epydoc?
I am considering epydoc for the documentation of one module. It looks ok to me and is working fine when I am generating html document.
I would like to try to generate the documenation in the pdf format. I've just modified the 'output' setting in my config file.
Unfortunately, epyd... | How to generate pdf with epydoc? | I am considering epydoc for the documentation of one module. It looks ok to me and is working fine when I am generating html document.
I would like to try to generate the documenation in the pdf format. I've just modified the 'output' setting in my config file.
Unfortunately, epydoc fails when generating the pdf file.... | [
"I suppose that you used an existing conf file.\nIf you have a closer look inside, you will see an option pstat: profile.out. This options says that the file profile.out will be used to generate the call graph (see doc).\n# The name of one or more pstat files (generated by the profile\n# or hotshot module). These ... | [
3
] | [] | [] | [
"documentation",
"epydoc",
"latex",
"python"
] | stackoverflow_0001176407_documentation_epydoc_latex_python.txt |
Q:
Python error: int argument required
What am I doing wrong here?
i = 0
cursor.execute("insert into core_room (order) values (%i)", (int(i))
Error:
int argument required
The database field is an int(11), but I think the %i is generating the error.
Update:
Here's a more thorough example:
time = datetime.datetime... | Python error: int argument required | What am I doing wrong here?
i = 0
cursor.execute("insert into core_room (order) values (%i)", (int(i))
Error:
int argument required
The database field is an int(11), but I think the %i is generating the error.
Update:
Here's a more thorough example:
time = datetime.datetime.now()
floor = 0
i = 0
try:
booster... | [
"Two things. First, use %s and not %i. Second, parameters must be in a tuple - so you need (i,) (with comma after i).\nAlso, ORDER is a keyword, and should be escaped if you're using it as field name.\n",
"I believe the second argument to execute() is expected to be an iterable. IF this is the case you need to c... | [
4,
1,
1
] | [] | [] | [
"mysql",
"mysql_error_1064",
"python"
] | stackoverflow_0001180673_mysql_mysql_error_1064_python.txt |
Q:
Best way to sort 1M records in Python
I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following
myHashTable = {}
myLists = { 'hits':{}, 'misses':{}, 'total':{} }
sorted = { 'hits':[], 'misses':[], 'total':[] }
for item in myList:
id = item.pop('id')
myHashTable[id] = i... | Best way to sort 1M records in Python | I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following
myHashTable = {}
myLists = { 'hits':{}, 'misses':{}, 'total':{} }
sorted = { 'hits':[], 'misses':[], 'total':[] }
for item in myList:
id = item.pop('id')
myHashTable[id] = item
for k, v in item.iteritems():
myL... | [
"You may find this related answer from Guido: Sorting a million 32-bit integers in 2MB of RAM using Python\n",
"What you really want is an ordered container, instead of an unordered one. That would implicitly sort the results as they're inserted. The standard data structure for this is a tree.\nHowever, there ... | [
13,
4,
1,
1,
1,
1,
0,
0,
0,
0
] | [
"Honestly, the best way is to not use Python. If performance is a major concern for this, use a faster language.\n"
] | [
-5
] | [
"python"
] | stackoverflow_0001180240_python.txt |
Q:
one liner for conditionally replacing dictionary values
Is there a better way to express this using list comprehension? Or any other way of expressing this in one line?
I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the ... | one liner for conditionally replacing dictionary values | Is there a better way to express this using list comprehension? Or any other way of expressing this in one line?
I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary.
col = {'1':3.5, '6':4.7}
original = {'1':3, '... | [
"I believe update is what you want.\n\nupdate([other])\nUpdate the dictionary with the key/value pairs from other, overwriting existing keys.\n Return None.\n\nCode:\noriginal.update(col[user])\n\nA simple test:\nuser = \"user\"\n\nmatrix = {\n \"user\" : {\n \"a\" : \"b\",\n \"c\" : \"d\",\n ... | [
2
] | [] | [] | [
"dictionary",
"list_comprehension",
"python",
"refactoring"
] | stackoverflow_0001180846_dictionary_list_comprehension_python_refactoring.txt |
Q:
Composite pattern for GTD app
This is a continuation of one of my previous questions
Here are my classes.
#Project class
class Project:
def __init__(self, name, children=[]):
self.name = name
self.children = children
#add object
def add(self, object):
self.children.append(o... | Composite pattern for GTD app | This is a continuation of one of my previous questions
Here are my classes.
#Project class
class Project:
def __init__(self, name, children=[]):
self.name = name
self.children = children
#add object
def add(self, object):
self.children.append(object)
#get list of all actions... | [
"The problem is with your initialization of Projects:\n __init__(self, name, children=[]):\n\nYou only get one list, which is shared by all Projects you create without passing a value for children. See here for an explanation. You want to instead make the default None, and initialize an empty list whenever the v... | [
5
] | [] | [] | [
"composite",
"gtd",
"python",
"recursion"
] | stackoverflow_0001180876_composite_gtd_python_recursion.txt |
Q:
Python Popen difficulties: File not found
I'm trying to use python to run a program.
from subprocess import Popen
sa_proc = Popen(['C:\\sa\\sa.exe','--?'])
Running this small snippit gives the error:
WindowsError: [Error 2] The system cannot find the file specified
The program exists and I have copy and pasted... | Python Popen difficulties: File not found | I'm trying to use python to run a program.
from subprocess import Popen
sa_proc = Popen(['C:\\sa\\sa.exe','--?'])
Running this small snippit gives the error:
WindowsError: [Error 2] The system cannot find the file specified
The program exists and I have copy and pasted directly from explorer the absolute path to th... | [
"As the docs say, \"On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline() method.\". Maybe that method is messing things up, so why not try the simpler approach of:\nsa_proc = Popen(... | [
8,
0
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0001180592_popen_python_subprocess.txt |
Q:
How can you check if a key is currently pressed using Tkinter in Python?
Is there any way to detect which keys are currently pressed using Tkinter? I don't want to have to use extra libraries if possible. I can already detect when keys are pressed, but I want to be able to check at any time what keys are pressed d... | How can you check if a key is currently pressed using Tkinter in Python? | Is there any way to detect which keys are currently pressed using Tkinter? I don't want to have to use extra libraries if possible. I can already detect when keys are pressed, but I want to be able to check at any time what keys are pressed down at the moment.
| [
"I think you need to keep track of events about keys getting pressed and released (maintaining your own set of \"currently pressed\" keys) -- I believe Tk doesn't keep track of that for you (and Tkinter really adds little on top of Tk, it's mostly a direct interface to it).\n"
] | [
4
] | [] | [] | [
"keylistener",
"python",
"tkinter"
] | stackoverflow_0001181027_keylistener_python_tkinter.txt |
Q:
limit output from a sort method
if my views code is:
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
what is the argument that will limit the result to 50 tags?
I'm assuming this:
.... limit=50)
is incorrect.
more complete code follows:
videoarttags = Media.objects.order_by('date_a... | limit output from a sort method | if my views code is:
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
what is the argument that will limit the result to 50 tags?
I'm assuming this:
.... limit=50)
is incorrect.
more complete code follows:
videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art')
au... | [
"what about heapq.nlargest:\nReturn a list with the n largest elements from the dataset defined by iterable.key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]\n>>>... | [
4,
3,
0,
0,
0
] | [] | [] | [
"django",
"python",
"python_itertools"
] | stackoverflow_0001162142_django_python_python_itertools.txt |
Q:
emulating LiveHTTPheader in server side script or javascript?
I ran into this problem when scraping sites with heavy usage of javascript to obfuscate it's data.
For example,
"a href="javascript:void(0)" onClick="grabData(23)"> VIEW DETAILS
This href attribute, reveals no information about the actual URL. You'd ha... | emulating LiveHTTPheader in server side script or javascript? | I ran into this problem when scraping sites with heavy usage of javascript to obfuscate it's data.
For example,
"a href="javascript:void(0)" onClick="grabData(23)"> VIEW DETAILS
This href attribute, reveals no information about the actual URL. You'd have to manually look and examine the grabData() javascript function ... | [
"I'm not sure I understand the question but...\nIn PHP, incoming POST parameters are stored in the $_POST array, you can display them with print_r($_POST);.\n"
] | [
1
] | [] | [] | [
"jquery",
"php",
"python"
] | stackoverflow_0001181233_jquery_php_python.txt |
Q:
Rearrange equations for solver
I am looking for a generic python way to manipulate text into solvable equations.
For example:
there may be some constants to initialize
e1,e2=0.58,0.62
ma1,ma2=0.85,1.15
mw=0.8
Cpa,Cpw=1.023,4.193
dba,dbr=0.0,25.0
and a set of equations (written here for readability rather than the... | Rearrange equations for solver | I am looking for a generic python way to manipulate text into solvable equations.
For example:
there may be some constants to initialize
e1,e2=0.58,0.62
ma1,ma2=0.85,1.15
mw=0.8
Cpa,Cpw=1.023,4.193
dba,dbr=0.0,25.0
and a set of equations (written here for readability rather than the solver)
Q=e1*ma1*Cpa*(tw1-dba)
Q=ma... | [
"Actually, I've implemented exactly the same thing in python. I'm also familiar with the Eureka and the other programs you mentioned. You can see my implementation at xyzsolve.appspot.com (Sorry for the shameless plug). The implementation is in all python. I'll list the iterations the code went through: \nIteration... | [
2,
1
] | [] | [] | [
"equation",
"python",
"solver"
] | stackoverflow_0001169593_equation_python_solver.txt |
Q:
How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin
I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins ... | How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin | I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins but not Pydev.
| [
"Here are the steps to set up an external launch configuration to launch IE:\n\nSelect Run->External Tools->External Tools Configurations...\nIn the left hand pane, select Program then the new icon (left-most icon above the pane).\nIn the right hand pane, select the Main tab.\nEnter launch_ie in the Name: field.\nE... | [
7,
1
] | [] | [] | [
"eclipse",
"eclipse_plugin",
"pydev",
"python"
] | stackoverflow_0000697142_eclipse_eclipse_plugin_pydev_python.txt |
Q:
Does anyone have example code of using scipy.stats.distributions?
I am struggling to figure out how to use the scipy.distributions package and wondered if anyone could post some example code for me. It appears to do everything I need, I just can't figure out how to use it.
I need to generate two distributions, on... | Does anyone have example code of using scipy.stats.distributions? | I am struggling to figure out how to use the scipy.distributions package and wondered if anyone could post some example code for me. It appears to do everything I need, I just can't figure out how to use it.
I need to generate two distributions, one log-normal and one poisson. I know the variance and lambda for each.... | [
"I assume you mean the distributions in scipy.stats. To create a distribution, generate random variates and calculate the pdf:\nPython 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from s... | [
8,
3
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0000485076_python_scipy.txt |
Q:
Practical point of view: Why would I want to use Python with C++?
I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?
I'd appreciate a simple example - Boost::... | Practical point of view: Why would I want to use Python with C++? | I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?
I'd appreciate a simple example - Boost::Python will do
| [
"It depends on your point of view:\nCalling C++ code from a python application\nYou generally want to do this when performance is an issue. Highly dynamic languages like python are typically somewhat slower then native code such as C++. \"Features\" of C++ such as manual memory management allows for the development... | [
21,
5,
3,
3,
2,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0001181462_c++_python.txt |
Q:
Python: Multicore processing?
I've been reading about Python's multiprocessing module. I still don't think I have a very good understanding of what it can do.
Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:
list_sum = sum(... | Python: Multicore processing? | I've been reading about Python's multiprocessing module. I still don't think I have a very good understanding of what it can do.
Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:
list_sum = sum(my_list)
But this only sends it to... | [
"Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads:\nfrom multiprocessing import Process, Queue\n\ndef do_sum(q,l):\n q.put(sum(l))\n\ndef main():\n my_list = range(1000000)\n\n q = Queue()\n\n p1 = Process(target=do_sum, args=(q,my_list[:50000... | [
37,
22,
8
] | [] | [] | [
"multicore",
"multiprocessing",
"python"
] | stackoverflow_0001182315_multicore_multiprocessing_python.txt |
Q:
cx_Oracle MemoryError when reading lob
When trying to read data from a lob field using cx_Oralce I’m receiving “exceptions.MemoryError”. This code has been working, this one lob field seems to be too big.
Example:
xml_cursor = ora_connection.cursor()
xml_cursor.arraysize = 2000
try:
xml_cursor.execute(“select... | cx_Oracle MemoryError when reading lob | When trying to read data from a lob field using cx_Oralce I’m receiving “exceptions.MemoryError”. This code has been working, this one lob field seems to be too big.
Example:
xml_cursor = ora_connection.cursor()
xml_cursor.arraysize = 2000
try:
xml_cursor.execute(“select xml_data from xmlTable where id = 1”)
f... | [
"Yep, if Python is giving MemoryError it means that just that one field of that just one row takes more memory than you have (quite possible with a LOB of course). You'll have to slice it up and get it in chunks (with select dbms_lob.substr(xml_data, ... repeatedly) and feed it to an incremental XML parser (or writ... | [
5
] | [] | [] | [
"cx_oracle",
"python"
] | stackoverflow_0001182146_cx_oracle_python.txt |
Q:
Static vs instance methods of str in Python
So, I have learnt that strings have a center method.
>>> 'a'.center(3)
' a '
Then I have noticed that I can do the same thing using the 'str' object which is a type, since
>>> type(str)
<type 'type'>
Using this 'type' object I could access the string methods like they ... | Static vs instance methods of str in Python | So, I have learnt that strings have a center method.
>>> 'a'.center(3)
' a '
Then I have noticed that I can do the same thing using the 'str' object which is a type, since
>>> type(str)
<type 'type'>
Using this 'type' object I could access the string methods like they were static functions.
>>> str.center('a',5)
' a... | [
"That's simply how classes in Python work:\nclass C:\n def method(self, arg):\n print \"In C.method, with\", arg\n\no = C()\no.method(1)\nC.method(o, 1)\n# Prints:\n# In C.method, with 1\n# In C.method, with 1\n\nWhen you say o.method(1) you can think of it as a shorthand for C.method(o, 1). A method_des... | [
19,
9,
5,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001180303_python_string.txt |
Q:
Python dictionary/list help
This is a python application that's supposed to get all the followers from one table and get their latest updates from another table. - All happening in the dashboard.
dashboard.html:
http://bizteen.pastebin.com/m65c4ae2d
the dashboard function in views.py:
http://bizteen.pastebin.com... | Python dictionary/list help | This is a python application that's supposed to get all the followers from one table and get their latest updates from another table. - All happening in the dashboard.
dashboard.html:
http://bizteen.pastebin.com/m65c4ae2d
the dashboard function in views.py:
http://bizteen.pastebin.com/m39798bd5
result:
http://biztee... | [
"There's far too much code there to try and work out what's going on, and your explanation is not particularly clear.\nHowever, one obvious problem is that you've got a lot of blank except clauses, which is almost always a bad idea as it masks any problems that might be happening outside of what you already expecte... | [
1
] | [] | [] | [
"django",
"list",
"python"
] | stackoverflow_0001183031_django_list_python.txt |
Q:
Why isn't Django returning a datetime field from the database?
For my first Django app, I'm trying to write a simple quote collection site (think bash.org), with really simple functionality, just to get my feet wet. I'm using sqlite as my database, since it's the easiest to setup.
Here's my only model right now:
... | Why isn't Django returning a datetime field from the database? | For my first Django app, I'm trying to write a simple quote collection site (think bash.org), with really simple functionality, just to get my feet wet. I'm using sqlite as my database, since it's the easiest to setup.
Here's my only model right now:
class Quote(models.Model):
text = models.TextField();
upvote... | [
"As Adam Bernier mentioned, you're misspelling quote\n",
"I'm not sure what you're doing with that date: filter -- what happens if you replace it with something simple, such as date:\"D d M Y?\n",
"I believe that django.views.generic.list_detail.object_detail uses a variable named object_id, not id.\n urlpat... | [
2,
0,
0
] | [] | [] | [
"datetime",
"django",
"python",
"sqlite"
] | stackoverflow_0001181145_datetime_django_python_sqlite.txt |
Q:
In Python 2.4, how can I strip out characters after ';'?
Let's say I'm parsing a file, which uses ; as the comment character. I don't want to parse comments. So if I a line looks like this:
example.com. 600 IN MX 8 s1b9.example.net ; hello!
Is there an easier/more-elegant way to strip c... | In Python 2.4, how can I strip out characters after ';'? | Let's say I'm parsing a file, which uses ; as the comment character. I don't want to parse comments. So if I a line looks like this:
example.com. 600 IN MX 8 s1b9.example.net ; hello!
Is there an easier/more-elegant way to strip chars out other than this:
rtr = ''
for line in file:
trig ... | [
"I'd recommend saying\nline.split(\";\")[0]\n\nwhich will give you a string of all characters up to but not including the first \";\" character. If no \";\" character is present, then it will give you the entire line.\n",
"just do a split on the line by comment then get the first element\neg\nline.split(\";\")[0... | [
134,
19,
4,
4,
3,
1,
1
] | [
"I have not tested this with python but I use similar code else where.\nimport re\ncontent = open(r'c:\\temp\\test.txt', 'r').read()\ncontent = re.sub(\";.+\", \"\\n\")\n\n"
] | [
-3
] | [
"python",
"python_2.4",
"string"
] | stackoverflow_0001178335_python_python_2.4_string.txt |
Q:
Interactive python
Possible Duplicate:
How to save a Python interactive session?
Can i save everything I type into a python session when "brain storming"?
For instance, not just default variables but of course even overriding the shell. I of course mean by invoking the actual python executable.
I seriously hope ... | Interactive python |
Possible Duplicate:
How to save a Python interactive session?
Can i save everything I type into a python session when "brain storming"?
For instance, not just default variables but of course even overriding the shell. I of course mean by invoking the actual python executable.
I seriously hope this is not a stupid qu... | [
"iPython (as suggested in another answer) is indeed a good suggestion, but if you prefer the good old Python interactive interpreter it's not too hard to do it there either. Set your environment variable PYTHONSTARTUP to point to a file that contains, for example:\nimport atexit\nimport readline\ntry:\n readline... | [
9,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001180802_python.txt |
Q:
To SHA512-hash a password in MySQL database by Python
This question is based on the answer.
I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.
How can you hash your password in a MySQL database by Python?
A:
As the documentation says... | To SHA512-hash a password in MySQL database by Python | This question is based on the answer.
I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.
How can you hash your password in a MySQL database by Python?
| [
"As the documentation says you should use hashlib library not the sha since python 2.5.\nIt is pretty easy to do make a hash.\nhexhash = hashlib.sha512(\"some text\").hexdigest()\n\nThis hex number will be easy to store in a database.\n",
"If you're storing passwords in a database, a recommended article to read i... | [
12,
7,
4,
1
] | [] | [] | [
"database",
"hash",
"mysql",
"python"
] | stackoverflow_0001183161_database_hash_mysql_python.txt |
Q:
Comparing dissimilar types in python
First the code:
class myClass(object):
def __cmp__(self, other):
return cmp(type(self), type(other)) or cmp(self.__something, other.__something)
Does this produce the same ordering as for other types in python? Is there a correct idiom
for this?
Related question: ... | Comparing dissimilar types in python | First the code:
class myClass(object):
def __cmp__(self, other):
return cmp(type(self), type(other)) or cmp(self.__something, other.__something)
Does this produce the same ordering as for other types in python? Is there a correct idiom
for this?
Related question:
A bit of looking around on google I found... | [
"Python 2 unfortunately did support such \"alien\" comparisons (fortunately abrogated in Python 3). It's NOT easy to emulate the built-ins behavior because it has so many special cases, for example float and int compare directly (no type-comparison override as you have it coded) but complex makes any comparison (ex... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001175529_python.txt |
Q:
Permalinks with Russian/Cyrillic news articles
I basically am working with an oldschool php cms based site in Russian, one of the many new functionalities requested is permalinks.
As of now, currently the website just uses the standard non-mvc 'article.php?id=50'. I was browsing the Russian wiki and this was reall... | Permalinks with Russian/Cyrillic news articles | I basically am working with an oldschool php cms based site in Russian, one of the many new functionalities requested is permalinks.
As of now, currently the website just uses the standard non-mvc 'article.php?id=50'. I was browsing the Russian wiki and this was really the only Russian site I've seen that made use of n... | [
"The current convention is to encode URLs in UTF-8, and then URL-escape (i.e. %-escape) them:\npy> urllib.quote(u\"articles/2009/Заглавная_страница\".encode(\"utf-8\"))\n'articles/2009/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0'\n\nAfter this, there won't... | [
2
] | [] | [] | [
"model_view_controller",
"mysql",
"python"
] | stackoverflow_0001183956_model_view_controller_mysql_python.txt |
Q:
why __builtins__ is both module and dict
I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the __builtins__ module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main sc... | why __builtins__ is both module and dict | I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the __builtins__ module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this:
if isinst... | [
"I think you want the __builtin__ module (note the singular).\nSee the docs:\n\n27.3. __builtin__ — Built-in objects\nCPython implementation detail: Most modules have the name __builtins__ (note the 's') made available as part of their globals. The value of __builtins__ is normally either this module or the value o... | [
17
] | [] | [] | [
"built_in",
"python",
"python_module"
] | stackoverflow_0001184016_built_in_python_python_module.txt |
Q:
Storing files for testbin/pastebin in Python
I'm basically trying to setup my own private pastebin where I can save html files on my private server to test and fool around - have some sort of textarea for the initial input, save the file, and after saving I'd like to be able to view all the files I saved.
I'm tryi... | Storing files for testbin/pastebin in Python | I'm basically trying to setup my own private pastebin where I can save html files on my private server to test and fool around - have some sort of textarea for the initial input, save the file, and after saving I'd like to be able to view all the files I saved.
I'm trying to write this in python, just wondering what th... | [
"I wrote something similar a while back in Django to test jQuery snippets. See:\nhttp://jquery.nodnod.net/\nI have the code available on GitHub at http://github.com/dz/jquerytester/tree/master if you're curious.\nIf you're using straight Python, there are a couple ways to approach naming:\n\nIf storing as files, a... | [
1,
1,
0
] | [] | [] | [
"python",
"web_applications"
] | stackoverflow_0001184116_python_web_applications.txt |
Q:
How does one encode and decode a string with Python for use in a URL?
I have a string like this:
String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ]
I would like to encrypt String A to be used in a clean URL. something like this:
String B: [ cYdfkeYss4543423sdfHsaaZ ]
Is there a encode API in python, ... | How does one encode and decode a string with Python for use in a URL? | I have a string like this:
String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ]
I would like to encrypt String A to be used in a clean URL. something like this:
String B: [ cYdfkeYss4543423sdfHsaaZ ]
Is there a encode API in python, given String A, it returns String B?
Is there a decode API in python, given... | [
"note that theres a huge difference between encoding and encryption.\nif you want to send sensitive data, then dont use the encoding mentioned above ;)\n",
"One way of doing the encode/decode is to use the package base64, for an example:\nimport base64\nimport sys\n\nencoded = base64.b64encode(sys.stdin.read())\n... | [
13,
9,
5,
5,
5,
2,
2,
1
] | [] | [] | [
"clean_urls",
"hash",
"python",
"string",
"urlencode"
] | stackoverflow_0000875771_clean_urls_hash_python_string_urlencode.txt |
Q:
python string search replace
SSViewer::set_theme('bullsorbit');
this my string. I want search in string "SSViewer::set_theme('bullsorbit'); " and replace 'bullsorbit' with another string. 'bullsorbit' string is dynamically changing.
A:
Not in a situation to be able to test this so you may need to fiddle with t... | python string search replace | SSViewer::set_theme('bullsorbit');
this my string. I want search in string "SSViewer::set_theme('bullsorbit'); " and replace 'bullsorbit' with another string. 'bullsorbit' string is dynamically changing.
| [
"Not in a situation to be able to test this so you may need to fiddle with the Regular Expression (they may be errors in it.)\nimport re\nre.sub(\"SSViewer::set_theme\\('[a-z]+'\\)\", \"SSViewer::set_theme('whatever')\", my_string)\n\nIs this what you want?\nJust tested it, this is some sample output:\nmy_string = ... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"replace",
"search",
"string"
] | stackoverflow_0001184119_python_replace_search_string.txt |
Q:
Graduation Project
I require to do a project as a part of my final year of engineering graduation studies.Can you suggest some projects pertaining to distributed systems and artificial intelligence together and which require python,c or c++ for programming?
Note:-Please suggest a project that is attainable for a g... | Graduation Project | I require to do a project as a part of my final year of engineering graduation studies.Can you suggest some projects pertaining to distributed systems and artificial intelligence together and which require python,c or c++ for programming?
Note:-Please suggest a project that is attainable for a group of 2 students.
| [
"Perhaps improve computer opponents for Go?\nhttp://en.wikipedia.org/wiki/Go_(game)\n",
"How about a decision process that uses mapreduce, and gets more efficient at choosing the answer each time?\n",
"And what about participating in NetFlix competition?\n",
"Orange is an comprehensive data mining and machine... | [
4,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"artificial_intelligence",
"c++",
"distributed",
"python",
"system"
] | stackoverflow_0001184018_artificial_intelligence_c++_distributed_python_system.txt |
Q:
Python: extending int and MRO for __init__
In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:
class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs ... | Python: extending int and MRO for __init__ | In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:
class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
However while calling C(3) works fine, ... | [
"The docs for the Python data model advise using __new__:\nobject.new(cls[, ...])\n\nnew() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.\n\nSomething like ... | [
7,
3,
3
] | [] | [] | [
"class_design",
"overriding",
"python"
] | stackoverflow_0001184337_class_design_overriding_python.txt |
Q:
python+encryption: Encrypting session key using public key
I want to encrypt the session key using the public key. How does the PGP software do this?
Can somebody specify the procedure or function of encryption in Python?
A:
There's also the PyCrypto module that looks exactly like what you are looking for: http:... | python+encryption: Encrypting session key using public key | I want to encrypt the session key using the public key. How does the PGP software do this?
Can somebody specify the procedure or function of encryption in Python?
| [
"There's also the PyCrypto module that looks exactly like what you are looking for: http://www.dlitz.net/software/pycrypto/ the API docs are here: http://www.dlitz.net/software/pycrypto/apidoc/ and some nice docs with basic examples of encrypting/decrypting here: http://www.dlitz.net/software/pycrypto/doc/.\nI'll c... | [
3,
1,
0
] | [] | [] | [
"encryption",
"public_key",
"python"
] | stackoverflow_0001057768_encryption_public_key_python.txt |
Q:
Is there a library which handles the parsing of BIND zone files in Python?
This is related to a similar question about BIND, but in this case I'm trying to see if there's any easy way to parse various zone files into a dictionary, list, or some other manageable data structure, with the final goal being committing ... | Is there a library which handles the parsing of BIND zone files in Python? | This is related to a similar question about BIND, but in this case I'm trying to see if there's any easy way to parse various zone files into a dictionary, list, or some other manageable data structure, with the final goal being committing the data to a database.
I'm using BIND 8.4.7 and Python 2.4. I may be able to c... | [
"ISTM, easyzone might meet your needs. It sits on top of dnspython, which would be an alternative API.\n"
] | [
1
] | [] | [] | [
"bind",
"database",
"parsing",
"python",
"python_2.4"
] | stackoverflow_0001184803_bind_database_parsing_python_python_2.4.txt |
Q:
To make a plan for my first MySQL project
I need to complete the plan of a ask-a-question site for my uni. in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.
Questions about the project which do not fit here
to make efficie... | To make a plan for my first MySQL project | I need to complete the plan of a ask-a-question site for my uni. in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.
Questions about the project which do not fit here
to make efficient tables
to improve a relation figure
to impro... | [
"First, this is all a lot to work with in a week. But here it goes.\nTools for the backend:\n\nSQLAlchemy - This is an ORM toolkit that is plenty powerful for most smaller tasks when using a MySQL database built with Python. To my knowledge, it is the best for this job. http://www.sqlalchemy.org/\nDjango - \"...is... | [
4,
2,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001168701_mysql_python.txt |
Q:
Creating child frames of main frame in wxPython
I am trying create a new frame in wxPython that is a child of the main frame so that when the main frame is closed, the child frame will also be closed.
Here is a simplified example of the problem that I am having:
#! /usr/bin/env python
import wx
class App(wx.App)... | Creating child frames of main frame in wxPython | I am trying create a new frame in wxPython that is a child of the main frame so that when the main frame is closed, the child frame will also be closed.
Here is a simplified example of the problem that I am having:
#! /usr/bin/env python
import wx
class App(wx.App):
def OnInit(self):
frame = MainFrame()
... | [
"class AboutFrame(wx.Frame):\n\n title = \"About this program\"\n\n def __init__(self):\n wx.Frame.__init__(self, wx.GetApp().TopWindow, title=self.title)\n\n"
] | [
10
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001185156_python_wxpython.txt |
Q:
Which python tools for building a database-backed webapp
I am completing my first database project which aims to build a simple discussion site.
The answers which I got at Superuser suggests me that Python is difficult to use in building a database webapp without any other tools.
Which other tools would you use?
... | Which python tools for building a database-backed webapp | I am completing my first database project which aims to build a simple discussion site.
The answers which I got at Superuser suggests me that Python is difficult to use in building a database webapp without any other tools.
Which other tools would you use?
| [
"Sorry, your question makes no sense.\n\nYou say you can't use Django because you have to write your SQL queries yourself. Firstly, why do you have to? And secondly, Django certainly doesn't stop you.\nEven though you say you want to write your SQL queries yourself, you then ask what ORM is best. An ORM replaces th... | [
5,
2,
2,
1,
1
] | [] | [] | [
"cheetah",
"orm",
"python"
] | stackoverflow_0001185248_cheetah_orm_python.txt |
Q:
memcache entities without ReferenceProperty
I have a list of entities which I want to store in the memcache. The
problem is that I have large Models referenced by their
ReferenceProperty which are automatically also stored in the memcache.
As a result I'm exceeding the size limit for objects stored in
memcache... | memcache entities without ReferenceProperty | I have a list of entities which I want to store in the memcache. The
problem is that I have large Models referenced by their
ReferenceProperty which are automatically also stored in the memcache.
As a result I'm exceeding the size limit for objects stored in
memcache.
Is there any possibility to prevent the Refere... | [
"For large entities, you might want to manually handle the loading of the related entities by storing the keys of the large entities as something other than a ReferenceProperty. That way you can choose when to load the large entity and when not to. Just use a long property store ids or a string property to store k... | [
1,
0
] | [] | [] | [
"google_app_engine",
"memcached",
"python"
] | stackoverflow_0001152690_google_app_engine_memcached_python.txt |
Q:
Error importing external library within Django template tag library
So I'm attempting to write a Django reusable app that provides a method for displaying your Twitter feed on your page. I know well that it already exists 20 times. It's an academic exercise. :)
Directory structure is pretty simple:
myproject
|__ ... | Error importing external library within Django template tag library | So I'm attempting to write a Django reusable app that provides a method for displaying your Twitter feed on your page. I know well that it already exists 20 times. It's an academic exercise. :)
Directory structure is pretty simple:
myproject
|__ __init__.py
|__ manage.py
|__ settings.py
|__ myapp
|__ __init__... | [
"I solve this kind of problem (shipping libraries that are dependencies for my overall project) in the following way. First, I create an \"ext\" directory in the root of my project (in your case that would be myproject/ext). Then I place dependencies such as feedparser in that ext directory - myproject/ext/feedpars... | [
5,
2
] | [] | [] | [
"django",
"feedparser",
"python",
"templatetags"
] | stackoverflow_0001185084_django_feedparser_python_templatetags.txt |
Q:
merge sort implementation to sort by string length - python
I've implemented what I believe to be a merge sort algorithm in python. I've never programmed in Python before, so I used several resources with commands that seemed foreign to me, to gain a better understanding.
However, I've also never implemented me... | merge sort implementation to sort by string length - python | I've implemented what I believe to be a merge sort algorithm in python. I've never programmed in Python before, so I used several resources with commands that seemed foreign to me, to gain a better understanding.
However, I've also never implemented merge sort in the first place, so I'm not sure if I've even impleme... | [
"Don't name variables \"list\". That's the name of Python's array type, so using a variable by the same name is confusing.\nWhen you return from a conditional, you don't need to sitck the rest of the function in an else block.\ndef mergesort(list):\n if len(list) < 2:\n return list\n middle = len(list... | [
3,
2
] | [] | [] | [
"algorithm",
"mergesort",
"python"
] | stackoverflow_0001185388_algorithm_mergesort_python.txt |
Q:
Using a caesarian cipher on a string of text in python?
I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters.
For example, inputing abcdefg will give me cdefghi (if x is 2).
A:
M... | Using a caesarian cipher on a string of text in python? | I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters.
For example, inputing abcdefg will give me cdefghi (if x is 2).
| [
"My first version:\n>>> key = 2\n>>> msg = \"abcdefg\"\n>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )\n'cdefghi'\n>>> msg = \"uvwxyz\"\n>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )\n'wxyzab'\n\n(Of course it works as expected only if msg is lowe... | [
9,
5,
3,
2,
1
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0001185775_encryption_python.txt |
Q:
How can I execute CGI files from PHP?
I'm trying to make a web app that will manage my Mercurial repositories for me.
I want it so that when I tell it to load repository X:
Connect to a MySQL server and make sure X exists.
Check if the user is allowed to access the repository.
If above is true, get the location o... | How can I execute CGI files from PHP? | I'm trying to make a web app that will manage my Mercurial repositories for me.
I want it so that when I tell it to load repository X:
Connect to a MySQL server and make sure X exists.
Check if the user is allowed to access the repository.
If above is true, get the location of X from a mysql server.
Run a hgweb cgi sc... | [
"You can run shell scripts from within PHP. There are various ways to do it, and complications with some hosts not providing the proper permissions, all of which are well-documented on php.net. That said, the simplest way is to simply enclose your command in backticks. So, to unzip a file, I could say:\n`unzip /pat... | [
2,
2,
0
] | [] | [] | [
"cgi",
"mercurial",
"php",
"python"
] | stackoverflow_0001185867_cgi_mercurial_php_python.txt |
Q:
Can I use C++ features while extending Python?
The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?
A:
It doesn't m... | Can I use C++ features while extending Python? | The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?
| [
"It doesn't matter whether your implementation of the hook functions is implemented in C or in C++. In fact, I've already seen some Python extensions which make active use of C++ templates and even the Boost library. No problem. :-)\n",
"The boost folks have a nice automated way to do the wrapping of C++ code for... | [
9,
3,
2,
1
] | [] | [] | [
"c",
"c++",
"python",
"python_c_api",
"python_c_extension"
] | stackoverflow_0001185878_c_c++_python_python_c_api_python_c_extension.txt |
Q:
Spoofing the origination IP address of an HTTP request
This only needs to work on a single subnet and is not for malicious use.
I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come ... | Spoofing the origination IP address of an HTTP request | This only needs to work on a single subnet and is not for malicious use.
I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools pro... | [
"This is a misunderstanding of HTTP. The HTTP protocol is based on top of TCP. The TCP protocol relies on a 3 way handshake to initialize requests.\n\nNeedless to say, if you spoof your originating IP address, you will never get past the synchronization stage and no HTTP information will be sent (the server can't s... | [
50,
7,
5,
1,
1
] | [] | [] | [
"http",
"networking",
"python",
"sockets",
"urllib2"
] | stackoverflow_0001180878_http_networking_python_sockets_urllib2.txt |
Q:
Python: is os.read() / os.write() on an os.pipe() threadsafe?
Consider:
pipe_read, pipe_write = os.pipe()
Now, I would like to know two things:
(1) I have two threads. If I guarantee that only one is reading os.read(pipe_read,n) and the other is only writing os.write(pipe_write), will I have any problem, even if ... | Python: is os.read() / os.write() on an os.pipe() threadsafe? | Consider:
pipe_read, pipe_write = os.pipe()
Now, I would like to know two things:
(1) I have two threads. If I guarantee that only one is reading os.read(pipe_read,n) and the other is only writing os.write(pipe_write), will I have any problem, even if the two threads do it simultaneously? Will I get all data that was ... | [
"os.read and os.write on the two fds returned from os.pipe is threadsafe, but you appear to demand more than that. Sub (1), yes, there is no \"atomicity\" guarantee for sinle reads or writes -- the scenario you depict (a single short write ends up producing two reads) is entirely possible. (In general, os.whatever ... | [
8
] | [] | [] | [
"multithreading",
"pipe",
"python",
"thread_safety"
] | stackoverflow_0001185660_multithreading_pipe_python_thread_safety.txt |
Q:
Customizing modelformset fields in Django
I'd like to use the following form class in a modelformset. It takes a maps parameter and customizes the form fields accordingly.
class MyModelForm(forms.ModelForm):
def __init__(self, maps, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
... | Customizing modelformset fields in Django | I'd like to use the following form class in a modelformset. It takes a maps parameter and customizes the form fields accordingly.
class MyModelForm(forms.ModelForm):
def __init__(self, maps, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
#customize fields here
class Meta:
... | [
"Keep in mind that Django uses class definition as a sort of DSL to define various things. As such, instantiating at places where it expects the class object will break things.\nOne approach is to create your own form factory. Something like:\n def mymodelform_factory(maps):\n class MyModelForm(forms.ModelFor... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001186753_django_python.txt |
Q:
Real world guide on using and/or setting up REST web services?
I've only used XML RPC and I haven't really delved into SOAP but I'm trying to find a good comprehensive guide, with real world examples or even a walkthrough of some minimal REST application.
I'm most comfortable with Python/PHP.
A:
I like the examp... | Real world guide on using and/or setting up REST web services? | I've only used XML RPC and I haven't really delved into SOAP but I'm trying to find a good comprehensive guide, with real world examples or even a walkthrough of some minimal REST application.
I'm most comfortable with Python/PHP.
| [
"I like the examples in the Richardson & Ruby book, \"RESTful Web Services\" from O'Reilly.\n",
"There is a good example with the Google App Engine Documentation. http://code.google.com/appengine/articles/rpc.html. It also talks you through some security aspects of doing REST\n",
"Here are a few links:\n\nhttp:... | [
1,
1,
1
] | [] | [] | [
"php",
"python",
"rest",
"soap",
"xml"
] | stackoverflow_0001186839_php_python_rest_soap_xml.txt |
Q:
Python SOAPpy Errors
Below is my Python code:
Service part
class Test:
def hello():
return "Hello World"
Server Part
import SOAPpy
from first_SOAP import *
host = "127.0.0.1"
port = 5551
SOAPpy.Config.debug = 1
server = SOAPpy.SOAPServer((host, port))
server.registerKWFunction(Test.hello)
print "Serv... | Python SOAPpy Errors | Below is my Python code:
Service part
class Test:
def hello():
return "Hello World"
Server Part
import SOAPpy
from first_SOAP import *
host = "127.0.0.1"
port = 5551
SOAPpy.Config.debug = 1
server = SOAPpy.SOAPServer((host, port))
server.registerKWFunction(Test.hello)
print "Server Runing"
server.serve_f... | [
"Do you really want to make test() a class method? I suggest you change your code like this.\nclass Test:\n def hello(self):\n return \"Hello World\"\n\nThen you must create an instance of the Test class and register:\nserver.registerObject(Test())\n\nThen the client can access the hello() method like this:\npr... | [
0
] | [] | [] | [
"python",
"soappy"
] | stackoverflow_0001186922_python_soappy.txt |
Q:
How to install a module as an egg under IronPython?
Maybe, it is a stupid question but I can't use python eggs with IronPython.
I would like to test with IronPython 2.0.2 one module that I've developped. This modules is pure python. It works ok with python 2.6 and is installed as a python egg thanks to setuptools.... | How to install a module as an egg under IronPython? | Maybe, it is a stupid question but I can't use python eggs with IronPython.
I would like to test with IronPython 2.0.2 one module that I've developped. This modules is pure python. It works ok with python 2.6 and is installed as a python egg thanks to setuptools.
I thought that the process for installing my module unde... | [
"AFAIK it's still not possible - it's work in progress. See this post, for example. IronPython's main strength is in integration with the .NET ecosystem - it's not a drop-in replacement for CPython. See this post for some other limitations of IronPython.\n"
] | [
1
] | [] | [] | [
"egg",
"ironpython",
"python"
] | stackoverflow_0001187110_egg_ironpython_python.txt |
Q:
In Python, how to tell if being called by exception handling code?
I would like to write a function in Python (2.6) that can determine if it is being called from exception handling code somewhere up the stack.
This is for a specialized logging use. In python's logging module, the caller has to explicitly specify t... | In Python, how to tell if being called by exception handling code? | I would like to write a function in Python (2.6) that can determine if it is being called from exception handling code somewhere up the stack.
This is for a specialized logging use. In python's logging module, the caller has to explicitly specify that exception information should be logged (either by calling logger.exc... | [
"If you clear the exception using sys.exc_clear in your exception handlers, then sys.exc_info should work for you. For example: If you run the following script:\nimport sys\n\ntry:\n 1 / 0\nexcept:\n print sys.exc_info()\n sys.exc_clear()\nprint sys.exc_info()\n\nYou should see this output:\n\n(, ZeroDivis... | [
2,
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0001187102_exception_python.txt |
Q:
How to make the program run again after unexpected exit in Python?
I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.
What's the techniques that I can use to make the program run again?
A:
You can use sys.exit() to tell that the program exited abnormal... | How to make the program run again after unexpected exit in Python? | I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.
What's the techniques that I can use to make the program run again?
| [
"You can use sys.exit() to tell that the program exited abnormally (generally, 1 is returned in case of error).\nYour Python script could look something like this:\nimport sys\n\ndef main():\n # ...\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n print >> sys.stderr, ... | [
5,
1,
0
] | [] | [] | [
"irc",
"python"
] | stackoverflow_0001187653_irc_python.txt |
Q:
Python: update a list of tuples... fastest method
This question is in relation to another question asked here:
Sorting 1M records
I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of th... | Python: update a list of tuples... fastest method | This question is in relation to another question asked here:
Sorting 1M records
I have since figured out the problem I was having with sorting. I was sorting items from a dictionary into a list every time I updated the data. I have since realized that a lot of the power of Python's sort resides in the fact that it so... | [
"You're scanning through all n records. You could instead do a binary search, which would be O(log(n)) instead of O(n). You can use the bisect module to do this.\n",
"Since apparently you don't care about the ending value of self.sorted_records actually being sorted (you have values in order 1, 45, 20, 76 -- that... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001186501_python.txt |
Q:
How to specify which eth interface Django test server should listen on?
As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server s... | How to specify which eth interface Django test server should listen on? | As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use?
-- Added --
The network configuration is here.
I'm connecting to t... | [
"I think the OP is referring to having multiple interfaces configured on the test machine.\nYou can specify the IP address that Django will bind to as follows:\n# python manage.py runserver 0.0.0.0:8000\n\nThis would bind Django to all interfaces on port 8000. You can pass any active IP address in place of 0.0.0.0,... | [
45,
2,
1
] | [] | [] | [
"django",
"ethernet",
"networking",
"python"
] | stackoverflow_0001188205_django_ethernet_networking_python.txt |
Q:
Why Python omits attribute in the SOAP message?
I have a web service that returns following type:
<xsd:complexType name="TaggerResponse">
<xsd:sequence>
<xsd:element name="msg" type="xsd:string"></xsd:element>
</xsd:sequence>
<xsd:attribute name="status" type="tns:Status"></xsd:attribute>
</xsd... | Why Python omits attribute in the SOAP message? | I have a web service that returns following type:
<xsd:complexType name="TaggerResponse">
<xsd:sequence>
<xsd:element name="msg" type="xsd:string"></xsd:element>
</xsd:sequence>
<xsd:attribute name="status" type="tns:Status"></xsd:attribute>
</xsd:complexType>
The type contains one element (msg) an... | [
"The response example you posted (the actual XML coming back from the WS request) does not have the value in it you are looking for! I would suggest this is why SOAPpy cannot return it to you.\nIf it is a case of making your code have consistent behaviour in cases where the value is returned and when it isn't then... | [
1
] | [] | [] | [
"python",
"soap",
"soappy",
"web_services",
"wsdl"
] | stackoverflow_0001188367_python_soap_soappy_web_services_wsdl.txt |
Q:
Writing in file's actual position in Python
I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:
"123456789" (before)
"123\n456\n789" (after)
I've tried with this:
f =... | Writing in file's actual position in Python | I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:
"123456789" (before)
"123\n456\n789" (after)
I've tried with this:
f = open(file, "r+")
f.write("123456789")
f.seek(3, ... | [
"I don't think there is any way to do that in the way you are trying to: you would have to read in to the end of the file from the position you want to insert, then write your new character at the position you wish it to be, then write the original data back after it. This is the same way things would work in C or... | [
7,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0001188214_file_python.txt |
Q:
Sensible python source line wrapping for printout
I am working on a latex document that will require typesetting significant amounts of python source code. I'm using pygments (the python module, not the online demo) to encapsulate this python in latex, which works well except in the case of long individual lines -... | Sensible python source line wrapping for printout | I am working on a latex document that will require typesetting significant amounts of python source code. I'm using pygments (the python module, not the online demo) to encapsulate this python in latex, which works well except in the case of long individual lines - which simply continue off the page. I could manually w... | [
"You might want to extend your current approach a bit, but using the tokenize module from the standard library to determine where to put your line breaks. That way you can see the actual tokens (COMMENT, STRING, etc.) of your source code rather than just the whitespace-separated words.\nHere is a short example of ... | [
3,
2,
1
] | [] | [] | [
"code_formatting",
"latex",
"pygments",
"python",
"syntax_highlighting"
] | stackoverflow_0001035721_code_formatting_latex_pygments_python_syntax_highlighting.txt |
Q:
Python POST ordered params
I have a web service that accepts passed in params using http POST but in a specific order, eg (name,password,data). I have tried to use httplib but all the Python http POST libraries seem to take a dictionary, which is an unordered data structure. Any thoughts on how to http POST para... | Python POST ordered params | I have a web service that accepts passed in params using http POST but in a specific order, eg (name,password,data). I have tried to use httplib but all the Python http POST libraries seem to take a dictionary, which is an unordered data structure. Any thoughts on how to http POST params in order for Python?
Thanks!
| [
"Why would you need a specific order in the POST parameters in the first place? As far as I know there are no requirements that POST parameter order is preserved by web servers.\nEvery language I have used, has used a dictionary type object to hold these parameters as they are inherently key/value pairs.\n"
] | [
2
] | [] | [] | [
"http",
"python"
] | stackoverflow_0001188737_http_python.txt |
Q:
Reusing a Django app within a single project
In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could... | Reusing a Django app within a single project | In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, ... | [
"What's the actual difference between blogs and news? Perhaps that difference ought to be part of the blog/news app and you include it just once.\nIf you have a blog page with blog entries and a news page with news entries and the only difference is a field in the database (kind_of_item = \"blog\" vs. kind_of_item... | [
3,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001188052_django_python.txt |
Q:
Python: encryption as means to prevent data tampering
Many of my company's clients use our data acquisition software in a research basis. Due to the nature of research in general, some of the clients ask that data is encrypted to prevent tampering -- there could be serious ramifications if their data was shown to... | Python: encryption as means to prevent data tampering | Many of my company's clients use our data acquisition software in a research basis. Due to the nature of research in general, some of the clients ask that data is encrypted to prevent tampering -- there could be serious ramifications if their data was shown to be falsified.
Some of our binary software encrypts output ... | [
"As a general principle, you don't want to use encryption to protect against tampering, instead you want to use a digital signature. Encryption gives you confidentiality, but you are after integrity.\nCompute a hash value over your data and either store the hash value in a place where you know it cannot be tampered... | [
13,
3,
0
] | [] | [] | [
"data_integrity",
"encryption",
"python",
"tampering"
] | stackoverflow_0001178789_data_integrity_encryption_python_tampering.txt |
Q:
Make SetupTools/easy_install aware of installed Debian Packages?
I'm installing an egg with easy_install which requires ruledispatch. It isn't available in PyPI, and when I use PEAK's version it FTBFS. There is, however, a python-dispatch package which provides the same functionality as ruledispatch. How can I get... | Make SetupTools/easy_install aware of installed Debian Packages? | I'm installing an egg with easy_install which requires ruledispatch. It isn't available in PyPI, and when I use PEAK's version it FTBFS. There is, however, a python-dispatch package which provides the same functionality as ruledispatch. How can I get easy_install to stop trying to install ruledispatch, and to allow it ... | [
"The path least fiddly is likely:\n\neasy_install --no-deps\nLook at the egginfo of what you just installed\nInstall all dependencies except ruledispatch by hand\nOptionally, prod the people responsible to list their stuff on pypi / not have dependencies that the package installer can't possibly satisfy / use depen... | [
3
] | [] | [] | [
"debian",
"easy_install",
"etch",
"python",
"setuptools"
] | stackoverflow_0001188812_debian_easy_install_etch_python_setuptools.txt |
Q:
SharePoint via SOAP using Python
I have been following the solution noted here - as this is exactly what I need to achieve;
how can i use sharepoint (via soap?) from python?
however when I run one of the last lines of this code I get the following error;
>>> client = SoapClient(url, {'opener' : opener})
Traceback ... | SharePoint via SOAP using Python | I have been following the solution noted here - as this is exactly what I need to achieve;
how can i use sharepoint (via soap?) from python?
however when I run one of the last lines of this code I get the following error;
>>> client = SoapClient(url, {'opener' : opener})
Traceback (most recent call last):
File "<stdin>... | [
"According to https://fedorahosted.org/suds/browser/trunk/suds/client.py?rev=504\n434 class SoapClient:\n...\n445 \"\"\"\n446 \n447 def __init__(self, client, method):\n448 \"\"\"\n449 @param client: A suds client.\n450 @type client: L{Client}\n451 ... | [
1
] | [] | [] | [
"python",
"sharepoint",
"soap",
"suds"
] | stackoverflow_0001078593_python_sharepoint_soap_suds.txt |
Q:
Why the trailing slash in the web service is so important?
I was testing a web service in PHP and Python. The address of the web service was, let's say, http://my.domain.com/my/webservice. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python u... | Why the trailing slash in the web service is so important? | I was testing a web service in PHP and Python. The address of the web service was, let's say, http://my.domain.com/my/webservice. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.
Below is the code I used to communic... | [
"They're different URLs. http://my.domain.com/my/webservice implies a file webservice in the my folder. http://my.domain.com/my/webservice/ implies the default document inside the my/webservice folder.\nMany webservers will automatically correct such URLs, but it is not required for them to do so.\n",
"Because th... | [
20,
3,
3,
2,
0
] | [] | [] | [
"php",
"python",
"soappy",
"wsdl"
] | stackoverflow_0001188927_php_python_soappy_wsdl.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.