Re: 3.0rc3: 'os.extsep' gone ... ?
Terry Reedy wrote: The doc for os.path begins This module implements some useful functions on pathnames. os.path contains functions that work differently on different systems. It is in fact a variable that is initialized to point to posixpath, ntpath etc as appropriate for the current system http://docs.python.org/library/undoc.html#platform-specific-modules. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
r0g wrote: Cong Ma wrote: Dear all, Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Thanks for your reply. Regards, Cong. for each in os.listdir(os.getcwd()): print each Roger. -- http://mail.python.org/mailman/listinfo/python-list Roger, It seemed I didn't make it clearly enough... Your code fetches a bunch of strings representing file names in the working directory, which is fine. But what I want is something like an integer file descriptor, like the one returned by os.open() for files, or the Linux dirfd() call, which returns an integer for a pointer to a DIR stream. Regards, Cong. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
Cong Ma wrote: r0g wrote: Cong Ma wrote: Dear all, Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Thanks for your reply. Regards, Cong. for each in os.listdir(os.getcwd()): print each Roger. -- http://mail.python.org/mailman/listinfo/python-list Roger, It seemed I didn't make it clearly enough... Your code fetches a bunch of strings representing file names in the working directory, which is fine. But what I want is something like an integer file descriptor, like the one returned by os.open() for files, or the Linux dirfd() call, which returns an integer for a pointer to a DIR stream. Regards, Cong. Erm, yeah, that's the os.listdir() bit. Roger. -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On Tue, 25 Nov 2008 07:27:41 +, John O'Hagan wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d or this: class Class_b(): def method_ab(self, args): a = args.a b = args.b return a + b def method_cd(self, args) c = args.c d = args.d return c + d ? Assuming we don't need access to the args from outside the class, is there anything to be gained (or lost) by not initialising attributes that won't be used unless particular methods are called? The question is if `args.a`, `args.b`, …, are semantically part of the state of the objects or not. Hard to tell in general. I know it's a made up example but in the second class I'd ask myself if those methods are really methods, because they don't use `self` so they could be as well be functions or at least `staticmethod`\s. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On 25 Nov, 08:27, John O'Hagan [EMAIL PROTECTED] wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d or this: class Class_b(): def method_ab(self, args): a = args.a b = args.b return a + b def method_cd(self, args) c = args.c d = args.d return c + d ? Assuming we don't need access to the args from outside the class, is there anything to be gained (or lost) by not initialising attributes that won't be used unless particular methods are called? Thanks, John O'Hagan If 'args' is an object of some class which has the attribute a,b,c,d, why don't you just add method_ab and method_cd to the same class, either directly or by sibclassing it? If for some reason you can't do the above, just make two functions: def function_ab(args): return args.a + args.b def function_cd(args): return args.c + args.d One good thing of Python is that you don't have to make classes if you don't need to ... Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
r0g wrote: Cong Ma wrote: r0g wrote: Cong Ma wrote: Dear all, Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Thanks for your reply. Regards, Cong. for each in os.listdir(os.getcwd()): print each Roger. -- http://mail.python.org/mailman/listinfo/python-list Roger, It seemed I didn't make it clearly enough... Your code fetches a bunch of strings representing file names in the working directory, which is fine. But what I want is something like an integer file descriptor, like the one returned by os.open() for files, or the Linux dirfd() call, which returns an integer for a pointer to a DIR stream. Regards, Cong. Erm, yeah, that's the os.listdir() bit. Roger. Actually, just re-reading your last mail, it isn't what you want at all is it?! Sorry! Roger. -- http://mail.python.org/mailman/listinfo/python-list
Re: Quick question about None and comparisons
Ok thanks. I'll avoid to do that. --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On 2008-11-25 08:27, John O'Hagan wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d or this: class Class_b(): def method_ab(self, args): a = args.a b = args.b return a + b def method_cd(self, args) c = args.c d = args.d return c + d ? That depends entirely on what you intend to do with objects of Class_a and Class_b. In the first case, you are persisting the argument attributes in the object, in the second case, you are merely working on them - just like you would in a function. Assuming we don't need access to the args from outside the class, is there anything to be gained (or lost) by not initialising attributes that won't be used unless particular methods are called? It is always good practice to provide default values for instance variables in the class definition, both to enhance readability and to allow adding documentation regarding the variables, e.g. class Class_a: # Foo bar a = None # Foo baz b = None ... -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 25 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2008-11-12: Released mxODBC.Connect 0.9.3 http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Django Latex Permissions Problem
I-T [EMAIL PROTECTED] wrote: I have a python/django webapp running with apache2. It executes system commands for getting a pdf generated by pdflatex from a .tex file and a couple of image files which it also generates. The permssions from ls-l for all the created files is:- -rw-r--r-- 1 www-data www-data The files are being created in /tmp/pdfscratch{id} created from the script and so is the directory. pdflatex fails with the following error message:- This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) %-line parsing enabled. entering extended mode ! I can't write on file `uber.log'. Please type another transcript file name: ! Emergency stop ! == Fatal error occurred, no output PDF file produced! Its supposed to write to this directory. I have a feeling that pdflatex is trying to generate files using some weird access credentials that dont have access to /tmp/pdfscratch{id} Unlikely - it takes root to change user and I wouldn't have thought any of the files would be setuid. Try chdir to /tmp/pdfscratch{id} first would be my suggestion. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: recommended __future__ imports for 2.5?
Dennis Lee Bieber [EMAIL PROTECTED] wrote: On Mon, 24 Nov 2008 13:36:32 -0700, Joe Strout [EMAIL PROTECTED] declaimed the following in comp.lang.python: older versions of Python with from __future__ import division. Once I stumbled across that, I was able to find the relevant PEP (#238) and read more about it. So now that import has become part of our standard boilerplate at the top of each file, along with the path to Python and the UTF-8 encoding declaration. I'm still waiting to hear that from __past__ import division will become a reality... ;-) I think that is called using // instead of / which works without any from __future__ import from python 2.2 onwards. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Python/C API: using from a shared library
Hi, If I use dlopen() to open a shared library that I've written, and that shared library tries to use the Python/C API, then it fails. I've reduced the problem to the test case below. The error is: ImportError: /usr/lib/python2.5/lib-dynload/time.so: undefined symbol: PyExc_ValueError It appears that time.so tries to resolve PyExc_ValueError out of my program instead of libpython.so. I'm using Ubuntu 8.04, so that's Python 2.5.2. How do I go about getting this to work? Is this a bug in lib-dynload, or am I using the wrong linker flags? Would this be better asked in python-dev? Thanks, Robie /* Start of mylib.c */ /* Compile with: gcc -I/usr/include/python2.5 -fno-strict-aliasing -g -fwrapv -Wall -Wstrict-prototypes -L/usr/lib/python2.5/config -fPIC -shared -l:libpython2.5.so.1 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions -o mylib.so mylib.c */ #include Python.h #include stdio.h int init(void) { PyObject *module; module = PyImport_ImportModule(time); if(!module) { fprintf(stderr, python module load failed\n); PyErr_Print(); return -1; } Py_DECREF(module); return 0; } void init_module(void) { fprintf(stderr, python initalizing\n); Py_Initialize(); fprintf(stderr, python initialized\n); } /* vim: set ts=8 sts=4 sw=4 ai : */ /* End of mylib.c */ /* Start of myprog.c */ /* Compile with: gcc -o myprog -ldl myprog.c */ #include dlfcn.h #include stdio.h int main(int argc, char **argv) { void *lib; int (*init)(void); void (*init_module)(void); char *error; lib = dlopen(./mylib.so, RTLD_LAZY); if(!lib) { fprintf(stderr, %s\n, dlerror()); return 1; } dlerror(); *(void **) (init_module) = dlsym(lib, init_module); if((error=dlerror()) != NULL) { fprintf(stderr, %s\n, error); return 1; } (*init_module)(); *(void **) (init) = dlsym(lib, init); if((error=dlerror()) != NULL) { fprintf(stderr, %s\n, error); return 1; } (*init)(); dlclose(lib); return 0; } /* vim: set ts=8 sw=4 sts=4 ai : */ /* End of myprog.c */ -- http://mail.python.org/mailman/listinfo/python-list
Getting in to metaprogramming
Hi, In the name of self-education can anyone share some pointers, links, modules, etc that I might use to begin learning how to do some metaprogramming. That is, using code to write code (right?) Cheers, - Rafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
On Nov 25, 11:08 am, Rafe [EMAIL PROTECTED] wrote: Hi, In the name of self-education can anyone share some pointers, links, modules, etc that I might use to begin learning how to do some metaprogramming. That is, using code to write code (right?) Cheers, - Rafe The word metaprogramming has many meanings. It covers code generation, as you say, but also a lots of other techniques; for instance you do metaprogramming with decorators when write functions operating over functions, or with metaclasses when you write classes operating over classes. You should clarify what you are interested in. For instance, are you interested in metaprogramming in Python only or you want a more general introduction? Have you read the Wikipedia entry? http://en.wikipedia.org/wiki/Metaprogramming -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
snip It is always good practice to provide default values for instance variables in the class definition, both to enhance readability and to allow adding documentation regarding the variables, e.g. class Class_a: # Foo bar a = None # Foo baz b = None snip Those are not instance 'variables' (attributes), they are class attributes. I used to do that in JScript, so I did it in python when I moved over. It caused a lot of trouble for me as a beginner. I was eventually given the advice to stop it. I haven't looked back since (until now). I think you would just be adding a new self.a which blocks access to your class.a, but I'm still shaky on this knowledge. Instance attribute defaults would be inside __init__() and before unpacking the *args. - Rafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On Tue, 25 Nov 2008, Marc 'BlackJack' Rintsch wrote: On Tue, 25 Nov 2008 07:27:41 +, John O'Hagan wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d or this: class Class_b(): def method_ab(self, args): a = args.a b = args.b return a + b def method_cd(self, args) c = args.c d = args.d return c + d ? Assuming we don't need access to the args from outside the class, is there anything to be gained (or lost) by not initialising attributes that won't be used unless particular methods are called? The question is if `args.a`, `args.b`, …, are semantically part of the state of the objects or not. Hard to tell in general. Would you mind elaborating a little on that first sentence? I know it's a made up example but in the second class I'd ask myself if those methods are really methods, because they don't use `self` so they could be as well be functions or at least `staticmethod`\s. I guess I went overboard keeping the example simple :) : the real case has many methods, and they all use self (except one, actually, so I'm looking up static methods now; thanks). Regards, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On Tue, 25 Nov 2008 10:48:01 +, John O'Hagan wrote: On Tue, 25 Nov 2008, Marc 'BlackJack' Rintsch wrote: On Tue, 25 Nov 2008 07:27:41 +, John O'Hagan wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d […] The question is if `args.a`, `args.b`, …, are semantically part of the state of the objects or not. Hard to tell in general. Would you mind elaborating a little on that first sentence? Do `self.a`, `self.b`, …, define the state of a `Class_a` instance or not? One can't answer that question without knowing the meaning of the class and the attributes. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
On Nov 25, 5:48 pm, John O'Hagan [EMAIL PROTECTED] wrote: On Tue, 25 Nov 2008, Marc 'BlackJack' Rintsch wrote: On Tue, 25 Nov 2008 07:27:41 +, John O'Hagan wrote: Is it better to do this: class Class_a(): def __init__(self, args): self.a = args.a self.b = args.b self.c = args.c self.d = args.d def method_ab(self): return self.a + self.b def method_cd(self): return self.c + self.d or this: class Class_b(): def method_ab(self, args): a = args.a b = args.b return a + b def method_cd(self, args) c = args.c d = args.d return c + d ? Assuming we don't need access to the args from outside the class, is there anything to be gained (or lost) by not initialising attributes that won't be used unless particular methods are called? The question is if `args.a`, `args.b`, …, are semantically part of the state of the objects or not. Hard to tell in general. Would you mind elaborating a little on that first sentence? I know it's a made up example but in the second class I'd ask myself if those methods are really methods, because they don't use `self` so they could be as well be functions or at least `staticmethod`\s. I guess I went overboard keeping the example simple :) : the real case has many methods, and they all use self (except one, actually, so I'm looking up static methods now; thanks). Regards, John I'm not sure if you are asking a technical question or a design question. If it helps, I try to think of an object as a thing which has a job to do. If the 'thing' needs information every time to define what it is, or give it a starting state, then that is an argument of __init__() . If I want the object to change or handle something which is a logical task of 'thing', then I give it what it needs via properties or methods (I find I almost never use public instance attributes, but then again I am usually writing SDKs which is all about interface). Not sure if that helps... - Rafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
On Nov 25, 5:41 pm, Aaron Brady [EMAIL PROTECTED] wrote: On Nov 25, 4:08 am, Rafe [EMAIL PROTECTED] wrote: Hi, In the name of self-education can anyone share some pointers, links, modules, etc that I might use to begin learning how to do some metaprogramming. That is, using code to write code (right?) Cheers, - Rafe Python programs can generate code for themselves. for i in range( 10 ): ... d= { 'cls': i } ... s= ... class Cls%(cls)s: ... def meth%(cls)s( self, arg ): ... print 'in meth%(cls)s, arg:', arg ... % d ... exec( s ) ... s= ... inst%(cls)s= Cls%(cls)s() ... % d ... exec( s ) ... inst0.meth0( arg ) in meth0, arg: arg inst1.meth1( arg ) in meth1, arg: arg inst2.meth2( arg ) in meth2, arg: arg The 'Cls0', 'Cls1', 'Cls2' repetitiveness is taken care of with a for- loop. Michele, I am thinking about python which writes python. Which makes Aaron's post accurate to my needs. More specifically, I am considering what it might be like to use python to build a script file which can be executed later. Until now I planned to store info to XML and then parse it to run later. There are good reasons that generating a script file would be more useful for me. Aaron, Is it really as simple as gathering strings of code? Sort of like generating HTML or XML directly? Is there any other framework or pattern set that is worth looking in to? Thanks for helping me explore this. - Rafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
On Nov 25, 12:12 pm, Rafe [EMAIL PROTECTED] wrote: is it really as simple as gathering strings of code? Yes. Sort of like generating HTML or XML directly? Is there any other framework or pattern set that is worth looking in to? Yes, the compiler module and the ast module in the standard library. You may also look at how templating languages that compile to Python code work (I mean mako or PTL/qpy). You may find interesting how the import hooks work too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple equates
On Nov 17, 7:41 pm, Tim Chase [EMAIL PROTECTED] wrote: It doesn't matter as none of this is valid Python. In Python you have to write array[x1] = False array[x2] = False Uh...not so much... a = [1,2,3,4,5] x1, x2 = 1, 3 a[x1] = a[x2] = False a [1, False, 3, False, 5] Works for me. To the OP, I think rather than cluttering my code, I'd just create a loop for i in [x1,x2,x3,x4,...x1024]: a[i] = False From Diez's disassembly of it (as an aside, nifty little intro to dis.dis()...thanks, Diez!), it looks like it boils down to is DUP_TOP faster than LOAD_CONST because the rest of the operations. At this point, it's pretty nitty-gritty. Unless the code is in an inner loop somewhere, the simple loop should be more than fast enough. Without knowing the source of the [x1,...] index variables, it's hard to tell if there's a more optimal way to do this. -tkc The loop is much nicer, especially as your array gets longer. The generic: for i in xrange(array): array[i] = False will set the entire array. Regarding your original question: array[x1] = array[x2] = False array[x1] = False array[x2] = False These two blocks are functionally the same when you are setting to True or False (or any immutable), but are not if setting to immutables, which could give you some real head-scratching bugs if you were unaware of the difference - the first version assigns the same object to both names: array[x1] = array[x2] = [] array[x1].append(Hi) array[x2] ['Hi'] Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
On Nov 25, 4:08 am, Rafe [EMAIL PROTECTED] wrote: Hi, In the name of self-education can anyone share some pointers, links, modules, etc that I might use to begin learning how to do some metaprogramming. That is, using code to write code (right?) Cheers, - Rafe Python programs can generate code for themselves. for i in range( 10 ): ... d= { 'cls': i } ... s= ... class Cls%(cls)s: ... def meth%(cls)s( self, arg ): ... print 'in meth%(cls)s, arg:', arg ... % d ... exec( s ) ... s= ... inst%(cls)s= Cls%(cls)s() ... % d ... exec( s ) ... inst0.meth0( arg ) in meth0, arg: arg inst1.meth1( arg ) in meth1, arg: arg inst2.meth2( arg ) in meth2, arg: arg The 'Cls0', 'Cls1', 'Cls2' repetitiveness is taken care of with a for- loop. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple equates
On Nov 25, 11:29 am, Iain King [EMAIL PROTECTED] wrote: On Nov 17, 7:41 pm, Tim Chase [EMAIL PROTECTED] wrote: It doesn't matter as none of this is valid Python. In Python you have to write array[x1] = False array[x2] = False Uh...not so much... a = [1,2,3,4,5] x1, x2 = 1, 3 a[x1] = a[x2] = False a [1, False, 3, False, 5] Works for me. To the OP, I think rather than cluttering my code, I'd just create a loop for i in [x1,x2,x3,x4,...x1024]: a[i] = False From Diez's disassembly of it (as an aside, nifty little intro to dis.dis()...thanks, Diez!), it looks like it boils down to is DUP_TOP faster than LOAD_CONST because the rest of the operations. At this point, it's pretty nitty-gritty. Unless the code is in an inner loop somewhere, the simple loop should be more than fast enough. Without knowing the source of the [x1,...] index variables, it's hard to tell if there's a more optimal way to do this. -tkc The loop is much nicer, especially as your array gets longer. The generic: for i in xrange(array): array[i] = False will set the entire array. Regarding your original question: array[x1] = array[x2] = False array[x1] = False array[x2] = False These two blocks are functionally the same when you are setting to True or False (or any immutable), but are not if setting to immutables, which could give you some real head-scratching bugs if you were unaware of the difference - the first version assigns the same object to both names: array[x1] = array[x2] = [] array[x1].append(Hi) array[x2] ['Hi'] Iain ...and of course, the second time I say 'immutable' I mean 'mutable'. Hopefully the example was clearer than the text. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
On Nov 25, 5:05 pm, Cong Ma [EMAIL PROTECTED] wrote: Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Try: os.open('dirname', os.O_RDONLY) Check os for a list of the valid flag types. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
On Nov 25, 9:53 pm, alex23 [EMAIL PROTECTED] wrote: On Nov 25, 5:05 pm, Cong Ma [EMAIL PROTECTED] wrote: Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Try: os.open('dirname', os.O_RDONLY) Check os for a list of the valid flag types. Sorry, that should probably be os.O_DIRECTORY. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't find Python Library packages in Ubuntu (Debian)
Scott David Daniels wrote: So, the first question is: How do I install the complete Python test framework under Ubuntu (Debian)? You could use BZR or SVN to get a copy of the full Lib/test tree. Given your long-disconnected running, I'd consider getting a full source set for release25-maint. Note that as of Python 2.6 / 3.0, if Python is not restricted to system directories for security reasons (if sys.flags.no_user_site is non-0), you may make a directory in your home directory to be searched. See http://docs.python.org/library/site.html for details on USER_SITE and USER_BASE. That will allow you to place a test subdirectory under site.USER_SITE and get to test.test_list (for example) on your python search path. Since it is a user-specific location, you can make a tester user with the directory in his own space and not worry about affecting the standard environment. Since I already compiled Python 2.6, and am using it basically only for testing purposes, this won't be necessary, right now. But someday, Python 2.6 will get released for Debian, and if it doesn't ship with the tests, I will come back your instructions. - Thanks, Scott! Paul Boddie wrote: I will try to contact whoever is responsible for the packaging of Python in Ubuntu (or Debian), and ask them if they are willing to support the _complete_ Python release. They may already do so, but I'd argue that they could document the packages which provide the complete release a bit better if these are not already mentioned in /usr/share/doc/python/README.Debian or some similar file. You are right, /usr/share/doc/python2.5/README.Debian , should contain that information, but it doesn't. I already filed a bug in Launchpad, and will move upstream, if necessary. By looking at the documentation for the Debian stable source package, I did manage to find a list of generated packages: http://packages.debian.org/source/etch/python-defaults Perhaps one of these contains the test files. I checked the most obvious packages there manually without success before posting my question here. I also used apt-file, which searches for a specific file in _all_ available packages, including not installed ones, ...no success, again. Although such files are arguably only of use to people building Python, and such people would therefore obtain the source package in order to perform the build process, there could be some benefit in having a package which provides these files separately. For example, one may wish to verify the behaviour of an installed version or to test aspects of another implementation. My personal interest in these tests is the following: I was working with some sequential dictionaries from ActiveState, but experienced problems with all recipes. I started writing my own test cases, but found somewhere a reference about test_dict, test_list et al. Using these, I've been able to fix a few problems. (Even if some test cases are quite difficult to interpret right now.) In general, I think that the Python test suite is extrermely valuable, and should be made more accessible to all users. Especially in combination with Python's new Abstract Base Classes, They could prove extremely useful in creating robust classes with standard interfaces. But I digress. Thank you, Paul! -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Modification Time of an Outlook Mail in Python
On Nov 25, 5:11 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi all, I am writing a small application which reads the contents of an Outlook Mail using python. I am able to read the contents, subject along with senders and receivers of a mail using MAPI objects. But may I know how can I get access to the modification time or the receiving time of an outlook mail in Python. For the others I have used message object of MAPI session. Here I am pasting a sample code to get an idea of what am I doing. session = Dispatch(MAPI.session) session.Logon('outlook') # MAPI profile name inbox = session.Inbox print Inbox name is:, inbox.Name print Number of messages:, inbox.Messages.Count for i in range(inbox.Messages.Count): message = inbox.Messages.Item(i + 1) objSender = message.Sender.Address objRecip = message.Recipients.Item(j+1) Now here I want to access the modification time of each mail. And if possible if you can guide me to a place where I can get the elements of that message object, that would be helpful. Please mail back for further information. Thanks in advance, Venu. This looks like the API for the Message object: http://msdn.microsoft.com/en-us/library/ms526130(EXCHG.10).aspx Looks like you want TimeLastModified Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Modification Time of an Outlook Mail in Python
Venu ... may I know how can I get access to the modification time or Venu the receiving time of an outlook mail in Python... I have no idea off the top of my head, but you might want to browse the SpamBayes Outlook plugin source code for various ways to manipulate Outlook messages. http://spambayes.svn.sourceforge.net/viewvc/spambayes/trunk/spambayes/Outlook2000/ -- Skip Montanaro - [EMAIL PROTECTED] - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-list
datetime objects and __new__()
Hi -- import datetime class ts(datetime.datetime): ... foo = 'bar' ... def __new__(cls, s): ... c = super(ts, cls) ... return c.fromtimestamp(s) ... t = ts(0) Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __new__ TypeError: __new__() takes exactly 2 arguments (9 given) I don't understand why that happens -- am I correct in assuming that the call to .fromtimestamp() is picking up on the ts class? Shouldn't it get the datetime class instead? (Yes, I am aware of the problems of using datetime and timestamps) Could some kind soul please enlighten me? peter. -- http://mail.python.org/mailman/listinfo/python-list
Re: initialized list: strange behavior
Jason Scheirer [EMAIL PROTECTED] writes: On Nov 24, 10:34 pm, [EMAIL PROTECTED] wrote: Hi Python experts! Please explain this behavior: nn=3*[[]] nn [[], [], []] mm=[[],[],[]] mm [[], [], []] Up till now, 'mm' and 'nn' look the same, right? Nope! mm[1].append(17) mm [[], [17], []] nn[1].append(17) nn [[17], [17], [17]] ??? Python 2.5 Win XP Thanks! You're creating three references to the same list with the multiplication operator. There's no need to introduce references: you're creating a list with the same object at each position. [...] Python is pass-by-reference, not pass-by-value. It's certainly not pass-by-reference, nor is it pass-by-value IMHO. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: initialized list: strange behavior
On Tue, Nov 25, 2008 at 9:23 AM, Arnaud Delobelle [EMAIL PROTECTED]wrote: Jason Scheirer [EMAIL PROTECTED] writes: On Nov 24, 10:34 pm, [EMAIL PROTECTED] wrote: Hi Python experts! Please explain this behavior: nn=3*[[]] nn [[], [], []] mm=[[],[],[]] mm [[], [], []] Up till now, 'mm' and 'nn' look the same, right? Nope! mm[1].append(17) mm [[], [17], []] nn[1].append(17) nn [[17], [17], [17]] ??? Python 2.5 Win XP Thanks! You're creating three references to the same list with the multiplication operator. There's no need to introduce references: you're creating a list with the same object at each position. [...] Python is pass-by-reference, not pass-by-value. It's certainly not pass-by-reference, nor is it pass-by-value IMHO. Please don't get into this here. We have enough threads for this already. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
On Tue, 25 Nov 2008 16:02:56 +0800 Cong Ma [EMAIL PROTECTED] wrote: Can you give me some hint on getting a directory file descriptor in Python? for each in os.listdir(os.getcwd()): print each Your code fetches a bunch of strings representing file names in the working directory, which is fine. But what I want is something like an integer file descriptor, like the one returned by os.open() for files, or the Linux dirfd() call, which returns an integer for a pointer to a DIR stream. Is this what you want? ofiles = [open(x) for x in os.listdir(os.getcwd())] -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: initialized list: strange behavior
Arnaud Delobelle wrote: Jason Scheirer [EMAIL PROTECTED] writes: On Nov 24, 10:34 pm, [EMAIL PROTECTED] wrote: Hi Python experts! Please explain this behavior: nn=3*[[]] nn [[], [], []] mm=[[],[],[]] mm [[], [], []] Up till now, 'mm' and 'nn' look the same, right? Nope! mm[1].append(17) mm [[], [17], []] nn[1].append(17) nn [[17], [17], [17]] ??? Python 2.5 Win XP Thanks! You're creating three references to the same list with the multiplication operator. There's no need to introduce references: you're creating a list with the same object at each position. [...] Python is pass-by-reference, not pass-by-value. It's certainly not pass-by-reference, nor is it pass-by-value IMHO. Since no lists are being passed as arguments in these examples it's not pass-by-anything. Jump off that horse right now! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
peter wrote: import datetime class ts(datetime.datetime): ... foo = 'bar' ... def __new__(cls, s): ... c = super(ts, cls) ... return c.fromtimestamp(s) ... t = ts(0) Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __new__ TypeError: __new__() takes exactly 2 arguments (9 given) I don't understand why that happens -- am I correct in assuming that the call to .fromtimestamp() is picking up on the ts class? Shouldn't it get the datetime class instead? (Yes, I am aware of the problems of using datetime and timestamps) Could some kind soul please enlighten me? If the datetime class were implemented in Python the fromtimestamp() method could look like: @classmethod def fromtimestamp(cls, s): year, month, day,... = ... return cls(year, month, day,...) This will fail since you modified the constructor to accept only a single argument. Peter -- http://mail.python.org/mailman/listinfo/python-list
SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
In article [EMAIL PROTECTED], Ryan Kelly [EMAIL PROTECTED] wrote: * Migrated from SWIG to ctypes for the C binding: Ryan, I'm looking at a doing a Python wrapper for a C++ library. We've already done a Perl wrapper for this library using SWIG (I wasn't personally involved in that effort). I'm debating whether I should do the Python version with SWIG or ctypes. I'd be interested to hear about your experiences with both and why you switched. -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
On Nov 25, 3:46 pm, Peter Otten [EMAIL PROTECTED] wrote: peter wrote: import datetime class ts(datetime.datetime): ... foo = 'bar' ... def __new__(cls, s): ... c = super(ts, cls) ... return c.fromtimestamp(s) ... t = ts(0) Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __new__ TypeError: __new__() takes exactly 2 arguments (9 given) I don't understand why that happens -- am I correct in assuming that the call to .fromtimestamp() is picking up on the ts class? Shouldn't it get the datetime class instead? (Yes, I am aware of the problems of using datetime and timestamps) Could some kind soul please enlighten me? If the datetime class were implemented in Python the fromtimestamp() method could look like: @classmethod def fromtimestamp(cls, s): year, month, day,... = ... return cls(year, month, day,...) This will fail since you modified the constructor to accept only a single argument. Hm, I had hoped that using super() would result in calling the constructor of the superclass, ie. datetime. Did I use super() wrong? Thanks, peter. Peter -- http://mail.python.org/mailman/listinfo/python-list
any body know how to use winlike
Hi, Any body know how to use winlike.If yes.Can s/he give a simple example of onEvent onClose functionally. Actually i am facing problem where. I have one page there if u click on a text Winlike window will open.After opening i want to print text value,it is not printing.i am calling by parent.document.forms['formname'].getElementById(Id). parent.document.forms is giving an object but parent.document.forms['formname'] is giving undefined.I already tired all the possibility like opener/parent.window .So can anybody give any solution? Thanks Anuradha -- || Anuradha || -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
Roy I'm debating whether I should do the Python version with SWIG or Roy ctypes. Unless your C++ library exports a C api I don't think you can use ctypes to make it available within Python. -- Skip Montanaro - [EMAIL PROTECTED] - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: initialized list: strange behavior
The issue is exhausted in Python Library Reference, Chapter 3.6, so I should apologize for initial posting. All comments were helpful, though Arnaud and Steve are right that pass-by-anything is off the point. Thanks All! -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
Roy Smith wrote: In article [EMAIL PROTECTED], Ryan Kelly [EMAIL PROTECTED] wrote: * Migrated from SWIG to ctypes for the C binding: Ryan, I'm looking at a doing a Python wrapper for a C++ library. We've already done a Perl wrapper for this library using SWIG (I wasn't personally involved in that effort). I'm debating whether I should do the Python version with SWIG or ctypes. I'd be interested to hear about your experiences with both and why you switched. You can't use ctypes for C++, only for C-style APIs. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
peter wrote: On Nov 25, 3:46 pm, Peter Otten [EMAIL PROTECTED] wrote: peter wrote: import datetime class ts(datetime.datetime): ... foo = 'bar' ... def __new__(cls, s): ... c = super(ts, cls) ... return c.fromtimestamp(s) ... t = ts(0) Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __new__ TypeError: __new__() takes exactly 2 arguments (9 given) I don't understand why that happens -- am I correct in assuming that the call to .fromtimestamp() is picking up on the ts class? Shouldn't it get the datetime class instead? (Yes, I am aware of the problems of using datetime and timestamps) Could some kind soul please enlighten me? If the datetime class were implemented in Python the fromtimestamp() method could look like: @classmethod def fromtimestamp(cls, s): year, month, day,... = ... return cls(year, month, day,...) This will fail since you modified the constructor to accept only a single argument. Hm, I had hoped that using super() would result in calling the constructor of the superclass, ie. datetime. Did I use super() wrong? Thanks, peter. Sorry, I didn't pay the necessary attention. I've only used super() with normal methods, but as from datetime import * class TS(datetime): ... def __new__(cls, ts): ... return datetime.fromtimestamp(ts) ... TS(0) datetime.datetime(1970, 1, 1, 1, 0) works super() would be the most likely culprit. Peter -- http://mail.python.org/mailman/listinfo/python-list
end of print = lower productivity ?
I want my productivity back. In Python 2.x, I could easily write things like -- print f / print add / print done -- to a lot of different places in my code, which allowed me to find bugs that I could not track otherwise. When I found out that f was not at fault, I could write -- print g -- to some other place... etc, so that a significant part of the time spent debugging was actually used to write print statements. Now the print statement disappeared, and I have to write print(f) instead. These parentheses not only take time to write, they also make me think twice about using print for debugging purposes. Pressing SHIFT then ( thenmakes the whole process quite a hassle. I agree with most of the arguments that have been made against using the print statement to build code, but I did care about the efficient debugging tool it was. -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
Now the print statement disappeared, and I have to write print(f) instead. These parentheses not only take time to write, they also make me think twice about using print for debugging purposes. Pressing SHIFT then ( thenmakes the whole process quite a hassle. :rollseyes: I hope there was a missing smiley in that post. If a couple extra parens destroys your debugging productivity I suspect you need a fresh approach to the task. -- Skip Montanaro - [EMAIL PROTECTED] - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
[EMAIL PROTECTED] wrote: I want my productivity back. In Python 2.x, I could easily write things like -- print f / print add / print done -- to a lot of different places in my code, which allowed me to find bugs that I could not track otherwise. When I found out that f was not at fault, I could write -- print g -- to some other place... etc, so that a significant part of the time spent debugging was actually used to write print statements. Now the print statement disappeared, and I have to write print(f) instead. These parentheses not only take time to write, they also make me think twice about using print for debugging purposes. Pressing SHIFT then ( thenmakes the whole process quite a hassle. I agree with most of the arguments that have been made against using the print statement to build code, but I did care about the efficient debugging tool it was. I used to use print a lot. Once I found import pdb; pdb.set_trace() I massively lost interest in it. And gained *much* more debugging power/productivity. Also, using logging instead of print allows you to keep the output producing statements in your code, while turning them on only if things get fishy. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
On Nov 25, 4:39 pm, Peter Otten [EMAIL PROTECTED] wrote: peter wrote: On Nov 25, 3:46 pm, Peter Otten [EMAIL PROTECTED] wrote: peter wrote: import datetime class ts(datetime.datetime): ... foo = 'bar' ... def __new__(cls, s): ... c = super(ts, cls) ... return c.fromtimestamp(s) ... t = ts(0) Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __new__ TypeError: __new__() takes exactly 2 arguments (9 given) I don't understand why that happens -- am I correct in assuming that the call to .fromtimestamp() is picking up on the ts class? Shouldn't it get the datetime class instead? (Yes, I am aware of the problems of using datetime and timestamps) Could some kind soul please enlighten me? If the datetime class were implemented in Python the fromtimestamp() method could look like: @classmethod def fromtimestamp(cls, s): year, month, day,... = ... return cls(year, month, day,...) This will fail since you modified the constructor to accept only a single argument. Hm, I had hoped that using super() would result in calling the constructor of the superclass, ie. datetime. Did I use super() wrong? Thanks, peter. Sorry, I didn't pay the necessary attention. I've only used super() with normal methods, but as from datetime import * class TS(datetime): ... def __new__(cls, ts): ... return datetime.fromtimestamp(ts) ... TS(0) datetime.datetime(1970, 1, 1, 1, 0) works super() would be the most likely culprit. Yes, that works, except the returned object is (unsurprisingly) a pure datetime instance, which means I cannot access any other attributes I defined on my class. The docs on super() ( http://docs.python.org/library/functions.html#super ) are a little murky unfortunately. Cheers, peter. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: initialized list: strange behavior
Steve Holden [EMAIL PROTECTED] writes: Arnaud Delobelle wrote: Jason Scheirer [EMAIL PROTECTED] writes: Python is pass-by-reference, not pass-by-value. It's certainly not pass-by-reference, nor is it pass-by-value IMHO. Since no lists are being passed as arguments in these examples it's not pass-by-anything. Jump off that horse right now! You're right that Python's calling semantics have nothing to do with the question asked. I just thought best not to leave the OP under any misapprehension. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
On Nov 25, 4:44 pm, [EMAIL PROTECTED] wrote: I want my productivity back. In Python 2.x, I could easily write things like -- print f / print add / print done -- to a lot of different places in my code, which allowed me to find bugs that I could not track otherwise. When I found out that f was not at fault, I could write -- print g -- to some other place... etc, so that a significant part of the time spent debugging was actually used to write print statements. Now the print statement disappeared, and I have to write print(f) instead. These parentheses not only take time to write, they also make me think twice about using print for debugging purposes. Pressing SHIFT then ( thenmakes the whole process quite a hassle. I agree with most of the arguments that have been made against using the print statement to build code, but I did care about the efficient debugging tool it was. BUT you now can do p = print p(f) Voila, 4 keystrokes saved :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
On Nov 25, 4:53 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: I used to use print a lot. Once I found import pdb; pdb.set_trace() I massively lost interest in it. And gained *much* more debugging power/productivity. In some cases, this is not discriminatory enough : there are simply too many function calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a directory file descriptor?
Cong Ma a écrit : Dear all, Can you give me some hint on getting a directory file descriptor in Python? Besides, what's good about os.fchdir() if I can't get a directory fd in the first place? Thanks for your reply. Regards, Cong. -- http://mail.python.org/mailman/listinfo/python-list Hello, I believe you want os.open : Python 2.5.2 (r252:60911, Sep 29 2008, 21:10:35) [GCC 4.3.2] on linux2 Type help, copyright, credits or license for more information. import os d=os.open('mydir',os.O_RDONLY) d 3 os.fchdir(d) os.getcwd() '/home/baptiste/mydir' Cheers, Baptiste -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
peter wrote: from datetime import * class TS(datetime): ... def __new__(cls, ts): ... return datetime.fromtimestamp(ts) ... TS(0) datetime.datetime(1970, 1, 1, 1, 0) works super() would be the most likely culprit. Yes, that works, except the returned object is (unsurprisingly) a pure datetime instance, which means I cannot access any other attributes I defined on my class. How about import datetime class DT(datetime.datetime): def __new__(cls, *args): if len(args) == 1: return cls.fromtimestamp(args[0]) return datetime.datetime.__new__(cls, *args) then? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
On Nov 25, 5:05 pm, peter [EMAIL PROTECTED] wrote: BUT you now can do p = print p(f) Voila, 4 keystrokes saved :-) All right. Let's talk about that. When I write print, it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key, and then the ( : move the left hand, press SHIFT, move the right hand, aim (, press, miss, press again. Same thing at the end of the function call. I know it sounds ridiculous, but it does *impair* my debugging productivity. Taylor would agree. -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
[EMAIL PROTECTED] schrieb: I know it sounds ridiculous Not only that - it also sounds as if there's spring break in Trollland. Regards, Johannes -- Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verlästerung von Gott, Bibel und mir und bewusster Blasphemie. -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
On Nov 25, 4:34 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: You can't use ctypes for C++, only for C-style APIs. Diez With some work, you can convert your C++ objects to PyObject* and then return the latter in a function with C bindings. -- http://mail.python.org/mailman/listinfo/python-list
Reg Expression - Get position of
Hey, I need the position of the last char Let's say I have a string mystr = mimetype=text/htmlcontent![CDATA[ I need the posistion of the (second sign) - so I can cut away the first part. The problem is that it can be like but also like or But it is def the quotes and the closing brakets. How do I get the position of the Hope you can help, Bacco -- http://mail.python.org/mailman/listinfo/python-list
confused about classes and tkinter object design
Hi, I've created my first Tkinter GUI class which consists of some buttons that trigger functions. I have also created a tkFileDialog.askdirectory control to local a root folder for log files. I have several file paths that depend on the value of tkFileDialog.askdirectory should I create an object that inherits this value or can I point functions at the GUI class? I am creating the tkinter GUI instance using; if __name__ == __main__: GUI = AuditorGUI() GUI.mainloop() class AuditorGUI(Frame): def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) ## Create GUI objects self.currentdir = StringVar() self.currentdir.set(os.getcwd()) self.logdir = Button(self, text=Choose Data directory,command=self.choose_dir) self.logdir.grid(row=1,column=0,sticky='nsew',pady=20,padx=20) self.labeldirpath = Label(self, textvariable=self.currentdir) def choose_dir(self): dirname = tkFileDialog.askdirectory (parent=self,initialdir=self.currentdir.get(),title='Please select a directory') if len(dirname ) 0: self.currentdir.set(dirname) I think I have created an instance of the AuditorGUI class called GUI so should be able to access the path using GUI.currentdir but this doesn't work. I'm still struggling with classes so not sure whether my problem is tkinter related or not. Thanks, MW -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
p = print p(f) Voila, 4 keystrokes saved :-) When I write print, it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key, and then the ( : move the left hand, press SHIFT, move the right hand, aim (, press, miss, press again. Same thing at the end of the function call. I know it sounds ridiculous, but it does *impair* my debugging productivity. Taylor would agree. It's not so much rediculous as a failure of your editor to assist you. In Vim (my editor-of-choice), I'd do something like :iab print print()leftbs and that's the end of it. Or you could be even lazier if you don't name your variables p: :iab p print()left in which case you can just type p and it automatically populates with print() with the cursor after the double-quote ready for you to type the string's contents. Net gain: 5 characters in old-Python and 6 characters in new-Python ;-) Any editor environment worth its salt should allow you to do things like this (insert abreviated text or template text). The gains made from making print a function far outweigh niggling things that simple editor-tweaks can overcome. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Instance attributes vs method arguments
M.-A. Lemburg a écrit : (snip) It is always good practice to provide default values for instance variables in the class definition, both to enhance readability and to allow adding documentation regarding the variables, e.g. Your opinion. As far as I'm concerned, using class variables this way is more of a WTF than a good practice. class Class_a: # Foo bar a = None # Foo baz b = None ... -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime objects and __new__()
On Nov 25, 5:16 pm, Peter Otten [EMAIL PROTECTED] wrote: peter wrote: from datetime import * class TS(datetime): ... def __new__(cls, ts): ... return datetime.fromtimestamp(ts) ... TS(0) datetime.datetime(1970, 1, 1, 1, 0) works super() would be the most likely culprit. Yes, that works, except the returned object is (unsurprisingly) a pure datetime instance, which means I cannot access any other attributes I defined on my class. How about import datetime class DT(datetime.datetime): def __new__(cls, *args): if len(args) == 1: return cls.fromtimestamp(args[0]) return datetime.datetime.__new__(cls, *args) then? A bit hacky, but does the trick quite nicely otherwise -- thanks :-) Still, I wonder whats up with super(). Obviously I must be missing something here. peter. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
2008/11/25 [EMAIL PROTECTED]: On Nov 25, 4:34 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: You can't use ctypes for C++, only for C-style APIs. Diez With some work, you can convert your C++ objects to PyObject* and then return the latter in a function with C bindings. http://cython.org also has some support for C++ bindings. I also heard that Boost.Python is very well suited to make full featured C++ / python bindings though I never tried myself. -- Olivier -- http://mail.python.org/mailman/listinfo/python-list
encoding
hello i'm writing an irc client, i use for encoding the utf-8 but i never see all the typed sign in the correct way, anyone know the standard encodind for the irc channels? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list
Enumerating k-segmentations of a sequence
I'm not sure if my terminology is precise enough, but what I want to do is: Given an ordered sequence of n items, enumerate all its possible k- segmentations. This is *not* the same as enumerating the k set partitions of the n items because I am only interested in those set partitions which preserve the order of the items. i.e. if the input sequence is (1 2 3 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4 5)) is acceptable. Hence use of term 'segmentations'. e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function which enumerates the following 3-segmentations: ((1 2 3) (4) (5)) ((1 2) (3 4) (5)) ((1 2) (3) (4 5)) ((1) (2 3 4) (5)) ((1) (2 3) (4 5)) ((1) (2) (3 4 5)) The reason I want to do this is to use it in some simple one- dimensional clustering, i.e. each set item (won't be just integers as above) will have a value of interest, and i'll select the particular set partition which minimises Sigma SSD (sum of squared differences from mean) of these values. It seems overkill to generate the full list of set partitions [including e.g. ((1 4) (2) (3 5))] because I intend to begin by sorting the input sequence such that element 1 element 2 ... element n. Structural Recursion not being my strong point, any ideas on how to go about this would be much appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding
On Tue, Nov 25, 2008 at 11:53 AM, luca72 [EMAIL PROTECTED] wrote: hello i'm writing an irc client, i use for encoding the utf-8 but i never see all the typed sign in the correct way, anyone know the standard encodind for the irc channels? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list This is something where Google is very helpful. I haven't dealt with this before, but a look at the definition of the protocol says there isn't any standard encoding. As a matter of fact, the RFC specifically says there is no standard character set[1]. The only thing it specifies is that IRC uses an 8-bit protocol. Since UTF-8 that doesn't work, I'd try using ISO-8859 and CP1252 and see if those work better. [1] http://www.faqs.org/rfcs/rfc1459.html (section 2.2) -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
bullockbefriending bard napisał(a): I'm not sure if my terminology is precise enough, but what I want to do is: Given an ordered sequence of n items, enumerate all its possible k- segmentations. This is *not* the same as enumerating the k set partitions of the n items because I am only interested in those set partitions which preserve the order of the items. i.e. if the input sequence is (1 2 3 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4 5)) is acceptable. Hence use of term 'segmentations'. e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function which enumerates the following 3-segmentations: ((1 2 3) (4) (5)) ((1 2) (3 4) (5)) ((1 2) (3) (4 5)) ((1) (2 3 4) (5)) ((1) (2 3) (4 5)) ((1) (2) (3 4 5)) The reason I want to do this is to use it in some simple one- dimensional clustering, i.e. each set item (won't be just integers as above) will have a value of interest, and i'll select the particular set partition which minimises Sigma SSD (sum of squared differences from mean) of these values. It seems overkill to generate the full list of set partitions [including e.g. ((1 4) (2) (3 5))] because I intend to begin by sorting the input sequence such that element 1 element 2 ... element n. Structural Recursion not being my strong point, any ideas on how to go about this would be much appreciated! I'm not sure if I correctly understood the semantics of what you need. Anyway it looks like a nice exercise in nested generators: def segmentations(sequence, k): assert 1 = k = len(sequence) if k == 1: yield [sequence] else: for headlen in xrange(1, len(sequence) - k + 2): head, tail = sequence[:headlen], sequence[headlen:] for tail_seg in segmentations(tail, k - 1): yield [head] + tail_seg for segmentation in segmentations((1, 2, 3, 4, 5), 3): print segmentation Regards, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
On Nov 25, 10:52 am, [EMAIL PROTECTED] wrote: Now the print statement disappeared, and I have to write print(f) instead. These parentheses not only take time to write, they also make me think twice about using print for debugging purposes. Pressing SHIFT then ( thenmakes the whole process quite a hassle. :rollseyes: I hope there was a missing smiley in that post. If a couple extra parens destroys your debugging productivity I suspect you need a fresh approach to the task. Seconded; I thought he's either joking or trolling. George -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
[EMAIL PROTECTED] wrote: On Nov 25, 4:53 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: I used to use print a lot. Once I found import pdb; pdb.set_trace() I massively lost interest in it. And gained *much* more debugging power/productivity. In some cases, this is not discriminatory enough : there are simply too many function calls. But not to many prints with to few parentheses? You must be joking. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding
2008/11/25 Benjamin Kaplan [EMAIL PROTECTED]: On Tue, Nov 25, 2008 at 11:53 AM, luca72 [EMAIL PROTECTED] wrote: hello i'm writing an irc client, i use for encoding the utf-8 but i never see all the typed sign in the correct way, anyone know the standard encodind for the irc channels? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list This is something where Google is very helpful. I haven't dealt with this before, but a look at the definition of the protocol says there isn't any standard encoding. As a matter of fact, the RFC specifically says there is no standard character set[1]. The only thing it specifies is that IRC uses an 8-bit protocol. Since UTF-8 that doesn't work, I'd try using ISO-8859 and CP1252 and see if those work better. [1] http://www.faqs.org/rfcs/rfc1459.html (section 2.2) In any case I would suggest that you use UTF-8 anyway. You will save your users a lot of headaches. While I am a big standards nut, this is the use case where you should divert. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-ي А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я ä-ö-ü-ß-Ä-Ö-Ü -- http://mail.python.org/mailman/listinfo/python-list
Re: Using dictionary to hold regex patterns?
John Machin schrieb: No, complicated is more related to unused features. In the case of using an aeroplane to transport 3 passengers 10 km along the autobahn, you aren't using the radar, wheel-retractability, wings, pressurised cabin, etc. In your original notion of using a dict in your lexer, you weren't using the mapping functionality of a dict at all. In both cases you have perplexed bystanders asking Why use a plane/dict when a car/list will do the job?. Now the matter is getting clearer in my head. Thanks and greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison! (Coluche) -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
On Nov 25, 4:56 pm, bullockbefriending bard [EMAIL PROTECTED] wrote: I'm not sure if my terminology is precise enough, but what I want to do is: [snip problem description] Structural Recursion not being my strong point, any ideas on how to go about this would be much appreciated! If you have Python 2.6 available, itertools.combination might be useful. Here's an example: from itertools import combinations def partitions(l, k): generate all partitions of a list l into k nonempty pieces n = len(l) for c in combinations(range(1, n), k-1): c = [0] + list(c) + [n] yield [l[c[i]:c[i+1]] for i in xrange(k)] for p in partitions(range(1, 6), 3): print p Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
On Nov 25, 5:34 pm, Mark Dickinson [EMAIL PROTECTED] wrote: If you have Python 2.6 available, itertools.combination might be That should be itertools.combinations, of course. The idea is that to give a partition of e.g., a 5-element list into 3 nonempty pieces, all you have to do is say where to break the list. There are 4 possible places to break (between the 1st and 2nd elements, 2nd and 3rd, etc.), and you've got to make two breaks. Then combinations(range(1, 5), 2) generates all possible pairs of breaking points. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
My version: from itertools import combinations as xcombinations from itertools import izip, islice def xpairwise(iterable): # docs and doctests removed return izip(iterable, islice(iterable, 1, None)) def segmentations(seq, k): for comb in xcombinations(range(1, len(seq)), k-1): yield [seq[start:stop] for start,stop in xpairwise((None,) + comb + (None,))] for seg in segmentations(range(1, 6), 3): print seg print for seg in segmentations(range(1, 7), 2): print seg print for seg in segmentations(range(1, 7), 3): print seg print for seg in segmentations(range(1, 7), 4): print seg print Other people have already explained how this works. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
Tim Chase [EMAIL PROTECTED] writes: p = print p(f) Voila, 4 keystrokes saved :-) When I write print, it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key, and then the ( : move the left hand, press SHIFT, move the right hand, aim (, press, miss, press again. Same thing at the end of the function call. I know it sounds ridiculous, but it does *impair* my debugging productivity. Taylor would agree. It's not so much rediculous as a failure of your editor to assist you. In Vim (my editor-of-choice), I'd do something like :iab print print()leftbs Or if you had chosen Emacs for editing, you could add the following to your .emacs. (fset 'py3kprint [?p ?r ?i ?n ?t ?( ?) left]) (add-hook 'python-mode-hook '(lambda () (define-key python-mode-map \C-cp 'py3kprint))) When in Python mode, it would bind C-c p to the same. (Warning - I am not an emacs lisp pro!) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
Rafe wrote: On Nov 25, 5:41 pm, Aaron Brady [EMAIL PROTECTED] wrote: On Nov 25, 4:08 am, Rafe [EMAIL PROTECTED] wrote: Hi, In the name of self-education can anyone share some pointers, links, modules, etc that I might use to begin learning how to do some metaprogramming. That is, using code to write code (right?) Cheers, - Rafe Python programs can generate code for themselves. for i in range( 10 ): ... d= { 'cls': i } ... s= ... class Cls%(cls)s: ... def meth%(cls)s( self, arg ): ... print 'in meth%(cls)s, arg:', arg ... % d ... exec( s ) ... s= ... inst%(cls)s= Cls%(cls)s() ... % d ... exec( s ) ... inst0.meth0( arg ) in meth0, arg: arg inst1.meth1( arg ) in meth1, arg: arg inst2.meth2( arg ) in meth2, arg: arg The 'Cls0', 'Cls1', 'Cls2' repetitiveness is taken care of with a for- loop. Michele, I am thinking about python which writes python. Which makes Aaron's post accurate to my needs. More specifically, I am considering what it might be like to use python to build a script file which can be executed later. Until now I planned to store info to XML and then parse it to run later. There are good reasons that generating a script file would be more useful for me. I use Python's own triple quoted string as a generator for the GUI, like this: GUI = self.NB ,wx.Notebook ,style = wx.NO_BORDER self.Grid ,Base_Table_Grid ,None, data_values, data_types, data_defs Panel2 ,PanelVer, 11,name = Page2 list1 ,wx.ListCtrl ,style = wx.LC_REPORT cheers, Stef Aaron, Is it really as simple as gathering strings of code? Sort of like generating HTML or XML directly? Is there any other framework or pattern set that is worth looking in to? Thanks for helping me explore this. - Rafe -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
Boost.Python is difficult to understand, far more than SWIG. It may be faster, but I don't think it is worth it ATM. Binding C++ classes with SWIG is really simple. Matthieu 2008/11/25 Olivier Grisel [EMAIL PROTECTED]: 2008/11/25 [EMAIL PROTECTED]: On Nov 25, 4:34 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: You can't use ctypes for C++, only for C-style APIs. Diez With some work, you can convert your C++ objects to PyObject* and then return the latter in a function with C bindings. http://cython.org also has some support for C++ bindings. I also heard that Boost.Python is very well suited to make full featured C++ / python bindings though I never tried myself. -- Olivier -- http://mail.python.org/mailman/listinfo/python-list -- Information System Engineer, Ph.D. Website: http://matthieu-brucher.developpez.com/ Blogs: http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn: http://www.linkedin.com/in/matthieubrucher -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
bullockbefriending bard [EMAIL PROTECTED] writes: I'm not sure if my terminology is precise enough, but what I want to do is: Given an ordered sequence of n items, enumerate all its possible k- segmentations. This is *not* the same as enumerating the k set partitions of the n items because I am only interested in those set partitions which preserve the order of the items. i.e. if the input sequence is (1 2 3 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4 5)) is acceptable. Hence use of term 'segmentations'. e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function which enumerates the following 3-segmentations: ((1 2 3) (4) (5)) ((1 2) (3 4) (5)) ((1 2) (3) (4 5)) ((1) (2 3 4) (5)) ((1) (2 3) (4 5)) ((1) (2) (3 4 5)) All you need to do is find the 'cutting places'. Here you are cutting at 2 places, the first cut has to be in position 0 and the last in position 5. That makes 4 potential cutting places: 1, 2, 3, 4. So you will have 4C2 = 6 2-segmentations of {1, 2, 3, 4, 5} which are given by the subsets of {1, 2, 3, 4} of size 2, i.e the 2-combinations of {1, 2, 3, 4}. Generalising this, if you want to find the k-segmentations of a sequence of length n, you will have (n-1)C(k-1) of them and their cutting places will be given by (k-1)-combinations of {1, 2, ..., n-1}. Generating the k-combinations is a standard problem so we're done! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating k-segmentations of a sequence
bullockbefriending bard wrote: I'm not sure if my terminology is precise enough, but what I want to do is: Given an ordered sequence of n items, enumerate all its possible k- segmentations. This is *not* the same as enumerating the k set partitions of the n items because I am only interested in those set partitions which preserve the order of the items. i.e. if the input sequence is (1 2 3 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4 5)) is acceptable. Hence use of term 'segmentations'. e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function which enumerates the following 3-segmentations: ((1 2 3) (4) (5)) ((1 2) (3 4) (5)) ((1 2) (3) (4 5)) ((1) (2 3 4) (5)) ((1) (2 3) (4 5)) ((1) (2) (3 4 5)) What Arnaud said. def nchoosek( n, k ): ''' Generate all subsets of S(n) that have k items. S(n) = {1, 2, 3, ..., n} list(nksubsets(3, 2)) [[1, 2], [1, 3], [2, 3]] ''' m = n - k + 1 indexer = range(0, k) seq = range(1, k+1) last = range(m, n+1) yield seq[:] while seq != last: high_value = -1 high_index = -1 for i in indexer: val = seq[i] if val high_value and val m + i: high_value = val high_index = i for j in range(k - high_index): seq[j+high_index] = high_value + j + 1 yield seq[:] #(minimally tested) def part(n,k): rng = range(1, n+1) for comb in nchoosek(n-1,k-1): comb = [0] + comb + [n] yield [rng[s:t] for (s,t) in (comb[i:i+2] for i in range(k))] for item in part(5, 2): print item for item in part(5, 3): print item G. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg Expression - Get position of
On Tue, Nov 25, 2008 at 8:36 AM, M_H [EMAIL PROTECTED] wrote: Hey, I need the position of the last char Let's say I have a string mystr = mimetype=text/htmlcontent![CDATA[ I need the posistion of the (second sign) - so I can cut away the first part. The problem is that it can be like but also like or But it is def the quotes and the closing brakets. How do I get the position of the Python 2.6 (r26:66714, Nov 18 2008, 21:48:52) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type help, copyright, credits or license for more information. mystr = 'mimetype=text/htmlcontent![CDATA[' mystr.rfind('') 30 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com Hope you can help, Bacco -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
pyExcelerator: setting zoom of a worksheet
Hi everybody, I use pyExcelerator and am quite happy with it, except: I cannot find a option for setting the zoom of a particular worksheet. I am using pyExcelerator 0.6.3a which is the latest as far as i know. I already contacted the developer of pyExcelerator, he says there is a zoom-option in Worksheet.py, but it seems not to be there in my version. Anyone ever worked with it and maybe can help me? Thanks a lot. KR, Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Module Structure/Import Design Problem
Rafe a écrit : On Nov 20, 2:06 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: (snip) Or (better IMHO) you can make types register themselves with the factory function (in which case it would have some state so it would make more sense to make it a factory object). Can you elaborate on what you mean by 'register' with the factory function? I think Arnaud means something like: # baselib.py class Base(object): _registry = {} @classmethod def register(cls, subclass): cls._registry[subclass.__name__] = subclass @classmethod def get_class(cls, classname): return cls._registry[classname] # typelib.py from baselib import Base class Sub(Base): pass Base.register(Sub) Also...holy [EMAIL PROTECTED], I got a clean import working! I swear I tried that before with unhappy results. I'll carefully try this in my real code. Is this the right way to impliment the imports? baselib.py [1] class BaseClass(object): [2] def factory(self): [3] import typelib # -- import inside function [4] return typelib.TypeA() This is one possible way to solve circular imports, but it has some drawbacks - mostly, the performance hit of the import statement on each call to BaseClass.factory typelib.py [1] import baselib # -- module level import [2] [3] class TypeA(baselib.BaseClass): [4] def __init__(self): [5] print TypeA : __init__() import typelib type = typelib.TypeA() ot This shadows the builtin type 'type'. Better to use another name here... /ot TypeA : __init__() another_type = type.factory() TypeA : __init__() another_type typelib.TypeA object at 0x00B45F10 I am curious (not directed at Arnaud), why not have an 'include'-like import for special cases in python (or do I not understand includes either?) In C, #include somefile.h is a pre-processor statement that does a textual inclusion before compilation. Python just doesn't work that way. -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
[EMAIL PROTECTED] schrieb: On Nov 25, 4:34 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: You can't use ctypes for C++, only for C-style APIs. Diez With some work, you can convert your C++ objects to PyObject* and then return the latter in a function with C bindings. Or you use SWIG or SIP or Python::Boost to do that for you with less work. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
[EMAIL PROTECTED] schrieb: On Nov 25, 5:05 pm, peter [EMAIL PROTECTED] wrote: BUT you now can do p = print p(f) Voila, 4 keystrokes saved :-) All right. Let's talk about that. When I write print, it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key, and then the ( : move the left hand, press SHIFT, move the right hand, aim (, press, miss, press again. Same thing at the end of the function call. I know it sounds ridiculous, but it does *impair* my debugging productivity. Taylor would agree. If the relative difference between pressing space ( impairs your absolute debugging productivity, it pretty much follows that the latter must be very low for such a minimal overhead to make such a difference. Try learning touchtype. Might increase your debugging, programming writing productivity manyfold. Diez -- http://mail.python.org/mailman/listinfo/python-list
Anyone heard of a good Voice Stress Analysis program
Anyone heard of a good voice stress analysis program that was either: a) Written in python b) can be used by python? It would be a great help to me. Thanks, Dan Folkes http://danfolkes.com -- http://mail.python.org/mailman/listinfo/python-list
Re: confused about classes and tkinter object design
On Nov 25, 10:38 am, marc wyburn [EMAIL PROTECTED] wrote: Hi, I've created my first Tkinter GUI class which consists of some buttons that trigger functions. I have also created a tkFileDialog.askdirectory control to local a root folder for log files. I have several file paths that depend on the value of tkFileDialog.askdirectory should I create an object that inherits this value or can I point functions at the GUI class? I am creating the tkinter GUI instance using; if __name__ == __main__: GUI = AuditorGUI() GUI.mainloop() class AuditorGUI(Frame): def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) ## Create GUI objects self.currentdir = StringVar() self.currentdir.set(os.getcwd()) self.logdir = Button(self, text=Choose Data directory,command=self.choose_dir) self.logdir.grid(row=1,column=0,sticky='nsew',pady=20,padx=20) self.labeldirpath = Label(self, textvariable=self.currentdir) def choose_dir(self): dirname = tkFileDialog.askdirectory (parent=self,initialdir=self.currentdir.get(),title='Please select a directory') if len(dirname ) 0: self.currentdir.set(dirname) I think I have created an instance of the AuditorGUI class called GUI so should be able to access the path using GUI.currentdir but this doesn't work. I'm still struggling with classes so not sure whether my problem is tkinter related or not. Thanks, MW -- http://mail.python.org/mailman/listinfo/python-list
Re: zope vs openACS
Stefan Scholl a écrit : [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Nov 19, 1:50 am, gavino [EMAIL PROTECTED] wrote: what is nicer about each? Yes. And No. Or maybe ? -- http://mail.python.org/mailman/listinfo/python-list
Re: confused about classes and tkinter object design
On Nov 25, 10:38 am, marc wyburn [EMAIL PROTECTED] wrote: Hi, I've created my first Tkinter GUI class which consists of some buttons that trigger functions. I have also created a tkFileDialog.askdirectory control to local a root folder for log files. I have several file paths that depend on the value of tkFileDialog.askdirectory should I create an object that inherits this value or can I point functions at the GUI class? I am creating the tkinter GUI instance using; if __name__ == __main__: GUI = AuditorGUI() GUI.mainloop() class AuditorGUI(Frame): def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) ## Create GUI objects self.currentdir = StringVar() self.currentdir.set(os.getcwd()) self.logdir = Button(self, text=Choose Data directory,command=self.choose_dir) self.logdir.grid(row=1,column=0,sticky='nsew',pady=20,padx=20) self.labeldirpath = Label(self, textvariable=self.currentdir) def choose_dir(self): dirname = tkFileDialog.askdirectory (parent=self,initialdir=self.currentdir.get(),title='Please select a directory') if len(dirname ) 0: self.currentdir.set(dirname) I think I have created an instance of the AuditorGUI class called GUI so should be able to access the path using GUI.currentdir but this doesn't work. I'm still struggling with classes so not sure whether my problem is tkinter related or not. Thanks, MW first off i would use a different instance variable besides GUI. Could be AG or auditorgui. Also the conditional if len(dirname ) 0: could simply be if dirname: When you ask for the attribute currentdir are you asking as GUI.currentdir.get() or GUI.currentdir??? only the second will work with a TKVAR, but there is really no need to use a TKVAR here. I would simply do: self.currentdir = None then you could say: if GUI.currentdir: do this() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get the class instance of a passed method ?
Arnaud Delobelle a écrit : (snip) .im_self will become example.method.__self__ and in python 3. But I can't see the equivalen of .im_class? At worst, you'll still have example.method.__self__.__class__ !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg Expression - Get position of
On Nov 25, 10:36 am, M_H [EMAIL PROTECTED] wrote: Hey, I need the position of the last char Let's say I have a string mystr = mimetype=text/htmlcontent![CDATA[ I need the posistion of the (second sign) - so I can cut away the first part. The problem is that it can be like but also like or But it is def the quotes and the closing brakets. How do I get the position of the Hope you can help, Bacco why not just spilt mystr = 'mimetype=text/htmlcontent![CDATA[' mystr.split('', 2)[-1] '![CDATA[' you don't want to use an re for something like this -- http://mail.python.org/mailman/listinfo/python-list
Re: Module Structure/Import Design Problem
Bruno Desthuilliers [EMAIL PROTECTED] writes: Rafe a écrit : On Nov 20, 2:06 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: (snip) Or (better IMHO) you can make types register themselves with the factory function (in which case it would have some state so it would make more sense to make it a factory object). Can you elaborate on what you mean by 'register' with the factory function? I think Arnaud means something like: # baselib.py class Base(object): _registry = {} @classmethod def register(cls, subclass): cls._registry[subclass.__name__] = subclass @classmethod def get_class(cls, classname): return cls._registry[classname] # typelib.py from baselib import Base class Sub(Base): pass Base.register(Sub) That's what I meant. Sorry Rafe I missed your follow-up. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with writing fast UDP server
On Nov 21, 6:55 pm, Greg Copeland [EMAIL PROTECTED] wrote: On Nov 21, 11:05 am, Krzysztof Retel [EMAIL PROTECTED] wrote: On Nov 21, 4:48 pm, Peter Pearson [EMAIL PROTECTED] wrote: On Fri, 21 Nov 2008 08:14:19 -0800 (PST), Krzysztof Retel wrote: I am not sure what do you mean by CPU-bound? How can I find out if I run it on CPU-bound? CPU-bound is the state in which performance is limited by the availability of processor cycles. On a Unix box, you might run the top utility and look to see whether the %CPU figure indicates 100% CPU use. Alternatively, you might have a tool for plotting use of system resources. -- To email me, substitute nowhere-spamcop, invalid-net. Thanks. I run it without CPU-bound With clearer eyes, I did confirm my math above is correct. I don't have a networking reference to provide. You'll likely have some good results via Google. :) If you are not CPU bound, you are likely IO-bound. That means you computer is waiting for IO to complete - likely on the sending side. In this case, it likely means you have reached your ethernet bandwidth limits available to your computer. Since you didn't correct me when I assumed you're running 10Mb ethernet, I'll continue to assume that's a safe assumption. So, assuming you are running on 10Mb ethernet, try converting your application to use TCP. I'd bet, unless you have requirements which prevent its use, you'll suddenly have enough bandwidth (in this case, frames) to achieve your desired results. This is untested and off the top of my head but it should get you pointed in the right direction pretty quickly. Make the following changes to the server: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) to sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Make this: print Waiting for first packet to arrive..., sock.recvfrom(BUFSIZE) look like: print Waiting for first packet to arrive..., cliSock = sock.accept() Change your calls to sock.recvfrom(BUFSIZE) to cliSock.recv(BUFSIZE). Notice the change to cliSock. Keep in mind TCP is stream based, not datagram based so you may need to add additional logic to determine data boundaries for re-assemble of your data on the receiving end. There are several strategies to address that, but for now I'll gloss it over. As someone else pointed out above, change your calls to time.clock() to time.time(). On your client, make the following changes. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) to sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect( (remotehost,port) ) nbytes = sock.sendto(data, (remotehost,port)) to nbytes = sock.send(data) Now, rerun your tests on your network. I expect you'll be faster now because TCP can be pretty smart about buffering. Let's say you write 16, 90B blocks to the socket. If they are timely enough, it is possible all of those will be shipped across ethernet as a single frame. So what took 16 frames via UDP can now *potentially* be done in a single ethernet frame (assuming 1500MTU). I say potentially because the exact behaviour is OS/stack and NIC-driver specific and is often tunable to boot. Likewise, on the client end, what previously required 15 calls to recvfrom, each returning 90B, can *potentially* be completed in a single call to recv, returning 1440B. Remember, fewer frames means less protocol overhead which makes more bandwidth available to your applications. When sending 90B datagrams, you're waisting over 48% of your available bandwidth because of protocol overhead (actually a lot more because I'm not accounting for UDP headers). Because of the differences between UDP and TCP, unlike your original UDP implementation which can receive from multiple clients, the TCP implementation can only receive from a single client. If you need to receive from multiple clients concurrently, look at python's select module to take up the slack. Hopefully you'll be up and running. Please report back your findings. I'm curious as to your results. I've been out of online for a while. Anyway, clarifing few things: - I am running on IO-bound - we have 10/100/1000MB ethernet, and 10/100MB switches, routers, servers, - the MTU is default 1500 I know what you are saying regarding TCP. I was using it in another project. However this project needs to be done using UDP and can't be changed :( Was testing today multiple approaches to client. Kept one similar to the above one, rewrote one using threads and found another issue. The speed is pretty acceptable, but there is an issue with sending 1.000.000 packets per client (it does it within around 1.5min). It runs from a client machine to the server machine, both on the same network. So, when sending milion packets only around 50%-70% are send over. On the client machine it looks like all the packets where transmitted however tcpdump running on the server shows that only 50-70% went through. I
Re: Getting in to metaprogramming
On Nov 25, 5:20 am, Michele Simionato [EMAIL PROTECTED] wrote: On Nov 25, 12:12 pm, Rafe [EMAIL PROTECTED] wrote: is it really as simple as gathering strings of code? Yes. Yes. Sort of like generating HTML or XML directly? Is there any other framework or pattern set that is worth looking in to? Yes, the compiler module and the ast module in the standard library. You may also look at how templating languages that compile to Python code work (I mean mako or PTL/qpy). You may find interesting how the import hooks work too. You could have Python generate HTML, Python generate COBOL, Python generate Python, Perl generate Python, sure. Not that I know COBOL. If you're generating Python with Python, you only need one file to do it, not two separate programs, as you would for the other combinations; it was my point. It could be really helpful or unnecessary, depending on your application. There are some templating modules, possibly for Python code. If anyone knows them, they can point them out. I don't know a clean, reliable way to structure a metaprogram though. Mine always turn out messy. -- http://mail.python.org/mailman/listinfo/python-list
converting a string data to a float value for access database
Hi, I am trying to copy a sql database to a access database using python. I can copy all the fields, but the date. I can store a float value in access data object, ie http://en.wikibooks.org/wiki/JET_Database/Data_types#Dates_and_times So access uses a float for a date, and mysql databse uses text, I got the following as the output 2008-11-25 09:59:39. How can I convert the string 2008-11-25 09:59:39 from mysql to a float for access?? -Ted -- http://mail.python.org/mailman/listinfo/python-list
Re: confused about classes and tkinter object design
On Nov 25, 2:31 pm, r [EMAIL PROTECTED] wrote: On Nov 25, 10:38 am, marc wyburn [EMAIL PROTECTED] wrote: Hi, I've created my first Tkinter GUI class which consists of some buttons that trigger functions. I have also created a tkFileDialog.askdirectory control to local a root folder for log files. I have several file paths that depend on the value of tkFileDialog.askdirectory should I create an object that inherits this value or can I point functions at the GUI class? I am creating the tkinter GUI instance using; if __name__ == __main__: GUI = AuditorGUI() GUI.mainloop() class AuditorGUI(Frame): def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) ## Create GUI objects self.currentdir = StringVar() self.currentdir.set(os.getcwd()) self.logdir = Button(self, text=Choose Data directory,command=self.choose_dir) self.logdir.grid(row=1,column=0,sticky='nsew',pady=20,padx=20) self.labeldirpath = Label(self, textvariable=self.currentdir) def choose_dir(self): dirname = tkFileDialog.askdirectory (parent=self,initialdir=self.currentdir.get(),title='Please select a directory') if len(dirname ) 0: self.currentdir.set(dirname) I think I have created an instance of the AuditorGUI class called GUI so should be able to access the path using GUI.currentdir but this doesn't work. I'm still struggling with classes so not sure whether my problem is tkinter related or not. Thanks, MW first off i would use a different instance variable besides GUI. Could be AG or auditorgui. Also the conditional if len(dirname ) 0: could simply be if dirname: When you ask for the attribute currentdir are you asking as GUI.currentdir.get() or GUI.currentdir??? only the second will work with a TKVAR, but there is really no need to use a TKVAR here. I would simply do: self.currentdir = None then you could say: if GUI.currentdir: do this() When you ask for the attribute currentdir are you asking as GUI.currentdir.get() or GUI.currentdir??? only the second will work with a TKVAR correction: only GUI.currentdir.get() will work with TKVAR my bad:( -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG vs. ctypes (Was: ANN: PyEnchant 1.5.0)
I'd be interested to hear about your experiences with both and why you switched. Enchant has a pretty simple C API so the binding process was straightforward with both SWIG and ctypes. The only real trick was in passing python functions as callbacks to the C API, for which I found ctypes a little easier to use. The switch wasn't motivated by any problems with SWIG, but simply because ctypes seems to have a lot of momentum on the alternate python implementations such as PyPy, Jython etc. As others have noted, ctypes unfortunately doesn't support C++ bindings. There was a recent post on the PyPy blog discussing options for C++ that you might be interested in: http://morepypy.blogspot.com/2008/10/sprint-discussions-c-library-bindings.html Cheers, Ryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Security implications of using open() on untrusted strings.
On Tue, 25 Nov 2008 20:40:57 +1300, Lawrence D'Oliveiro [EMAIL PROTECTED] wrote: Jorgen Grahn wrote: Seems to me you simply want to know beforehand that the reading will work. But you can never check that! You can stat(2) the file, or open-and-close it -- and then a microsecond later, someone deletes the file, or replaces it with another one, or write-protects it, or mounts a file system on top of its directory, or drops a nuke over the city, or ... Depends on what exactly you're trying to guard against. Your comments would apply, for example, to a set-uid program being run by a potentially hostile local user Yeah, I know. I covered that in the part you snipped: Nor seems the 'user' input come from some other user than the one your program is running as, nor from some input source which the user cannot be held responsible for. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: end of print = lower productivity ?
[EMAIL PROTECTED] writes: BUT you now can do p = print p(f) All right. Let's talk about that. When I write print, it is both effortless and instantaneous : my hands do not move, a wave goes through my fingers, it all happens in a tenth of a second. Contrast this with what one has to go through to catch the SHIFT key ... You could say: class Printer: def __isub__(self, x): print(x) p = Printer() Then p-= foo doesn't need use of the shift key. Use of -= instead of - gets rid of operator precedence issues. -- http://mail.python.org/mailman/listinfo/python-list
Re: converting a string data to a float value for access database
On 2008-11-25 22:37, [EMAIL PROTECTED] wrote: Hi, I am trying to copy a sql database to a access database using python. I can copy all the fields, but the date. I can store a float value in access data object, ie http://en.wikibooks.org/wiki/JET_Database/Data_types#Dates_and_times So access uses a float for a date, and mysql databse uses text, I got the following as the output 2008-11-25 09:59:39. How can I convert the string 2008-11-25 09:59:39 from mysql to a float for access?? Use mxDateTime: from mx.DateTime import * DateTimeFrom('2008-11-25 09:59:39').COMDate() 39777.4164236 See http://www.egenix.com/products/python/mxBase/mxDateTime/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 25 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2008-11-12: Released mxODBC.Connect 0.9.3 http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: What are the syntax for , ||
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] How do I do in Python? if condition1 and condition2: # doThis elif condition3 or condition4: # || doThat See the pattern? if condition1 and condition2: doThis elif condition3 or condition4: doThat -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
Aaron Brady [EMAIL PROTECTED] writes: I don't know a clean, reliable way to structure a metaprogram though. Mine always turn out messy. I don't think Python is designed for large scale metaprogramming. Lisp is the only naturally suited language that I know. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Security implications of using open() on untrusted strings.
On Tue, 25 Nov 2008 02:26:32 -0500, r0g [EMAIL PROTECTED] wrote: Jorgen Grahn wrote: ... Or am I missing something? No Jorgen, that's exactly what I needed to know i.e. that sending unfiltered text to open() is not negligent or likely to allow any badness to occur. As far as what I was looking for: I was not looking for anything in particular as I couldn't think of any specific cases where this could be a problem however... my background is websites (where input sanitization is rule number one) and some of the web exploits I've learned to mitigate over the years aren't ones I would have necessarily figured out for myself i.e. CSRF I have no idea what CSRF is, but I know what you mean. And it applies in the safe and cozy Unix account world too -- that the exploits are surprising, I mean. Maybe I made it out to be *too* safe in my previous posting. But still ... So I thought I'd ask you guys in case there's anything I haven't considered that I should consider! Thankfully it seems I don't have too much to worry about :-) ... no, in this case you're just doing what everybody else does, and you have no alternative plan (filter for what?) There ought to be some list common attacks on applications run by local Unix users which one could learn from. Maybe it's not obvious that the content of a local file should, in many situations, be handled as untrusted. In the meantime, there's things like this: http://www.debian.org/security/2008/ Many of them are local exploits. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: pyExcelerator: setting zoom of a worksheet
On Nov 26, 6:40 am, Frank [EMAIL PROTECTED] wrote: Hi everybody, I use pyExcelerator and am quite happy with it, except: I cannot find a option for setting the zoom of a particular worksheet. I am using pyExcelerator 0.6.3a which is the latest as far as i know. That is the latest released version (three years ago). There have been a few bug-fixes and enhancements since then (last change: 21 months ago); to access them you would need to get the source from the sourceforge svn repository. You may be interested in xlwt, a fork of pyExcelerator; see http://pypi.python.org/pypi/xlwt ... also consider joining the python- excel discussion group at http://groups.google.com/group/python-excel I already contacted the developer of pyExcelerator, [jaw drops] Ambiguity resolution please: do you mean the author (rvk) or the subsequent transient maintainer (gwashburn) or the recent apparition (dizzy_ghost)? he says there is a zoom-option in Worksheet.py, but it seems not to be there in my version. It's there, it's called normal_magn (normal view as opposed to page- break preview view, and magn being short for magnification). However it doesn't work. It could be made to work (in xlwt). Further discussion in the python-excel group if you are interested. Which UI would viewers of your files be using? Excel 2003 and Gnumeric 1.9.1 are OK, but OpenOffic.org Calc v2 has a problem: given a file hand-crafted using Excel 2003 with (say) 50% mag in first sheet and 200% mag in second sheet, it displays second sheet with 50% mag not 200%. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg Expression - Get position of
On Tue, 25 Nov 2008 12:41:53 -0800 (PST), r [EMAIL PROTECTED] wrote: On Nov 25, 10:36 am, M_H [EMAIL PROTECTED] wrote: Hey, I need the position of the last char Let's say I have a string mystr = mimetype=text/htmlcontent![CDATA[ I need the posistion of the (second sign) - so I can cut away the first part. The problem is that it can be like but also like or But it is def the quotes and the closing brakets. How do I get the position of the Hope you can help, Bacco why not just spilt mystr = 'mimetype=text/htmlcontent![CDATA[' mystr.split('', 2)[-1] '![CDATA[' you don't want to use an re for something like this Depends on if you have an irrational fear of REs or not ... I agree that REs are overused for things which are better done with split, but in this case I think an RE would be clearer. re.sub('.*', '', 'dkjkdjdd') 'dd' -- assuming he means what I think he means. The question was almost impossible to comprehend. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Security implications of using open() on untrusted strings.
Jorgen Grahn wrote: Compare with a language (does Perl allow this?) where if the string is rm -rf /|, open will run rm -rf / and start reading its output. *That* interface would have been Good example. (for perl): The problem doesn't exist in python open(rm -rf / |) would try to open a file with exactly that name and it would fail if it doesn't exist. In perl the perl script author has the choice to be safe (three argument open) or to allow stupid or nice things with a two argument open. In perl: open($fh,rm -rf / |) would execute the command rm -rf / and pass it's output to perl In perl: open($fh,rm -rf / |,) would work as in python The only similiar pitfall for pyhon would be popen() in a context like filename=userinput() p = os.popen(md5sum +f) here you would have unexpected behavior if filename were something like bla ; rm -rf / Sometimes I miss the 'dangerous variation' in python and I explicitely add code in python that the filename '-' will be treated as stdin for files to be read and as stdout for files to be written to bye N -- http://mail.python.org/mailman/listinfo/python-list