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:
Issues when writing a medium/large system
There is some hype with languages like Python (that I like very much) and Ruby but I was writing a medium-size system in Python and feel the lack of some tools that I would have if I was using Java: Eclipse features, JUnit integration and some language-features like catchi... | Issues when writing a medium/large system | There is some hype with languages like Python (that I like very much) and Ruby but I was writing a medium-size system in Python and feel the lack of some tools that I would have if I was using Java: Eclipse features, JUnit integration and some language-features like catching some errors in compile time.
Some people say... | [
"You make a valid point in saying that Java is more suited to enterprise software. That's really where Java shines: it works very well for enterprise programming.\nHowever, your gripes about the tools in Python and Ruby are unfounded. PyDev for Eclipse takes full advantage of the same features that you would enjoy ... | [
1,
1,
0
] | [] | [] | [
"enterprise",
"java",
"python",
"ruby",
"system"
] | stackoverflow_0004083554_enterprise_java_python_ruby_system.txt |
Q:
Removing Spaces from Strings in Python 3.x
I need to transform the string:
"There are 6 spaces in this string."
to:
"Thereare6spacesinthisstring."
A:
You can use replace
string = "There are 6 spaces in this string"
string = string.replace(' ', '')
A:
new = "There are 6 spaces in this old_string.".replace(' ',... | Removing Spaces from Strings in Python 3.x | I need to transform the string:
"There are 6 spaces in this string."
to:
"Thereare6spacesinthisstring."
| [
"You can use replace\nstring = \"There are 6 spaces in this string\"\nstring = string.replace(' ', '')\n\n",
"new = \"There are 6 spaces in this old_string.\".replace(' ', '')\n\nIf you want to strip all whitespace, including tabs:\nnew = ''.join( old_string.split() )\n\n",
"You can use replace() :\nprint(strin... | [
15,
4,
2
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0004083772_python_python_3.x_string.txt |
Q:
Is it possible to use matplotlib and pylab to create filled line graph?
I was wondering if it is possible to create a filled line graph, like below, using matplotlib?
I have matplotlib 0.91.2 and pylab installed.
http://test1.xsports.co.nz/media/Forecast.png
A:
This example in the matplotlib gallery looks li... | Is it possible to use matplotlib and pylab to create filled line graph? | I was wondering if it is possible to create a filled line graph, like below, using matplotlib?
I have matplotlib 0.91.2 and pylab installed.
http://test1.xsports.co.nz/media/Forecast.png
| [
"This example in the matplotlib gallery looks like it will do what you want - you just have to fill between the graph and the x-axis.\nAlternatively, you could use a bar graph with many single pixel bars (or whatever resolution you wanted).\nHTH\n"
] | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004083776_matplotlib_python.txt |
Q:
feature mobile phone tracking application
I would like to build a mobile phone tracking application for feature phones which have minimum of gprs connectivity. I would like a user to log in to the application and be able to see the location of their phone through google maps. Any resources or information will be h... | feature mobile phone tracking application | I would like to build a mobile phone tracking application for feature phones which have minimum of gprs connectivity. I would like a user to log in to the application and be able to see the location of their phone through google maps. Any resources or information will be highly appreciated. I would preferably use pytho... | [
"As far as I know, there is no way to get Python code running on that kind of mobile platform.\nTry looking up JavaME and/or Brew. Further, you will need the carrier and device maker to allow your app the get access to the phone's GPS information. This is not a given on the low-end devices.\nAs a first step, most... | [
1
] | [] | [] | [
"mobile",
"python",
"security"
] | stackoverflow_0004081333_mobile_python_security.txt |
Q:
clarification on comparing objects of different types
The following sentences are a cause of confusion for me(from Guido's Tutorial on python.org):
"Note that comparing objects of
different types is legal. The outcome
is deterministic but arbitrary: the
types are ordered by their name. Thus,
a list is alw... | clarification on comparing objects of different types | The following sentences are a cause of confusion for me(from Guido's Tutorial on python.org):
"Note that comparing objects of
different types is legal. The outcome
is deterministic but arbitrary: the
types are ordered by their name. Thus,
a list is always smaller than a
string, a string is always smaller
t... | [
"(1) is an int. You probably meant (1,), which is a tuple.\n",
"Please note that you should not rely upon this behavior anymore. Some built-in types cannot be compared with other built-ins, and new data model provides a way to overload comparator functionality.\n>>> set([1]) > [1]\nTraceback (most recent call las... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0004084243_python.txt |
Q:
querying relation does not give back related object in sqlalchemy
I have a very simple table(mapped as AuthToken class), consisting of a string ('token'), and a userid (foreign key to another table), with 'user' as relation ( = class User)
session.query(AuthToken.user).one() gives back the token, and the userid (a... | querying relation does not give back related object in sqlalchemy | I have a very simple table(mapped as AuthToken class), consisting of a string ('token'), and a userid (foreign key to another table), with 'user' as relation ( = class User)
session.query(AuthToken.user).one() gives back the token, and the userid (as a tuple), but not the user object.
Does anybody know why?
thanks!
| [
"You should query mapped classes, not their attributes, if you want to receive objects.\ntoken = Session.query(AuthToken).options(eagerload('user')).filter(...).one()\nuser = token.user\n\n"
] | [
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004028625_orm_python_sqlalchemy.txt |
Q:
How can I aggregate dictionaries over class hierarchy (Python)
Let's say I have the following class hierarchy:
class A(object):
_d = {}
class B(A):
_d = {'b': 1}
class C(A):
_d = {'b': 2, 'c': 3}
class D(B):
_d = {'d': 4}
Is there a way to write an @property method d on A which will return the aggregat... | How can I aggregate dictionaries over class hierarchy (Python) | Let's say I have the following class hierarchy:
class A(object):
_d = {}
class B(A):
_d = {'b': 1}
class C(A):
_d = {'b': 2, 'c': 3}
class D(B):
_d = {'d': 4}
Is there a way to write an @property method d on A which will return the aggregated dictionary over all superclasses of an object? For example, B().... | [
"Use inspect.getmro to skip any concerns with multiple inheritance and avoid the necessity of a recursive call to get all the subclasses.\nimport inspect\n\n@property\nd(self):\n res = {}\n subclasses = inspect.getmro(type(self))\n for cls in reversed(subclasses):\n res.update(gettattr(cls, 'd', {})... | [
4,
2,
2
] | [] | [] | [
"dictionary",
"inheritance",
"python"
] | stackoverflow_0004084385_dictionary_inheritance_python.txt |
Q:
A more pythonic way to write this expression?
I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first.
Here's what I got:
list_1 = []
list_2 = []
for word in words:
list_1.append(word) if word[0] == 'x' else list_2.append(word)
return sorted(list_1) + sort... | A more pythonic way to write this expression? | I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first.
Here's what I got:
list_1 = []
list_2 = []
for word in words:
list_1.append(word) if word[0] == 'x' else list_2.append(word)
return sorted(list_1) + sorted(list_2)
But I have a feeling there is a much mo... | [
">>> words = ['xoo', 'dsd', 'xdd']\n>>> sorted(words, key=lambda x: (x[0] != 'x', x))\n['xdd', 'xoo', 'dsd']\n\nExplanation: the key function returns a pair (tuple). The first element is False or True, depending on whether the first char in the string is 'x'. False sorts before True, so strings starting with 'x' wi... | [
40,
9,
6,
5,
2,
2,
1,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004077249_python_sorting.txt |
Q:
Using Cython to expose functionality to another application
I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder:
#include <windows.h>
#include <DemoPlugin.h>
/** A helper function to convert a char array into a
LPBYTE array. */
LPBYTE mes... | Using Cython to expose functionality to another application | I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder:
#include <windows.h>
#include <DemoPlugin.h>
/** A helper function to convert a char array into a
LPBYTE array. */
LPBYTE message(const char* message, long* pLen)
{
size_t length = strlen(... | [
"I think the solution is to use both. Let me explain.\nCython makes it convenient to make a fast plugin using python but inconvenient (if at all possible) to make the right \"kind\" of DLL. You would probably have to use the standalone mode so that the necessary python runtime is included and then mess with the gen... | [
3
] | [] | [] | [
"c",
"c++",
"cython",
"python"
] | stackoverflow_0004083150_c_c++_cython_python.txt |
Q:
get some substring from readline() in python with regular expression
I use tcpdump to sniff my network packet and I want to get some info out of the stored file. My file have 2 separated lines but they repeated many times.
23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 4... | get some substring from readline() in python with regular expression | I use tcpdump to sniff my network packet and I want to get some info out of the stored file. My file have 2 separated lines but they repeated many times.
23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)
192.168.98.138.49341 > 201.20.49.239.80: Flags [P.], seq 562034569:56... | [
"For the first portion, to get timestamp, id and offset.\nI am sure this is a crude regex. \n>>> import re\n>>> l = '23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)'\n>>> k = re.compile(r'^([0-9:]+\\.[0-9]+) IP \\(.* id ([0-9]+), offset ([0-9]+).*\\)')\n>>> x = k.matc... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004085121_python_regex.txt |
Q:
Python app engine: how to save a image?
This is what I got from flex 4 file reference upload:
self.request =
Request: POST /UPLOAD
Accept: text/*
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 51386
Content-Type: multipart/form-data; boundary=----------ei4cH2gL6ae0ei4ae0gL6... | Python app engine: how to save a image? | This is what I got from flex 4 file reference upload:
self.request =
Request: POST /UPLOAD
Accept: text/*
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 51386
Content-Type: multipart/form-data; boundary=----------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4
Host: localhost:8080
User-A... | [
"\nAn App Engine application cannot:\n\nwrite to the filesystem. Applications must use the App Engine\n datastore for storing persistent data.\n\n\nWhat you need to do is presenting a form with a file upload field to the user.\nWhen the form is submitted, the file is uploaded and the Blobstore creates a blob from ... | [
6
] | [] | [] | [
"google_app_engine",
"python",
"upload"
] | stackoverflow_0004054471_google_app_engine_python_upload.txt |
Q:
How to get the return value (like Ajax) using task queue on Google App Engine
I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue?
This is my code:
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengin... | How to get the return value (like Ajax) using task queue on Google App Engine | I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue?
This is my code:
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.ap... | [
"The current Task Queue API doesn't support processing return values or sending them back to the point of origin. Your appengine process isn't long-lived enough for that programming paradigm to work.\nIn your example, it looks like what you want is something like this:\n\nCreate task\nReturn AJAX code that will po... | [
2
] | [] | [] | [
"ajax",
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0004085075_ajax_google_app_engine_python_task_queue.txt |
Q:
How do I serialize this into JSON?
{
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_... | How do I serialize this into JSON? | {
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_url" : "http://farm2.static.flickr.com/1... | [
"I doubt that the problem has to do anything with datetime: in your dictionary, there is no datetime object at all, but the \"date\" key has a regular string value.\nMore likely, the problem is that it can't serialize the ObjectId class. To overcome this limitation, create a new class inheriting from JSONEncoder, a... | [
6,
1,
1
] | [] | [] | [
"datetime",
"javascript",
"json",
"python",
"serialization"
] | stackoverflow_0004085276_datetime_javascript_json_python_serialization.txt |
Q:
Echo Program Help
I need some guidance on how best to run this program. Im trying to come up with a python program that accepts input from the user and prints them out until the word quit is inputted in which the program quits but not before printing the inputs twice..
For example
2.0'
6.0
3.5
quit
2.0
6.0
3.5
2.... | Echo Program Help | I need some guidance on how best to run this program. Im trying to come up with a python program that accepts input from the user and prints them out until the word quit is inputted in which the program quits but not before printing the inputs twice..
For example
2.0'
6.0
3.5
quit
2.0
6.0
3.5
2.0
6.0
3.5
Thanks so m... | [
"[Edited answer]\nYou are converting raw_input to float and then trying to compare with a string. Shouldn't you compare first and then print. \nApart from this mistake you are doing fine!\n",
"Edited to improve visual clarity:\n1 #!/usr/bin/env python\n2 \n3 if __name__ == \"__main__\":\n4 inputs = []\n5 whil... | [
0,
-1
] | [] | [] | [
"python",
"user_input"
] | stackoverflow_0004084442_python_user_input.txt |
Q:
what is a request object in python socketserver api
In python socketserver api, as well as xmlrpcserver, there are mentioned many times the request object,for example:
SimpleXMLRPCServer.process_request(self, request, client_address):
But I cannot find any description to this request object. What is it ? where in... | what is a request object in python socketserver api | In python socketserver api, as well as xmlrpcserver, there are mentioned many times the request object,for example:
SimpleXMLRPCServer.process_request(self, request, client_address):
But I cannot find any description to this request object. What is it ? where in the python doc can I find the the expaination(it's attri... | [
"You can use the source (of SocketServer.py in this case) to answer such questions. process_request is called in _handle_request_noblock, which gets the request from get_request. What that does depends on the SocketServer subclass. For a TCPServer, you'll find that it is the result of the socket accept() call.\n"
] | [
1
] | [] | [] | [
"python",
"request",
"sockets",
"xml_rpc"
] | stackoverflow_0004085364_python_request_sockets_xml_rpc.txt |
Q:
How to check the last element of a python list?
In python I need a stack, and I'm using a list for it. In the documenation it says that you can use append() and pop() for stack operations but what about accessing the top of the stack without removing it?
How to do that in the most readable way? Because all I came... | How to check the last element of a python list? | In python I need a stack, and I'm using a list for it. In the documenation it says that you can use append() and pop() for stack operations but what about accessing the top of the stack without removing it?
How to do that in the most readable way? Because all I came up with is stack[-1:][0] which looks a bit ugly for ... | [
"No need to slice.\nstack[-1]\n\n",
"stack[-1] ist the last element\nEDIT renamed the previously list called variable (Thanks, Tim McNamara). \n"
] | [
21,
2
] | [] | [] | [
"list",
"python",
"stack"
] | stackoverflow_0004085417_list_python_stack.txt |
Q:
Problems Connecting to Minimized Signal
Problem: I have a gtk.Dialog. Whenever the 'minimize' button on the dialog is clicked, the window is destroyed.
Question: How can I connect to the minimize button of a gtk.Dialog so that I can iconify the window?
A:
Are you sure it's the minimize button? Because GTK doesn'... | Problems Connecting to Minimized Signal | Problem: I have a gtk.Dialog. Whenever the 'minimize' button on the dialog is clicked, the window is destroyed.
Question: How can I connect to the minimize button of a gtk.Dialog so that I can iconify the window?
| [
"Are you sure it's the minimize button? Because GTK doesn't deal with (or even know about the existence of) minimize buttons at all, they are part of the window manager.\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0004081020_gtk_pygtk_python_user_interface.txt |
Q:
Is Django 1.2.3 competable with Python 2.6.5
Just curious to know, Test module won't work properly with django 1.2.3 when update from django 1.1.1 (now on python 2.6.5)
A:
Yes. You're having other problems.
| Is Django 1.2.3 competable with Python 2.6.5 | Just curious to know, Test module won't work properly with django 1.2.3 when update from django 1.1.1 (now on python 2.6.5)
| [
"Yes. You're having other problems.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004085826_django_python.txt |
Q:
Can any one suggest a good networking project in python
I want to do a networking project using python. Can any one suggest a useful project in networking? I am aiming to complete it within next 5 months or so.
A:
Without a doubt, if you want to have a good understanding with implementation, Twisted is the way t... | Can any one suggest a good networking project in python | I want to do a networking project using python. Can any one suggest a useful project in networking? I am aiming to complete it within next 5 months or so.
| [
"Without a doubt, if you want to have a good understanding with implementation, Twisted is the way to go. Just by going through the documentation, you will get lots of ideas for a project.\nAnd also, these Twisted tutorials (introduction) are the best (based on a question I asked earlier on SO)\n",
"Take a simple... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0004084776_python.txt |
Q:
Multiple reactors (main loops) in one application through threading (or alternative means)
I've got an idea for an app I'd like to work on to learn a bit more about Twisted and WebSockets. I was thinking of integrating a previously written IRC Bot into a web application. As far as I can see it, I would need thre... | Multiple reactors (main loops) in one application through threading (or alternative means) | I've got an idea for an app I'd like to work on to learn a bit more about Twisted and WebSockets. I was thinking of integrating a previously written IRC Bot into a web application. As far as I can see it, I would need three reactors to make it work:
Primary Reactor: Web Server (HTTP). This would be your average tw... | [
"Lucky for you, it is easy to reduce the number of reactors, specifically, to 1:\nYou can only ever have a single reactor, in a single thread, in any given Twisted process. If you try to have more, nothing will work.\nThe whole point of a reactor, actually, is to facilitate having multiple sources of events combin... | [
20,
5
] | [] | [] | [
"events",
"multithreading",
"python",
"reactor",
"twisted"
] | stackoverflow_0004084090_events_multithreading_python_reactor_twisted.txt |
Q:
Creating a dictionary from an iterable
What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:
>>> x = dict(zip(range(0, 10), range(0)))
But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)
So how do I go... | Creating a dictionary from an iterable | What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:
>>> x = dict(zip(range(0, 10), range(0)))
But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)
So how do I go about it? If I do:
>>> x = dict(zip(range(0... | [
"In python 3, You can use a dict comprehension.\n>>> {i:0 for i in range(0,10)}\n{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n\nFortunately, this has been backported in python 2.7 so that's also available there.\n",
"You need the dict.fromkeys method, which does exactly what you want.\nFrom the d... | [
32,
23,
2,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004084749_dictionary_python.txt |
Q:
With the GAE Bulk Uploader script, how do I deal with empty values in the CSV?
I've set up my app.yaml and data_uploader files as suggested in this document. My CSV file has some null values (the spreadsheet that I exported had some empty cells).
When I run the script, I get this error in the log file:
[ERROR ... | With the GAE Bulk Uploader script, how do I deal with empty values in the CSV? | I've set up my app.yaml and data_uploader files as suggested in this document. My CSV file has some null values (the spreadsheet that I exported had some empty cells).
When I run the script, I get this error in the log file:
[ERROR ] Error in WorkerThread-0: Value should not be empty; received [].
My guess is that ... | [
"You probably should customize your bulkloader.yaml giving the right directive in the property map section. \nCheck if the import_transform element on your model kind property that gives problem is set, and try to use the none_if_empty directive .\n- property: fooproperty\n external_name: fooproperty\n import_tra... | [
1
] | [] | [] | [
"csv",
"google_app_engine",
"python"
] | stackoverflow_0003908524_csv_google_app_engine_python.txt |
Q:
How to MySQL to store multi-params for HTTP POST?
HTTP Post may have multiple params such as:
http://example.com/controller/ (while params=({'country':'US'},{'city':'NYC'})
I am developing a web spider with Python, I face a problem how to track difference with same url with different params. Now I can load the con... | How to MySQL to store multi-params for HTTP POST? | HTTP Post may have multiple params such as:
http://example.com/controller/ (while params=({'country':'US'},{'city':'NYC'})
I am developing a web spider with Python, I face a problem how to track difference with same url with different params. Now I can load the content, but I have no idea how to store the post params i... | [
"You can convert to and from json easily like this:\n>>> import json\n>>> json.dumps({'spam': 1, 'eggs': 2, 'bacon': 0})\n'{\"eggs\": 2, \"bacon\": 0, \"spam\": 1}'\n>>> json.loads('{\"eggs\": 2, \"bacon\": 0, \"spam\": 1}')\n{u'eggs': 2, u'bacon': 0, u'spam': 1}\n\n>>> json.dumps((1,2,3,4))\n'[1, 2, 3, 4]'\n>>> js... | [
3,
0
] | [] | [] | [
"post",
"python",
"sqlite"
] | stackoverflow_0004085925_post_python_sqlite.txt |
Q:
Python/Tkinter: Stretch an image horizontally?
Is it possible to stretch an image horizontally?
Use case: I have a one pixel wide (60 pixel tall) image that I would like to stretch horizontally to fill its parent container. The purpose of stretching this image is to give the container in question the appearance o... | Python/Tkinter: Stretch an image horizontally? | Is it possible to stretch an image horizontally?
Use case: I have a one pixel wide (60 pixel tall) image that I would like to stretch horizontally to fill its parent container. The purpose of stretching this image is to give the container in question the appearance of a gradient background.
Here's what I tried without... | [
"No, there is no way to stretch an image to fill the container. However, you can detect when a widget changes size and you can \"repaint\" the gradient. Use a canvas, and create a binding to <Configure> that draws the gradient. It sounds slow but it's plenty fast enough assuming you don't have hundreds of these.\n"... | [
1
] | [] | [] | [
"image",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004084383_image_python_tkinter_user_interface.txt |
Q:
Open a new window in Vim-embedded python script
I've just started wrapping my head around vim+python scripts (having no experience with native vim scripts).
How can I open a new window to contain the stdout from a background process?
Currently, after reading some :help python, the only option I see is something li... | Open a new window in Vim-embedded python script | I've just started wrapping my head around vim+python scripts (having no experience with native vim scripts).
How can I open a new window to contain the stdout from a background process?
Currently, after reading some :help python, the only option I see is something like:
cmd = ":bel new"
vim.command(cmd)
| [
"Since vim.command can execute most (if not all?) ex commands, you can simply call :new +read!ls from within it.\n:new splits the current window and puts a new (empty, no name) buffer into the upper window. It takes an argument +[cmd] which we use to execute read!cmd which reads the stdout of cmd after the bang int... | [
3
] | [] | [] | [
"python",
"scripting",
"vim"
] | stackoverflow_0003546952_python_scripting_vim.txt |
Q:
python queue concurrency process management
The use case is as follows :
I have a script that runs a series of
non-python executables to reduce (pulsar) data. I right now use
subprocess.Popen(..., shell=True) and then the communicate function of subprocess to
capture the standard out and standard error from the no... | python queue concurrency process management | The use case is as follows :
I have a script that runs a series of
non-python executables to reduce (pulsar) data. I right now use
subprocess.Popen(..., shell=True) and then the communicate function of subprocess to
capture the standard out and standard error from the non-python executables and the captured output I lo... | [
"Maybe Celery will serve your needs.\n",
"The subprocess module can start multiple processes for you just fine, and keep track of them. The problem, though, is reading the output from each process without blocking any other processes. Depending on the platform there's several ways of doing this: using the select ... | [
2,
2,
0
] | [] | [] | [
"concurrency",
"process",
"python",
"queue"
] | stackoverflow_0004086311_concurrency_process_python_queue.txt |
Q:
Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir?
I've been using SQLObject for a long while, but noticed that SQLAlchemy has become a lot more popular in the last couple years: http://www.google.com/trends?q=sqlobject,+sqlalchemy
Are there compelling reasons to switch to SQLAlchemy? How is its per... | Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir? | I've been using SQLObject for a long while, but noticed that SQLAlchemy has become a lot more popular in the last couple years: http://www.google.com/trends?q=sqlobject,+sqlalchemy
Are there compelling reasons to switch to SQLAlchemy? How is its performance relative to SQLObject? Its usability? And what is the added... | [
"I used SqlObject extensively as part of TurboGears 0.9, but switched to SqlAlchemy + elixir as a drop in replacement for SqlObject even before TurboGears did.\nNote that even without elixir, SqlAlchemy has it's own declarative style class definitions:\nhttp://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarati... | [
11
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy",
"sqlobject"
] | stackoverflow_0004066803_python_python_elixir_sqlalchemy_sqlobject.txt |
Q:
How to output in the log window in perforce client p4v using custom tools
We're developing perforce custom tools in python and we're outputting messages during the script execution. It shows up in p4win but we're mainly using p4v and the output doesn't show up in the log window.
Is there a way to output there or ... | How to output in the log window in perforce client p4v using custom tools | We're developing perforce custom tools in python and we're outputting messages during the script execution. It shows up in p4win but we're mainly using p4v and the output doesn't show up in the log window.
Is there a way to output there or in any other pane without resorting to run the tool in a terminal window?
| [
"When Python is directing its output to a pipe rather than straight to a terminal, it buffers its output by default. I think you can work around this by either passing the \"-u\" parameter when invoking Python (e.g., python -u myscript.py arg1 arg2) to tell it not to buffer, or by calling sys.stdout.flush() through... | [
1
] | [] | [] | [
"customtool",
"logging",
"perforce",
"python"
] | stackoverflow_0002608361_customtool_logging_perforce_python.txt |
Q:
Integrate Python's Django into a C++ application
I would like to integrate Python, and specifically Django, to a C++ application. This is for many reasons which include, but not limited to:
Ease of data handling and feature development in python
Django's amazing ORM
Django's instant admin interface
etc...
My spe... | Integrate Python's Django into a C++ application | I would like to integrate Python, and specifically Django, to a C++ application. This is for many reasons which include, but not limited to:
Ease of data handling and feature development in python
Django's amazing ORM
Django's instant admin interface
etc...
My specific application is a real-time event intensive appli... | [
"I would strongly recommend considering to integrate the other way around: your C++ application into Python. A good article on the tradeoffs of extending vs. embedding.\nAlso, re the Django/web server part, it's not always recommended to have a monolithic application that's too large. Consider breaking the web-serv... | [
4
] | [] | [] | [
"c++",
"django",
"integration",
"python"
] | stackoverflow_0004086888_c++_django_integration_python.txt |
Q:
how to develop a python wrapper for a C code?
Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do th... | how to develop a python wrapper for a C code? | Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do that ?
| [
"Of course, it's called \"extending\" in the Python world. The official documentation is here. A short excerpt:\n\nThis document describes how to write\n modules in C or C++ to extend the\n Python interpreter with new modules.\n Those modules can define new functions\n but also new object types and their\n met... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004087240_python.txt |
Q:
(python) meaning of st_mode
Can anyone tell me what is the meaning of the number from the ST_MODE function?
Example:
>>>import os
>>>stat = os.stat('/home')
>>>print stat.st_mode
16877
it prints 16877. What is that for?
A:
It's the permission bits of the file.
>>> oct(16877)
'040755'
See the various stat... | (python) meaning of st_mode | Can anyone tell me what is the meaning of the number from the ST_MODE function?
Example:
>>>import os
>>>stat = os.stat('/home')
>>>print stat.st_mode
16877
it prints 16877. What is that for?
| [
"It's the permission bits of the file.\n>>> oct(16877)\n'040755'\n\nSee the various stat.S_* attributes for more info.\n",
"The standard stat module can help you interpret these values from os.stat:\n\nThe stat module defines constants and\n functions for interpreting the results\n of os.stat(), os.fstat() and\... | [
29,
1
] | [] | [] | [
"python"
] | stackoverflow_0004087427_python.txt |
Q:
Logging worker processes with Parallel Python
I've inherited the maintenance of some scientific computing using Parallel Python on a cluster. With Parallel Python, jobs are submitted to a ppserver, which (in this case) talks to already-running ppserver processes on other computers, dishing tasks out to ppworkers ... | Logging worker processes with Parallel Python | I've inherited the maintenance of some scientific computing using Parallel Python on a cluster. With Parallel Python, jobs are submitted to a ppserver, which (in this case) talks to already-running ppserver processes on other computers, dishing tasks out to ppworkers processes.
I'd like to use the standard library log... | [
"One way to solve your problem is to do the following:\n\nIn each worker process, use a logging.handlers.SocketHandler to send events from the worker to a dedicated logger process.\nCreate a dedicated logger process which listens for logging events on a socket, based on the working example given in the docs at http... | [
6,
2
] | [] | [] | [
"logging",
"parallel_python",
"python"
] | stackoverflow_0004005180_logging_parallel_python_python.txt |
Q:
Django: Import CSV file and handle clash of unique values correctly
I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance. For... | Django: Import CSV file and handle clash of unique values correctly | I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance. For example, see below:
for row in dataReader:
person=Person()
perso... | [
"One of the Django orm function that i love so much is get_or_create()\nso i will suggest you do like this:\nfor row in dataReader:\n person_record, created = person.get_or_create(name=row[0], age=row[1])\n\nyou can check after if you want to change the old record in person_record or check if the record was crea... | [
5,
2,
1,
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004086630_database_django_python.txt |
Q:
Why does Parallel Python work the way it does?
In Parallel Python, why is it necessary to wrap any modules the function passed will need along with variables and namespaces in that job submission call - how necessary is it to preserve module level "global" variables? (if that's all that's going on)
submit functi... | Why does Parallel Python work the way it does? | In Parallel Python, why is it necessary to wrap any modules the function passed will need along with variables and namespaces in that job submission call - how necessary is it to preserve module level "global" variables? (if that's all that's going on)
submit function:
submit(self, func, args=(), depfuncs=(), modules... | [
"The reason that pp works the way it does, is that it makes a fresh instance of the Python interpreter for every worker, which is completely independent from anything that has run before or since. This ensures that there are no unintended side-effects, such as __future__ imports being active in the worker process. ... | [
3
] | [] | [] | [
"parallel_processing",
"parallel_python",
"python"
] | stackoverflow_0004074297_parallel_processing_parallel_python_python.txt |
Q:
django template date filter format string question
I have a datetime value that is available in a django template.
I am trying to format the date as "d-mmm"
so for example dates are formated as:
5-Mar
10-Mar
4-Apr
etc.
I have tried different combinations - NOTHING works so far?. I hope I dont have to write a cu... | django template date filter format string question | I have a datetime value that is available in a django template.
I am trying to format the date as "d-mmm"
so for example dates are formated as:
5-Mar
10-Mar
4-Apr
etc.
I have tried different combinations - NOTHING works so far?. I hope I dont have to write a custom filter just to format a date ?
[Edit]
I tried the '... | [
"Have you tried {{ some_date|date:\"j-M\" }}?\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\n"
] | [
14
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004087717_django_python.txt |
Q:
Email notification on file change in particular directory with Python
I would like to script a function wich is looking in a particular directory
for files, if there are new files, it should send out an notification email.
I already prepared a script which is looking for new files in a directory, it write
the noti... | Email notification on file change in particular directory with Python | I would like to script a function wich is looking in a particular directory
for files, if there are new files, it should send out an notification email.
I already prepared a script which is looking for new files in a directory, it write
the notification about a new file into the console. But now I would like to notifie... | [
"It's very simple if you have an SMTP mail server set up (i'm assuming you have a mail system!). Will take you about 10 lines of code in total. Here is a\npython example.\nIf you have any problems, we will need more information to help further. For example, what mail system you are using e.t.c.\n",
"OKI, in this... | [
1,
0
] | [] | [] | [
"email",
"file",
"notifications",
"python"
] | stackoverflow_0003987134_email_file_notifications_python.txt |
Q:
What's the best solution for OpenID with Django?
Please note: this is an ancient question with ancient answers. Most of the linked apps are now unmaintained. These days, most people seem to use django-allauth or python-social-auth. I'll leave the original question intact below for posterity's sake.
There are at l... | What's the best solution for OpenID with Django? | Please note: this is an ancient question with ancient answers. Most of the linked apps are now unmaintained. These days, most people seem to use django-allauth or python-social-auth. I'll leave the original question intact below for posterity's sake.
There are at least half a dozen Django apps that provide OpenID auth... | [
"The one that has proven to work best for me, and which seems most up-to-date is the one over at launchpad.\nIt integrated seamlessly with my application that already utilizes the django.auth module.\nhttps://launchpad.net/django-openid-auth\nTo get a copy run:\nbzr branch lp:django-openid-auth\n\nOr install it via... | [
87,
32,
12,
8,
5,
1
] | [] | [] | [
"django",
"openid",
"python"
] | stackoverflow_0002123369_django_openid_python.txt |
Q:
Read XML file just like python's lxml with C#?
<Connections>
<Connection ID = "1" Source="1:0" Sink="4:0"/>
<Connection ID = "2" Source="2:0" Sink="4:1"/>
<Connection ID = "3" Source="2:0" Sink="5:0"/>
<Connection ID = "4" Source="3:0" Sink="5:1"/>
<Connection ID = "5" Source="4:0" Sink=... | Read XML file just like python's lxml with C#? | <Connections>
<Connection ID = "1" Source="1:0" Sink="4:0"/>
<Connection ID = "2" Source="2:0" Sink="4:1"/>
<Connection ID = "3" Source="2:0" Sink="5:0"/>
<Connection ID = "4" Source="3:0" Sink="5:1"/>
<Connection ID = "5" Source="4:0" Sink="6:0"/>
<Connection ID = "6" Source="5:0" Sink=... | [
"You want to use LINQ-to-XML:\nvoid GetNodeList()\n{\n var connection = this.doc.Descendants(\"Connections\").First();\n var cons = connection.Elements(\"Connection\");\n\n foreach (var con in cons)\n {\n var id = (string)con.Attribute(\"ID\");\n }\n}\n\n",
"I would use XElement:\nvar xml = ... | [
4,
0
] | [] | [] | [
"c#",
"lxml",
"python",
"xml"
] | stackoverflow_0004087847_c#_lxml_python_xml.txt |
Q:
Efficient way of Element lookup in a Python List?
I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much!
... | Efficient way of Element lookup in a Python List? | I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much!
for record in result:
filelist.append(record[0])
p... | [
"Sounds like you want to do a test:\nfor file in os.listdir(sys.argv[1].strip() + \"/\"):\n if file in filelist:\n # Found a file in the wanted-list.\n print file\n\n",
"If order and uniqueness don't matter, you can use a set intersection, which will be much more efficient.\nimport set\nos_list =... | [
3,
3,
1,
1
] | [] | [] | [
"arrays",
"list",
"lookup",
"python",
"traversal"
] | stackoverflow_0004088092_arrays_list_lookup_python_traversal.txt |
Q:
WIth django, can you do something similiar to user = User.new(params[:user]) during a form post?
in ruby/ror you can do this:
user = User.new(params[:user])
which populates a new object with the values from a posted form.
Can something similar be done using django/python?
A:
Look at the model form documentation... | WIth django, can you do something similiar to user = User.new(params[:user]) during a form post? | in ruby/ror you can do this:
user = User.new(params[:user])
which populates a new object with the values from a posted form.
Can something similar be done using django/python?
| [
"Look at the model form documentation. Basically, the code would look like:\nf = UserForm(request.POST or None)\nuser = f.save()\n\n",
"If you are talking about Django's built-in auth app, then keep in mind that there are a few considerations when creating users, such as passwords, unique usernames, etc\n"
] | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004087609_django_python.txt |
Q:
re-combining a list/dictionary in python
following on from this question
i have the following lists in python which i want to recombine into a dictionary/list:
from
fromfruits = { "names" : ['banana','grapefruit','apple'] , "colors" : ['yellow','pink','green'], ... }
to
tofruits = [
{'name':'banana','color':'yell... | re-combining a list/dictionary in python | following on from this question
i have the following lists in python which i want to recombine into a dictionary/list:
from
fromfruits = { "names" : ['banana','grapefruit','apple'] , "colors" : ['yellow','pink','green'], ... }
to
tofruits = [
{'name':'banana','color':'yellow',...},
{'name':'grapefruit','color':'pink'... | [
"Since the request is now to be more general:\n>>> from itertools import izip\n>>> ff = {'colors': ['yellow', 'pink', 'green'], 'names': ['banana', 'grapefruit', 'apple'], 'blah': ['a','b','c']}\n\n>>> [dict(izip(ff.iterkeys(), v)) for v in izip(*ff.itervalues())]\n[{'blah': 'a', 'colors': 'yellow', 'names': 'banan... | [
4,
3,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python"
] | stackoverflow_0004087622_dictionary_list_loops_python.txt |
Q:
Converting an unknown timestamp to a datetime in Python
I'm getting a timestamp back from the WordPress API, but the usual method of converting from timestamp to datetime is failing me.
I run this:
print pages[1]['dateCreated']
print datetime.fromtimestamp(pages[1]['dateCreated'])
And get this:
20100228T09:25:07
... | Converting an unknown timestamp to a datetime in Python | I'm getting a timestamp back from the WordPress API, but the usual method of converting from timestamp to datetime is failing me.
I run this:
print pages[1]['dateCreated']
print datetime.fromtimestamp(pages[1]['dateCreated'])
And get this:
20100228T09:25:07
Traceback (most recent call last):
File "C:\Python26\Lib\SI... | [
"Assume you've from datetime import datetime:\nprint datetime.strptime(pages[1]['dateCreated'],'%Y%m%dT%H:%M:%S')\n\n"
] | [
3
] | [] | [] | [
"datetime",
"python",
"timestamp"
] | stackoverflow_0004088506_datetime_python_timestamp.txt |
Q:
Assigning dates to samples in matplotlib
Given some arbitrary numpy array of data, how can I plot it to make dates appear on the x axis? In this case, sample 0 will be some time, say 7:00, and every sample afterwards will be spaced one minute apart, so that for 60 samples, the time displayed should be 7:00, 7:01, ... | Assigning dates to samples in matplotlib | Given some arbitrary numpy array of data, how can I plot it to make dates appear on the x axis? In this case, sample 0 will be some time, say 7:00, and every sample afterwards will be spaced one minute apart, so that for 60 samples, the time displayed should be 7:00, 7:01, ..., 7:59.
I looked at some of the other quest... | [
"If you use an array of datetime objects for your x-axis, the plot() function will behave like you want (assuming that you don't want all 60 labels from 7:00 to 7:59 to be displayed). Here is a sample code:\nimport random\nfrom pylab import *\nfrom datetime import *\nN = 60\nt0 = datetime.combine(date.today(), time... | [
1
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0004088005_matplotlib_numpy_python.txt |
Q:
raw_input() is deprecated in python 3.1?
Possible Duplicate:
Easy: How to use Raw_input in 3.1
in old style i can entering data with this function
A:
raw_input is now input per http://docs.python.org/dev/py3k/whatsnew/3.0.html
A:
raw_input has been renamed to input. The 2.x input, which eval'd the input, was... | raw_input() is deprecated in python 3.1? |
Possible Duplicate:
Easy: How to use Raw_input in 3.1
in old style i can entering data with this function
| [
"raw_input is now input per http://docs.python.org/dev/py3k/whatsnew/3.0.html\n",
"raw_input has been renamed to input. The 2.x input, which eval'd the input, was removed.\n",
"You should use input() instead, which uses the behavior of raw_input() from 2.x.\n",
"in Python 3 you use input function\n"
] | [
3,
3,
0,
0
] | [] | [] | [
"python",
"raw_input"
] | stackoverflow_0004088692_python_raw_input.txt |
Q:
Pythonistas, how do I move data from top to bottom to left to right in MySQL (think multiple values for each ID)?
Task at hand is to move data as shown in table 1 to that of table 2.
Table (1)
ID Val
-- ---
1 a
1 b
1 c
2 k
3 l
3 m
3 n
Val columns depend on the number of unique values for each ID.... | Pythonistas, how do I move data from top to bottom to left to right in MySQL (think multiple values for each ID)? | Task at hand is to move data as shown in table 1 to that of table 2.
Table (1)
ID Val
-- ---
1 a
1 b
1 c
2 k
3 l
3 m
3 n
Val columns depend on the number of unique values for each ID. in this case it is 3 but it can be 20 in real world!
Table (2)
ID Val1 Val2 Val3
-- -- -- --
1 a b c
2... | [
"the pytonic way to do this is to use itertools.groupby\nimport itertools\n\na = [(1, 'a'), (1, 'b'), (2, 'c')]\n\n# groupby need sorted value so sorted in case\na.sort(key=lambda x:x[0])\n\nfor i, j in itertools.groupby(a, key=lambda x:x[0]):\n print i, [k[1] for k in j]\n\nreturn\n1 ['a', 'b']\n2 ['c']\n\n"
] | [
2
] | [] | [] | [
"data_manipulation",
"mysql",
"python"
] | stackoverflow_0004088639_data_manipulation_mysql_python.txt |
Q:
Formatting large integers in Python
I am dealing with large integral numbers in my script and I want to format the numbers into strings using the 'K', 'M' and 'B' postfix chars to denote scale of thousands, millions or billionsб respectively.
Rather than rolling my own function, I wonder if there is an built-in fu... | Formatting large integers in Python | I am dealing with large integral numbers in my script and I want to format the numbers into strings using the 'K', 'M' and 'B' postfix chars to denote scale of thousands, millions or billionsб respectively.
Rather than rolling my own function, I wonder if there is an built-in function that either does this "out of the ... | [
"There's no built-in way to do this in the Python standard library, but there's a nice example of what you want to achieve here.\n"
] | [
3
] | [] | [] | [
"largenumber",
"python",
"string_formatting"
] | stackoverflow_0004088700_largenumber_python_string_formatting.txt |
Q:
python int doesn't have __iadd__() method?
I know this is bad practice:
>>> a = 5
>>> a.__radd__(5)
10
>>> a
5
>>> a.__iadd__(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'
Out of curiosity, if an int object doesn't have __iadd_... | python int doesn't have __iadd__() method? | I know this is bad practice:
>>> a = 5
>>> a.__radd__(5)
10
>>> a
5
>>> a.__iadd__(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'
Out of curiosity, if an int object doesn't have __iadd__, then how does += work?
| [
"\nOut of curiosity, if an int object doesn't have __iadd__, then how does += work?\n\na += 5\n\nBecomes\na = a + 5\n\nBecause there's no __iadd__ for immutable objects.\nThis is (in effect)\na = a.__add__( 5 )\n\nAnd works nicely. A new int object is created by __add__.\nSome of the rules are here http://docs.pyt... | [
6,
3
] | [] | [] | [
"immutability",
"integer",
"python"
] | stackoverflow_0004088731_immutability_integer_python.txt |
Q:
Can python mechanize handle HTTP auth?
Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success.
My code looks like this.
import mechanize
project = "test"
baseurl = "http://trac.somewhere.net"
loginurl = "%s/%s/login" % (baseurl, project)
b = mechanize... | Can python mechanize handle HTTP auth? | Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success.
My code looks like this.
import mechanize
project = "test"
baseurl = "http://trac.somewhere.net"
loginurl = "%s/%s/login" % (baseurl, project)
b = mechanize.Browser()
b.add_password(baseurl, "user", "... | [
"Mechanize claims that the parameters should be uri, username and password as parameters, but you have four parameters. Four parameters are correct for urllib2.add_password, but then the first parameter should be the realm, not the uri.\nhttp://wwwsearch.sourceforge.net/mechanize/\nI'd try to change that first.\nDo... | [
6,
4,
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0001097380_mechanize_python.txt |
Q:
comparing two dictionary lists in python
I have two dictionaries
{key1:[list_of_objects ], {key2:[list_of_objects ]}
e.g
dict1 = {key1:['a', 'b', 'c', 'd' ], key2: ['f', 'g', 'h' ] }
dict2 = {key1:['a', 'b', 'c', 'd'], key2: ['f', 'g', 'h', 'i' ] }
For eack key in both dict1 and dict2, i want to compare the ite... | comparing two dictionary lists in python | I have two dictionaries
{key1:[list_of_objects ], {key2:[list_of_objects ]}
e.g
dict1 = {key1:['a', 'b', 'c', 'd' ], key2: ['f', 'g', 'h' ] }
dict2 = {key1:['a', 'b', 'c', 'd'], key2: ['f', 'g', 'h', 'i' ] }
For eack key in both dict1 and dict2, i want to compare the items in the lists.
i.e compare each value in di... | [
"for key in dict1.keys():\n for a,b in zip(dict1[key],dict2[key]):\n if a.some_function() == b.some_function():\n #do something\n\nIf your lists are very long you could swap zip for izip from collections.\n",
"sets make it easy:\nfor key in dict1.keys():\n diff = set(dict1[key]).symmetric_d... | [
0,
0
] | [] | [] | [
"compare",
"dictionary",
"python"
] | stackoverflow_0004088398_compare_dictionary_python.txt |
Q:
Is there a more pythonic way to do this dictionary iteration?
I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None.
The None values are being printed as ... | Is there a more pythonic way to do this dictionary iteration? | I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None.
The None values are being printed as 'None' in the template, so I wrote this little function to clean ou... | [
"Have you looked at defaultdict within collections? You'd have a dictionary formed via\ndefaultdict(list)\n\nwhich initializes an empty list when a key is queried and that key does not exist.\n",
"filtered_dict = dict((k, v) for k, v in table.items() if v is not None)\n\nor in Python 2.7+, use the dictionary com... | [
3,
0
] | [] | [] | [
"django_templates",
"django_views",
"python"
] | stackoverflow_0004088471_django_templates_django_views_python.txt |
Q:
How to export python functions and reuse them in another app
I was wondering if there is any way to export python functions to dll. There is py2exe and I can successfully create exe file. My program should be used by another program written in delphi (there is possibility of importing dll's in delphi).
So I was wo... | How to export python functions and reuse them in another app | I was wondering if there is any way to export python functions to dll. There is py2exe and I can successfully create exe file. My program should be used by another program written in delphi (there is possibility of importing dll's in delphi).
So I was wondering what would be the best way to connect those 2 applications... | [
"There are some pretty big challenges to making languages work well together. As a simple alternative to trying to hook python code directly into delphi, you could consider using something like an xmlrpc server to provide python functionality remotely. \nhttp://docs.python.org/library/xmlrpclib.html\nOf course, a... | [
1,
0
] | [] | [] | [
"dll",
"export",
"python"
] | stackoverflow_0004089569_dll_export_python.txt |
Q:
tkinter: grid method strange behavior
I want this code to do this:
Create 4 frames with this layout (dashes mean the frame spans that column):
-X-
XXX
Within each of these frames (X's) there should be two rows like this:
cowN,1
cowN,2
It seems like the grid() method is global ONLY and is never specific to a s... | tkinter: grid method strange behavior | I want this code to do this:
Create 4 frames with this layout (dashes mean the frame spans that column):
-X-
XXX
Within each of these frames (X's) there should be two rows like this:
cowN,1
cowN,2
It seems like the grid() method is global ONLY and is never specific to a single frame...
#!/usr/apps/Python/bin/pytho... | [
"The problem with your code is that your are not keeping a reference to the Frame objects on your frameN variables: you create the objects, and call their grid method: you store the return of the grid method on the variables, which is None.\nSo, your labels are being created with None as their master. \nJust chang... | [
2
] | [] | [] | [
"frames",
"grid",
"python",
"tkinter"
] | stackoverflow_0004088390_frames_grid_python_tkinter.txt |
Q:
TinyMce File browser for pylons?
Do you now some AJAX based filebrowser to TinyMCE which can I use in my pylons app?
A:
It seems like the closest thing to what you want is TinyMCE Image Manager, which claims to have file management capabilities. However, it's not very clear what you're asking, so you may want t... | TinyMce File browser for pylons? | Do you now some AJAX based filebrowser to TinyMCE which can I use in my pylons app?
| [
"It seems like the closest thing to what you want is TinyMCE Image Manager, which claims to have file management capabilities. However, it's not very clear what you're asking, so you may want to clarify your question. \n"
] | [
0
] | [] | [] | [
"pylons",
"python",
"tinymce"
] | stackoverflow_0002838227_pylons_python_tinymce.txt |
Q:
What is the way data is stored in *.npy?
I'm saving NumPy arrays using numpy.save function.
I want other developers to have capability to read data from those file using C language.
So I need to know,how numpy organizes binary data in file.OK, it's obvious when I'm saving array of 'i4' but what about array of arra... | What is the way data is stored in *.npy? | I'm saving NumPy arrays using numpy.save function.
I want other developers to have capability to read data from those file using C language.
So I need to know,how numpy organizes binary data in file.OK, it's obvious when I'm saving array of 'i4' but what about array of arrays that contains some structures?Can't find an... | [
"The npy file format is documented in numpy's NEP 1 — A Simple File Format for NumPy Arrays.\nFor instance, the code \n>>> dt=numpy.dtype([('outer','(3,)<i4'),\n... ('outer2',[('inner','(10,)<i4'),('inner2','f8')])])\n>>> a=numpy.array([((1,2,3),((10,11,12,13,14,15,16,17,18,19),3.14)),\n... ... | [
48,
6
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004090080_numpy_python.txt |
Q:
Infrastructure for a "news-feed"
I'd like to offer a news-feed like feature for users of our website. When the user logs in, he is shown a list of the latest updates across various areas of the site.
I'm afraid that this is going to be difficult to scale.
What are some networking / database topologies that can ... | Infrastructure for a "news-feed" | I'd like to offer a news-feed like feature for users of our website. When the user logs in, he is shown a list of the latest updates across various areas of the site.
I'm afraid that this is going to be difficult to scale.
What are some networking / database topologies that can support a scalable infrastructure with... | [
"\nDon't prematurely optimize. \nThis might be more of a question for the Server Fault crowd. \nPerformance at scale often requires having lots of copies of the same data - you tagged the question \"facebook,\" and that's part of how Facebook does it. Twitter, too. You are asking for a system that's fast (\"upd... | [
0
] | [] | [] | [
"facebook",
"feed",
"infrastructure",
"pylons",
"python"
] | stackoverflow_0002703549_facebook_feed_infrastructure_pylons_python.txt |
Q:
execute sqlserver store procedure using python
I have this code
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connection")
dbConn.Open( connection_string )
( rs, result )... | execute sqlserver store procedure using python | I have this code
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connection")
dbConn.Open( connection_string )
( rs, result ) = s.dbConn.Execute( query_string )
while not rs.EO... | [
"Not sure if this will help, but here's how to do it with pyODBC:\n cn = pyodbc.connect(\"DSN=myDBName\")\n cn.autocommit = True\n cr = cn.cursor()\n cr.execute(\"set nocount on\")\n cr.execute(\"exec myStoredProc\")\n ...\n cr.close()\n cn.close()\n\n"
] | [
0
] | [] | [] | [
"python",
"sql_server_2005"
] | stackoverflow_0004090165_python_sql_server_2005.txt |
Q:
Integrating SQLAlchemy's ORM with existing classes in pylons
I have a class in my existing python project, User, that I would like to map to tables. But I'm not sure what the best way to do this is?
Does this mean I can remove:
class User:
pass
from my model/__ init __.py?
Or should I leave that in there, an... | Integrating SQLAlchemy's ORM with existing classes in pylons | I have a class in my existing python project, User, that I would like to map to tables. But I'm not sure what the best way to do this is?
Does this mean I can remove:
class User:
pass
from my model/__ init __.py?
Or should I leave that in there, and have something like:
from project.model.user import User
class U... | [
"You should not define a class that maps onto a table in the model's __init__.py file, nor should you have two different clases with the same name. \nClasses that map onto tables belong in your project's model directory, grouped into modules. Then import the classes in __init__.py to make them available. \n"
] | [
0
] | [] | [] | [
"orm",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002365459_orm_pylons_python_sqlalchemy.txt |
Q:
How to catch FTP errors? e.g., socket.error: [Errno 10060]
I'm using the ftplib module to upload files:
files = [ a.txt , b.txt , c.txt ]
s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP
for i in range(len(files)):
f = open(files[i], 'rb')
stor = 'stor ' + files[... | How to catch FTP errors? e.g., socket.error: [Errno 10060] | I'm using the ftplib module to upload files:
files = [ a.txt , b.txt , c.txt ]
s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP
for i in range(len(files)):
f = open(files[i], 'rb')
stor = 'stor ' + files[i]
s.storbinary(stor, f)
f.close() # clo... | [
"import socket\n\ntry:\n s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP\nexcept socket.error, e:\n print \"do something with %s\" % e\n\nthis will catch all socket errors (whatever their \"errno\" -- ones 10000 and up are quite Windows specific, they're very different on Unix).\nSee the docs ... | [
3,
2
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0002823937_ftp_ftplib_python.txt |
Q:
Why can I not import this class?
I have three classes having to import each others methods. The statements would be as follows in the corresponding files with classes:
File A with class a
from B import b
File B with class b
from C import c
File C with class c
from A import a
Why does this not work in python? I ... | Why can I not import this class? | I have three classes having to import each others methods. The statements would be as follows in the corresponding files with classes:
File A with class a
from B import b
File B with class b
from C import c
File C with class c
from A import a
Why does this not work in python? I rather get the error message:
ImportEr... | [
"What you have is a classic circular import problem in Python. Have you taken a look at previous questions on SO, like this one?\n",
"Python can't find it. Is it in the proper directory, does it actually exist?\n"
] | [
2,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0004090588_class_python.txt |
Q:
Overriding default tab behaviour in Python Tkinter
I am writing an application in Python using Tkinter to manage my GUI.
There is a text entry box on which I am trying to implement an autocompletion function which will bind to the Tab key.
I have bound the tab key to my entry box, but when I press tab, the program... | Overriding default tab behaviour in Python Tkinter | I am writing an application in Python using Tkinter to manage my GUI.
There is a text entry box on which I am trying to implement an autocompletion function which will bind to the Tab key.
I have bound the tab key to my entry box, but when I press tab, the program attempts to cycle between GUI elements.
How do I overri... | [
"Return 'break' at the end of your event handler. It interrupts event propagation.\ndef my_tab_handler(event):\n ... # handle tab event\n return 'break' # interrupts event propagation to default handlers\n\n"
] | [
11
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004090683_python_tkinter_user_interface.txt |
Q:
Weird PyPI authentication behavior
I'm trying to upload my package to PyPI. It asks me to identify, I do, it gives an OK response (which doesn't happen unless the identification is right), but then it claims I didn't identify! Why?
[...]
removing 'build\bdist.win32\egg' (and everything under it)
running register
W... | Weird PyPI authentication behavior | I'm trying to upload my package to PyPI. It asks me to identify, I do, it gives an OK response (which doesn't happen unless the identification is right), but then it claims I didn't identify! Why?
[...]
removing 'build\bdist.win32\egg' (and everything under it)
running register
We need to know who you are, so please ch... | [
"I've never encountered that myself, but some things to check:\n\nMake sure you can login to PyPI using your browser with the username and password.\nCheck that ~/.pypirc has the correct contents. If it does not exist, try creating it.\nCheck your setup.cfg file to make sure all the PyPI settings (if any) are corre... | [
1,
1
] | [] | [] | [
"distribution",
"distutils",
"pypi",
"python"
] | stackoverflow_0001750186_distribution_distutils_pypi_python.txt |
Q:
How can you make Pylons email you the full post parameters with an error report?
Pylons can email you errors when something goes wrong in production mode, but it truncates the post parameters so it's hard to see what the error is. Is there a way to make it email you the whole thing?
A:
You can actually make Pylo... | How can you make Pylons email you the full post parameters with an error report? | Pylons can email you errors when something goes wrong in production mode, but it truncates the post parameters so it's hard to see what the error is. Is there a way to make it email you the whole thing?
| [
"You can actually make Pylons email you errors in development, testing, and production modes, just so long as you put the correct email information in the .ini file. \nThe facilities for emailing you error messages come from the WebError middleware, particularly the weberror.reporter module. The only truncating t... | [
0
] | [] | [] | [
"post",
"pylons",
"python"
] | stackoverflow_0003283111_post_pylons_python.txt |
Q:
where to store a log file name in python?
I have a Python program that consists of several modules. The "main" module creates a file variable log_file for logging the output; all the other modules would need to write to that file as well.
However, I don't want to import the "main" module into other modules, since ... | where to store a log file name in python? | I have a Python program that consists of several modules. The "main" module creates a file variable log_file for logging the output; all the other modules would need to write to that file as well.
However, I don't want to import the "main" module into other modules, since it would be a really weird dependency (not to m... | [
"Put the \"global\" variable in a \"settings\" module.\nsettings.py\nlog_file = \"/path/to/file\"\n\nmain.py\nimport settings\nimport logging\nlogging.basicConfig(filename=settings.log_file,level=logging.DEBUG)\n\nlogging.debug(\"This should go to the log file\")\n\nother_module.py\nimport logging\nlogging.debug(\"... | [
2,
1
] | [] | [] | [
"module",
"python",
"python_3.x"
] | stackoverflow_0004090652_module_python_python_3.x.txt |
Q:
Where is the best place to associate a 'form display text' with SQLAlchemy mapped property?
In django orm I can use the 'verbose_name' kwarg to set a label that will be displayed in model forms. Now I'm dynamically generating WTForms for each model in a SQLAlchemy mapped backend, but I'm not sure where to associat... | Where is the best place to associate a 'form display text' with SQLAlchemy mapped property? | In django orm I can use the 'verbose_name' kwarg to set a label that will be displayed in model forms. Now I'm dynamically generating WTForms for each model in a SQLAlchemy mapped backend, but I'm not sure where to associate a display text to use in the auto generated fields for each form. For example, in django I coul... | [
"You could duplicate that functionality by using the 'info' keyword argument to Column. That would look like this:\nClass User(Base):\n name = Column(String, info={verbose_name: 'Enter your username',})\n password = Column(String, info={verbose_name: 'Enter your password',})\n\nThen you could pull info['verb... | [
3
] | [] | [] | [
"django",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003949131_django_pylons_python_sqlalchemy.txt |
Q:
Is there a way to resend UDP packets using Twisted?
Problem: Simple UDP proxy - receive UDP packets from multiple sources on port X and forward (resend) them to IP Y on port Z.
Description: I am able to create a simple UDP server using twisted, and receive incoming packets easily. However, I cant find a way to res... | Is there a way to resend UDP packets using Twisted? | Problem: Simple UDP proxy - receive UDP packets from multiple sources on port X and forward (resend) them to IP Y on port Z.
Description: I am able to create a simple UDP server using twisted, and receive incoming packets easily. However, I cant find a way to resend these packets (their data) further, using Twisted. Is... | [
"You do something like this:\nclass MyProtocol(DatagramProtocol):\n def datagramReceived(self, datagram, addr):\n # use self.transport.write to send stuff\n some_where = ('192.168.0.1',5001)\n self.transport.write( datagram, some_where )\n\n"
] | [
2
] | [] | [] | [
"forwarding",
"proxy",
"python",
"twisted",
"udp"
] | stackoverflow_0004090572_forwarding_proxy_python_twisted_udp.txt |
Q:
How can I pass variables between two classes/windows in PyGtk?
I am starting out with PyGtk and am having trouble understanding the interaction of windows.
My very simple question is the following.
Suppose I have a class that simply creates a window with a text-entry field. When clicking the "ok" button in that wi... | How can I pass variables between two classes/windows in PyGtk? | I am starting out with PyGtk and am having trouble understanding the interaction of windows.
My very simple question is the following.
Suppose I have a class that simply creates a window with a text-entry field. When clicking the "ok" button in that window, I want to pass the text in the entry field to another window, ... | [
"Let's call A the Menu, and B the window with the text-entry field.\nIf I understood correctly A calls B and when Ok button is pressed in B, A needs to update its menu.\nIn this scenario you could create a callback function in A, meant to be called when B's ok button is pressed. When you create B you can pass this ... | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004090804_pygtk_python.txt |
Q:
How can I pass a user input string to a function as arguments in a python script?
I want to pass a user input string to a function, using the space separated words as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give.
A:
def your_function(*args):
# ... | How can I pass a user input string to a function as arguments in a python script? | I want to pass a user input string to a function, using the space separated words as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give.
| [
"def your_function(*args):\n # 'args' is now a list that contains all of the arguments\n ...do stuff...\n\ninput_args = user_string.split()\nyour_function(*input_args) # Convert a list into the arguments to a function\n\nhttp://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists\nGranted, if yo... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004091054_python.txt |
Q:
Python/Tkinter: Turn on/off screen updates like wxPython Freeze/Thaw?
Does Tkinter provide a way to temporarily turn off screen updates (when performing a large amount of screen activity) and then turn on screen updates when the UI updates are complete? Many GUI frameworks have this feature. wxPython provides Free... | Python/Tkinter: Turn on/off screen updates like wxPython Freeze/Thaw? | Does Tkinter provide a way to temporarily turn off screen updates (when performing a large amount of screen activity) and then turn on screen updates when the UI updates are complete? Many GUI frameworks have this feature. wxPython provides Freeze and Thaw methods for this functionality. The Windows Win32api supports t... | [
"No, Tkinter has no such thing. However, the screen is only updated via the event loop, so if all of your \"large amount of screen activity\" is happening in a single method, none of the activity will show up until your method finishes and the event loop is re-entered (or you explicitly call .update_idletasks())\n"... | [
1
] | [] | [] | [
"python",
"pywin32",
"tkinter",
"user_interface",
"win32ole"
] | stackoverflow_0004088996_python_pywin32_tkinter_user_interface_win32ole.txt |
Q:
How to change the app name in OSX menubar in a pure-Python application bundle?
I am trying to create a pure-Python application bundle for a wxPython app. I created the .app directory with the files described in Apple docs, with an Info.plist file etc. The only difference between a "normal" app and this bundle is t... | How to change the app name in OSX menubar in a pure-Python application bundle? | I am trying to create a pure-Python application bundle for a wxPython app. I created the .app directory with the files described in Apple docs, with an Info.plist file etc. The only difference between a "normal" app and this bundle is that the entry point (CFBundleExecutable) is a script which starts with the following... | [
"Change a key called LSHasLocalizedDisplayName in Info.plist to true, as in:\n<key>LSHasLocalizedDisplayName</key>\n<true/>\n\nand then create a file in the executable bundle\nfoo.app/Contents/Resources/English.lproj/InfoPlist.strings\n\nwhich has lines\nCFBundleName=\"name in the menu bar\";\nCFBundleDisplayName=\... | [
3,
3,
1
] | [] | [] | [
"bundle",
"macos",
"py2app",
"python",
"wxpython"
] | stackoverflow_0002932211_bundle_macos_py2app_python_wxpython.txt |
Q:
plotting unix timestamps in matplotlib
I'd like to make a generic value -vs- time plot with python's matplotlib module. My times are in unix time but I'd like them to show up in a readable format on the plot's x-axis.
I have read answers about plotting with datetime objects but this method seems to remove hour/... | plotting unix timestamps in matplotlib | I'd like to make a generic value -vs- time plot with python's matplotlib module. My times are in unix time but I'd like them to show up in a readable format on the plot's x-axis.
I have read answers about plotting with datetime objects but this method seems to remove hour/min/sec information and rails timestamps to ... | [
"It is possible to call plt.plot(dates,values) with dates being a list of datetime.datetime objects. The plot will include xticks in a format like '%Y-%m-%d' and as you zoom in, automatically change to one that shows hours, minutes, seconds. \nHowever, it sounds like you desire more control than this. Perhaps it is... | [
92
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004090383_matplotlib_python.txt |
Q:
Backprop implementation issue
What I am supposed to do. I have an black and white image (100x100px):
I am supposed to train a backpropagation neural network with this image. The inputs are x, y coordinates of the image (from 0 to 99) and output is either 1 (white color) or 0 (black color).
Once the network has le... | Backprop implementation issue | What I am supposed to do. I have an black and white image (100x100px):
I am supposed to train a backpropagation neural network with this image. The inputs are x, y coordinates of the image (from 0 to 99) and output is either 1 (white color) or 0 (black color).
Once the network has learned, I would like it to reproduce... | [
"It's been a while, but I did get my degree in this stuff, so I think hopefully some of it has stuck.\nFrom what I can tell, you're too deeply overloading your middle layer neurons with the input set. That is, your input set consists of 10,000 discrete input values (100 pix x 100 pix); you're attempting to encode ... | [
5
] | [] | [] | [
"artificial_intelligence",
"machine_learning",
"matlab",
"neural_network",
"python"
] | stackoverflow_0004091172_artificial_intelligence_machine_learning_matlab_neural_network_python.txt |
Q:
String error in my python api wrapper class
I'm writing an API wrapper to a couple of different web services.
I have a method that has an article url, and I want to extract text from it using alchemyapi.
def extractText(self):
#All Extract Text Methods ---------------------------------------------------------/... | String error in my python api wrapper class | I'm writing an API wrapper to a couple of different web services.
I have a method that has an article url, and I want to extract text from it using alchemyapi.
def extractText(self):
#All Extract Text Methods ---------------------------------------------------------//
#Extract page text from a web URL (ignoring... | [
"You should raise Exception or a subclass thereof, instead of a string.\n",
"The information provided is not actually very helpful to diagnose or solve the problem. Have you considered taking a look at the response from the server? You might inspect a complete traffic log using Fiddler. \nAdditionally, the SDK pr... | [
2,
2,
0,
0
] | [] | [] | [
"api",
"python",
"wrapper"
] | stackoverflow_0004056073_api_python_wrapper.txt |
Q:
Trying to find a pure python scrollbar, slider or guage widget to control the x axis of a graph (wxPython)
Does anyone know of an example / tutorial of one? I want to control the x-min and x-max values of an xy plot (for mpl) using mouse clicks / drag & drop in wxPython-
Thx in advance.
--DM
A:
This should be pr... | Trying to find a pure python scrollbar, slider or guage widget to control the x axis of a graph (wxPython) | Does anyone know of an example / tutorial of one? I want to control the x-min and x-max values of an xy plot (for mpl) using mouse clicks / drag & drop in wxPython-
Thx in advance.
--DM
| [
"This should be pretty easy to do. Have you looked at the docs and this example?\nSo when the slider changes, you can easily set the values you desire. Also, there is a SetMin and SetMax method for what you want.\n",
"The RulerCtrl widget by Andrea Gavana can probably do what you want. \nIt's \"pure Python\" as ... | [
1,
0
] | [] | [] | [
"matplotlib",
"python",
"wxpython"
] | stackoverflow_0004081133_matplotlib_python_wxpython.txt |
Q:
CTRL-C behaves differently in Python
I've recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Py... | CTRL-C behaves differently in Python | I've recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Python one doesn't. This is seen when a sepa... | [
"Several issues:\n\nDon't catch all exceptions and silently exit. That's the worst possible thing you can do.\nUnless you really know what you're doing, never catch SIGTSTP. It's not a signal meant for applications to intercept, and if you're catching it, chances are you're doing something wrong.\nKeyboardInterru... | [
5,
1
] | [] | [] | [
"java",
"python",
"sockets"
] | stackoverflow_0004090891_java_python_sockets.txt |
Q:
Trying to produce monospaced output in pyqt browser
I have modified a short piece of pyqt code to produce real-time rendering of a user's expression. I have used sympy's pretty-printing function for this, however the output does not appear correctly as the QTextBrowser uses a proportional rather than a monospaced ... | Trying to produce monospaced output in pyqt browser | I have modified a short piece of pyqt code to produce real-time rendering of a user's expression. I have used sympy's pretty-printing function for this, however the output does not appear correctly as the QTextBrowser uses a proportional rather than a monospaced font.
As a beginner I would also welcome any other though... | [
"You should be able to change the font with setFontFamily.\nConcerning your code: I haven't really worked with PyQt yet (only some hacks like the font family in qbzr...), so I can't tell you if everything is okay. But the following is not a good idea:\n except:\n if text=='': self.browser.clear()\n\n\nNev... | [
4,
1
] | [] | [] | [
"pyqt",
"python",
"sympy"
] | stackoverflow_0004091276_pyqt_python_sympy.txt |
Q:
How do I create a numpy array from string?
I have a file reader that reads n bytes from a file and returns a string of chars representing that (binary) data. I want to read up n bytes into a numpy array of numbers and run a FFT on it, but I'm having trouble creating an array from a string. A couple lines of examp... | How do I create a numpy array from string? | I have a file reader that reads n bytes from a file and returns a string of chars representing that (binary) data. I want to read up n bytes into a numpy array of numbers and run a FFT on it, but I'm having trouble creating an array from a string. A couple lines of example would be awesome.
Edit:
I'm reading raw binar... | [
"In Python 2, you can do this directly with numpy.fromstring:\nimport numpy as np\ns = '\\x01\\x05\\x03\\xff'\na = np.fromstring(s, dtype='uint8')\n\nOnce completing this, a is array([ 1, 5, 3, 255]) and you can use the regular scipy/numpy FFT routines.\nIn Python 3, the switch to default Unicode strings means that... | [
21,
5,
1
] | [] | [] | [
"arrays",
"fft",
"numpy",
"python"
] | stackoverflow_0004090981_arrays_fft_numpy_python.txt |
Q:
subprocess.call requiring all parameters to be separated by commas
I used to be able to do a subprocess.call(["command","-option value -option value"]) and it would work there was a change to the command to work properly with things in quotes, but now I have to change my subprocess call command to look like this... | subprocess.call requiring all parameters to be separated by commas | I used to be able to do a subprocess.call(["command","-option value -option value"]) and it would work there was a change to the command to work properly with things in quotes, but now I have to change my subprocess call command to look like this:
subprocess.call(["command","-option","value","-option","value"])
is... | [
"Avoid shell=True if you can -- it's a security risk. For this purpose, shlex.split suffices:\nimport subprocess\nimport shlex\nsubprocess.call(shlex.split(\"command -option value -option value\"))\n\n",
"You'll need to specify shell=True to get subprocess.call to interpret the string.\nSee the note in the subpr... | [
44,
3
] | [] | [] | [
"python"
] | stackoverflow_0004091242_python.txt |
Q:
Nice way (for CPU) to wait for a free lock in Python
I have a generic class called "lockingValue" that may be referenced by several threads. This is to prevent a race condition.
class lockingValue(object):
def __init__(self,value=None):
self._locked=False
self._value=value
def _lock(sel... | Nice way (for CPU) to wait for a free lock in Python | I have a generic class called "lockingValue" that may be referenced by several threads. This is to prevent a race condition.
class lockingValue(object):
def __init__(self,value=None):
self._locked=False
self._value=value
def _lock(self):
while self._locked:
pass
s... | [
"Check out threading.Lock().\nimport threading\n\nclass lockingValue(object):\n def __init__(self,value=None):\n self._lock = threading.Lock()\n self._value = value\n\n def _lock(self):\n self._lock.acquire()\n\n def _unlock(self):\n self._lock.release()\n\n def update(self, ... | [
3,
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004091565_multithreading_python.txt |
Q:
Incrementing previous entry by 1
I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out ... | Incrementing previous entry by 1 | I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out the first step.
here is my models.py
c... | [
"It looks to me that your \"quote\" is two things: a monotonically incrementing \"project number\", and a year. Since that's what they are, they have a regular structure. Exclude them from your form and view entirely, and create two new fields: \"quote_year\" and \"quote_id.\"\nYour save would then look something... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0004090019_django_django_forms_django_models_django_views_python.txt |
Q:
printing to a file in Python: redirect vs print's file argument vs write
I have a bunch of print calls that I need to write to a file instead of stdout. (I don't need stdout at all.)
I am considering three approaches. Are there any advantages (including performance) to any one of them?
Full redirect, which I saw h... | printing to a file in Python: redirect vs print's file argument vs write | I have a bunch of print calls that I need to write to a file instead of stdout. (I don't need stdout at all.)
I am considering three approaches. Are there any advantages (including performance) to any one of them?
Full redirect, which I saw here:
import sys
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout ... | [
"I would not expect any durable performance differences among these approaches.\nThe advantage of the first approach is that any reasonably well-behaved code which you rely upon (modules you import) will automatically pick up your desired redirection.\nThe second approach has no advantage. It's only suitable for d... | [
6,
4,
4
] | [] | [] | [
"file",
"python",
"python_3.x",
"redirect",
"stdout"
] | stackoverflow_0004090997_file_python_python_3.x_redirect_stdout.txt |
Q:
server-side scripting for web pages with Python: nothing happens
I'm trying to learn to use Python to create dynamic web content. Problem I'm having right out the door, though, is that when I try to do a mySQL query, absolutely nothing happens. There's no error message... it looks like the script simply stops runn... | server-side scripting for web pages with Python: nothing happens | I'm trying to learn to use Python to create dynamic web content. Problem I'm having right out the door, though, is that when I try to do a mySQL query, absolutely nothing happens. There's no error message... it looks like the script simply stops running when I import the module that enables connection to the database.
... | [
"Please, take 24h to learn something like Django. Django has an ORM and a XML serializer that will make your life easier ensuring proper (and legal) xml, it really pays up.\n",
"You can enable cgi traceback to see what happens:\nimport cgitb\ncgitb.enable()\n\n(I don't think it causes your problem, and clients un... | [
1,
0
] | [] | [] | [
"mysql",
"python",
"xml"
] | stackoverflow_0004091167_mysql_python_xml.txt |
Q:
a little bit of python help
i need a little help here, since i am new to python, i am trying to do a nice app that can tell me if my website is down or not, then send it to twitter.
class Tweet(webapp.RequestHandler):
def get(self):
import oauth
client = oauth.TwitterClient(TWITTER_CONSUMER_KEY,
... | a little bit of python help | i need a little help here, since i am new to python, i am trying to do a nice app that can tell me if my website is down or not, then send it to twitter.
class Tweet(webapp.RequestHandler):
def get(self):
import oauth
client = oauth.TwitterClient(TWITTER_CONSUMER_KEY,
TWITTER_... | [
"You could use Google App Engine URL Fetch API.\nThe fetch() function returns a Response object containing the HTTP status_code.\nJust fetch the url and check the status with something like this:\nfrom google.appengine.api import urlfetch\ndef is_down(url):\n result = urlfetch.fetch(url, method = urlfetch.HEAD)\... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004090116_google_app_engine_python.txt |
Q:
Python Timers not working
I have the following code:
def countdown():
def countdown1():
print 'countdown1'
def countdown2():
def countdown3():
takePic()
self.pic.set_markup("<span size='54000'>1</spa... | Python Timers not working | I have the following code:
def countdown():
def countdown1():
print 'countdown1'
def countdown2():
def countdown3():
takePic()
self.pic.set_markup("<span size='54000'>1</span>");
print... | [
"Your main thread is probably exiting before any timers fire. The simplest and crudest way to fix this is to get the main thread to sleep for as long as necessary. A saner option is to signal something like a semaphore at the end of countdown3 and wait on it in the main thread.\nA more elegant solution, which can b... | [
2,
1,
0
] | [] | [] | [
"multithreading",
"python",
"timer"
] | stackoverflow_0004092053_multithreading_python_timer.txt |
Q:
How can I improve my paw detection?
After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws.
You see, my proof of concept basically took the max... | How can I improve my paw detection? | After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws.
You see, my proof of concept basically took the maximal pressure of each sensor over time an... | [
"If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: SciPy's ndimage.morphology module. This is a fairly common image morphology operation. \n\nBasically, you have 5 steps:\ndef find_paws(data, smooth_radius=5, threshold=0.0001):\n data = sp.ndimage.uniform_filter... | [
363,
5,
1
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0004087919_image_processing_python.txt |
Q:
py2exe error when compiling
i was made some python script and i want to make this script to exe file.
but when compiling this script to exe, some error encounter i was try to resolve this problem
but no luck.
following is script source
if anyone can help me really much appreciate!
# -*- coding: utf-8 -*-
import ... | py2exe error when compiling | i was made some python script and i want to make this script to exe file.
but when compiling this script to exe, some error encounter i was try to resolve this problem
but no luck.
following is script source
if anyone can help me really much appreciate!
# -*- coding: utf-8 -*-
import lxml,cookielib,urllib,configobj,s... | [
"Looks to me like you're printing gzipped data to the command line. Possibly because the data returned by the server is not being decompressed by urllib when it is compiled to an exe.\nTry manually removing the Accept-Encoding header, this would prevent the server from returning compressed data and prevent your scr... | [
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0004052385_py2exe_python.txt |
Q:
Creating aliases for Python packages?
I have a directory, let's call it Storage full of packages with unwieldy names like mypackage-xxyyzzww, and of course Storage is on my PYTHONPATH. Since packages have long unmemorable names, all of the packages are symlinked to friendlier names, such as mypackage.
Now, I don't... | Creating aliases for Python packages? | I have a directory, let's call it Storage full of packages with unwieldy names like mypackage-xxyyzzww, and of course Storage is on my PYTHONPATH. Since packages have long unmemorable names, all of the packages are symlinked to friendlier names, such as mypackage.
Now, I don't want to rely on file system symbolic links... | [
"Instead of using imp, you can assign different names to imported modules.\nimport mypackage_xxyyzzww as mypackage\n\nIf you then create a __init__.py file inside of Storage, you can add several of the above lines to make importing easier.\nStorage/__init__.py:\nimport mypackage_xxyyzzww as mypackage\nimport otherp... | [
10,
4,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0004090945_package_python.txt |
Q:
Why does setting a default parameter value make this function a closure?
I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results:
class Tag(object):
def __in... | Why does setting a default parameter value make this function a closure? | I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results:
class Tag(object):
def __init__(self, name):
self.name = name
self.links = []
def __repr__(sel... | [
"This is a common mistake in Python:\ndef tag_chain(tag, known=[]):\n # ...\n\nknown=[] doesn't mean that if known is unsupplied, make it an empty list; in fact, it binds known to an \"anonymous\" list. Each time that known defaults to that list, it is the same list.\nThe typical pattern to do what you intended h... | [
9,
3
] | [] | [] | [
"closures",
"python",
"recursion"
] | stackoverflow_0004092233_closures_python_recursion.txt |
Q:
Running python 64 with shebang (#!) on Mac
I use python 64bit as follows.
alias python64='arch -x86_64 /usr/bin/python2.6'
How can I run python 64bit mode with shebang(#!)?
??? #!/usr/bin/python2.6 ???
A:
#!/path/to/arch -x86_64 /usr/bin/python2.6
I dont have a mac to test right now, but usually in *nix you... | Running python 64 with shebang (#!) on Mac | I use python 64bit as follows.
alias python64='arch -x86_64 /usr/bin/python2.6'
How can I run python 64bit mode with shebang(#!)?
??? #!/usr/bin/python2.6 ???
| [
"#!/path/to/arch -x86_64 /usr/bin/python2.6\n\nI dont have a mac to test right now, but usually in *nix you can find the path to an executable using:\nwhich arch\n\n",
"In OS X 10.6 arch is /usr/bin/arch, so your line is\n#!/usr/bin/arch -x86_64 /usr/bin/python2.6\n\nIn general, if you don't know the path you can... | [
1,
1
] | [] | [] | [
"64_bit",
"python",
"shebang"
] | stackoverflow_0004092497_64_bit_python_shebang.txt |
Q:
Reportlab PDF version generation problems
I am using reportlab PDF package with platypus to generate some PDF files. On linux server and on windows box I have the same python application, same version of reportlab package (although slightly different python version - 2.6.5 vs 2.6.6). I am using my own fonts, I do ... | Reportlab PDF version generation problems | I am using reportlab PDF package with platypus to generate some PDF files. On linux server and on windows box I have the same python application, same version of reportlab package (although slightly different python version - 2.6.5 vs 2.6.6). I am using my own fonts, I do not depend on system fonts. Lately, I have noti... | [
"Are you attempting to generate them with the exact code on each system? I did a quick search in the reportlab source code and found some comments stating that if you utilize the setFillAlpha or setStrokeAlpha methods then it will cause a PDF 1.4 to be generated instead of 1.3.\nEdit:\nLooking further, I'm fairly c... | [
1
] | [] | [] | [
"pdf_generation",
"python",
"reportlab"
] | stackoverflow_0004091043_pdf_generation_python_reportlab.txt |
Q:
Passing strings[]'s as byte[]
I'm working on a network in which my python script will communicate with my java application. The python script is passing a DataPacket (just a packet that holds some strings and a little other data) to the java server for processing. I know how to pack the information into a byte arr... | Passing strings[]'s as byte[] | I'm working on a network in which my python script will communicate with my java application. The python script is passing a DataPacket (just a packet that holds some strings and a little other data) to the java server for processing. I know how to pack the information into a byte array, but how do I unpack it to be us... | [
"I'm not sure that what you're doing is quite right, in that you're fragmenting your strings into separate packets. This could cause problems with multibyte strings.\nHowever, you may wish to check out ByteArrayOutputStream. You can write into this, then convert to a String using toString(enc), where enc is the enc... | [
1
] | [] | [] | [
"byte",
"inputstream",
"java",
"networking",
"python"
] | stackoverflow_0004092604_byte_inputstream_java_networking_python.txt |
Q:
Python - BeautifulSoup html parsing handle gbk encoding poorly - Chinese webscraping problem
I have been tinkering with the following script:
# -*- coding: utf8 -*-
import codecs
from BeautifulSoup import BeautifulSoup, NavigableString,
UnicodeDammit
import urllib2,sys
import time
try:
import timeoutsocket ... | Python - BeautifulSoup html parsing handle gbk encoding poorly - Chinese webscraping problem | I have been tinkering with the following script:
# -*- coding: utf8 -*-
import codecs
from BeautifulSoup import BeautifulSoup, NavigableString,
UnicodeDammit
import urllib2,sys
import time
try:
import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py
timeoutsocket.setDefaultSocketTimeout(10)
e... | [
"The file's meta tag claims that the character set is GB2312, but the data contains a character from the newer GBK/GB18030 and this is what's tripping BeautifulSoup up:\n\nsimon@lucifer:~$ python\nPython 2.7 (r27:82508, Jul 3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyrig... | [
5
] | [] | [] | [
"beautifulsoup",
"python",
"unicode",
"unicode_string",
"web_scraping"
] | stackoverflow_0004092606_beautifulsoup_python_unicode_unicode_string_web_scraping.txt |
Q:
subclassing float to force fixed point printing precision in python
[Python 3.1]
I'm following up on this answer:
class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
I know I need to keep track of my float literals (i.e., replace 3.0 with prettyfloat(3.0), etc.), and that's fine.
But whenev... | subclassing float to force fixed point printing precision in python | [Python 3.1]
I'm following up on this answer:
class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
I know I need to keep track of my float literals (i.e., replace 3.0 with prettyfloat(3.0), etc.), and that's fine.
But whenever I do any calculations, prettyfloat objects get converted into float.
W... | [
"I had a look at the answer you followed up on, and I think you're confusing data and its representation.\n@Robert Rossney suggested to subclass float so you could map() an iterable of standard, non-adulterated floats into prettyfloats for display purposes:\n# Perform all our computations using standard floats.\nre... | [
5,
3,
1
] | [] | [] | [
"built_in_types",
"floating_point",
"python",
"python_3.x",
"subclass"
] | stackoverflow_0004092674_built_in_types_floating_point_python_python_3.x_subclass.txt |
Q:
Link 2 attributes in a database
We are looking for advice to find a solution to this problem :
We consider that we have the following database table
Article (id, title, content)
We store 2 articles on this table
article1(1, title1, content1)
article2(2, title2, content2)
The primary key is the id and we want to kn... | Link 2 attributes in a database | We are looking for advice to find a solution to this problem :
We consider that we have the following database table
Article (id, title, content)
We store 2 articles on this table
article1(1, title1, content1)
article2(2, title2, content2)
The primary key is the id and we want to know if there is a way to "link" the ar... | [
"This is RDBS 101 but I'll answer anyway. Setup some schema like this:\narticle\n id\n title_id\n content\n\ntitle\n id\n title\n\nThen you can get the articles and titles using an INNER JOIN.\nSELECT\n article.id,\n title.title,\n article.content\nFROM article \nINNER JOIN title ON\n tit... | [
1
] | [] | [] | [
"content_management_system",
"database",
"python"
] | stackoverflow_0004092827_content_management_system_database_python.txt |
Q:
how to verify a hash in python?
I have a hashtable in python of strings. So, each entry is a string. The strings could possibly start with "/" which implies they are file names.
What would be a quick way to take a hashtable like this, and for each string in it that starts with a "/" verify whether the file exists?... | how to verify a hash in python? | I have a hashtable in python of strings. So, each entry is a string. The strings could possibly start with "/" which implies they are file names.
What would be a quick way to take a hashtable like this, and for each string in it that starts with a "/" verify whether the file exists?
If the file does not exist, then the... | [
"To find if the string begins with a forward slash:\nstr.startswith('/')\n\nor\nstr[0] == '/'\n\nTo find if a file is valid:\nimport os.path\nos.path.exists(str)\n\nYou can loop through your hashtable using a for statement. Putting it all together (assuming the potential paths are the values in the hashtable [call... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004092886_python.txt |
Q:
Eliminate dups and sum corresponding terms in lists
Given these 2 lists
L2 = [A,B,C,D,A,B]
L3 = [3,2,1,2,2,1]
I want to obtain
L2_WANTED = [A,B,C,D]
L3_WANTED = [5,3,1,2]
The lists are always ordered and same size and elements correspond as key value pairs eg A:3, B:2 and so on.
The objective is to eliminate the... | Eliminate dups and sum corresponding terms in lists | Given these 2 lists
L2 = [A,B,C,D,A,B]
L3 = [3,2,1,2,2,1]
I want to obtain
L2_WANTED = [A,B,C,D]
L3_WANTED = [5,3,1,2]
The lists are always ordered and same size and elements correspond as key value pairs eg A:3, B:2 and so on.
The objective is to eliminate the dups in L2 and sum the corresponding terms in L3 to obta... | [
"I am sure there are more elegant answer there and would come in the replies.\nBut for some simple answers:\nL2 = ['A','B','C','D','A','B']\nL3 = [3,2,1,2,2,1]\n\nL4 = zip(L2, L3)\n\nL5 = []\nL6 = []\ndef freduce(l):\n for x, y in l:\n print x , y\n if x in L5:\n k = L5.index(x)\n ... | [
2,
2,
1
] | [] | [] | [
"list_comprehension",
"python",
"python_itertools"
] | stackoverflow_0004084369_list_comprehension_python_python_itertools.txt |
Q:
How would I implement a ranking algorithm in my website to sort database data?
I want to implement a ranking system on a website I've been working on and have decided to go with the Hacker News algorithm. My reasoning for choosing this algorithm is simply because it's been described here.
I was looking at this Pyt... | How would I implement a ranking algorithm in my website to sort database data? | I want to implement a ranking system on a website I've been working on and have decided to go with the Hacker News algorithm. My reasoning for choosing this algorithm is simply because it's been described here.
I was looking at this Python code (the language I'm using to build my site) and couldn't figure out how I wou... | [
"You can use the data you need in the ORDER BY clause.\nSELECT p.id, p.title, p.time_submitted, SUM(v.score) as num_votes \n FROM posts p, votes v\n WHERE v.postid = p.id\nGROUP BY p.id\nORDER BY \n (SUM(v.score) - 1) / POW(TIMESTAMPDIFF(HOUR,p.time_submitted,NOW()) + INTERVAL 2 HOUR, 1.8) DESC\nLIMIT 100\n\n",
... | [
4,
0
] | [] | [] | [
"algorithm",
"implementation",
"python",
"sql"
] | stackoverflow_0004093115_algorithm_implementation_python_sql.txt |
Q:
Python: Programming 8051
Can I program 8051 using Python?
I'm not getting any of the to program 8051 in python environment.
If anybody knows, please help me.
A:
There is Python-on-a-Chip, but note its "disclaimer":
"The PyMite VM DOES NOT HAVE:
A built-in compiler
Any of Python's libraries (no batteries includ... | Python: Programming 8051 | Can I program 8051 using Python?
I'm not getting any of the to program 8051 in python environment.
If anybody knows, please help me.
| [
"There is Python-on-a-Chip, but note its \"disclaimer\":\n\n\"The PyMite VM DOES NOT HAVE:\n\nA built-in compiler\nAny of Python's libraries (no batteries included)\nA ready-to-go solution for the beginner (you need to know C and how to work with microcontrollers)\"\n\n\nThus, if the questioner's goal for python wa... | [
6,
4
] | [] | [] | [
"8051",
"low_level",
"microcontroller",
"python"
] | stackoverflow_0004059703_8051_low_level_microcontroller_python.txt |
Q:
How do I monitor a "stuck" Python script?
I have a data-intensive Python script that uses HTTP connections to download data. I usually run it overnight. Sometimes the connection will fail, or a website will be unavailable momentarily. I have basic error-handling that catches these exceptions and tries again period... | How do I monitor a "stuck" Python script? | I have a data-intensive Python script that uses HTTP connections to download data. I usually run it overnight. Sometimes the connection will fail, or a website will be unavailable momentarily. I have basic error-handling that catches these exceptions and tries again periodically, exiting gracefully (and logging errors)... | [
"It sounds like there is a bug in your script. The answer is not to monitor the bug, but to hunt down the bug and fix it.\nWe can't help you find the bug without seeing some code. But as a general idea, you might want to use logging to pinpoint where the problem is occurring, and write unit tests to help you build ... | [
7,
4,
1,
1
] | [] | [] | [
"freebase",
"python",
"scripting",
"sockets",
"urllib2"
] | stackoverflow_0004093166_freebase_python_scripting_sockets_urllib2.txt |
Q:
I use tornado frameworks. I can use dict and list types in tornado templates, but when I use a object in the templates, it render as memory address
for detail. I import Solrpy package to use. As for the document on Django project to introduce the pagenator. I pass the pagenator.page (Solrpage) object to tornado te... | I use tornado frameworks. I can use dict and list types in tornado templates, but when I use a object in the templates, it render as memory address | for detail. I import Solrpy package to use. As for the document on Django project to introduce the pagenator. I pass the pagenator.page (Solrpage) object to tornado template
but it doesn't work. I can'd use any method of Solrpage. instead it is rendered as a memory address.
below is the way to use the paginator , whic... | [
"Your class definition needs a __str__( self ) method to render as something other than a random address in a template.\n"
] | [
2
] | [] | [] | [
"pagination",
"python",
"solr",
"tornado"
] | stackoverflow_0004093540_pagination_python_solr_tornado.txt |
Q:
dynamically assigning function to __dir__ of an instance
I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried:
import types
cla... | dynamically assigning function to __dir__ of an instance | I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried:
import types
class Foo(object):
def __init__(self, arg):
def __dir... | [
"Ok, based on your comment I worked things a bit. I think this might be closer to the behavior you're looking for. Calling dir with no args gives all the names in the local scope and calling it on __class__ gives all class names. This ignores the defined __dir__ which can be called later on. I'm curious what you're... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004093607_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.