Re: How to stop an [Rpyc] server thread?
Saizan wrote: I embedded an Rpyc threaded server in a preexistent daemon (an irc bot), this is actually very simple; start_threaded_server(port = DEFAULT_PORT) then I had the necessity to stop the thread which accept() new connections without killing the whole app, the thread is simply a while True that spawn a new thread which serves each connection, so I placed a flag and a break in this way: def local_threaded_server(port = DEFAULT_PORT, **kw): global stop sock = create_listener_socket(port) while True: newsock, name = sock.accept() t = Thread(target = serve_socket, args = (newsock,), kwargs = kw) t.setDaemon(True) t.start() if stop: break First off, instead of the while True and the break, you could write: while not stop: but, since sock.accept() blocks, when I set stop=True the server wait one more connection and only then stops. I tried sock.settimeout(10) before entering the while and so checking timeout exception on accept() but I experienced a strange behavior, the clients connections close immediatly, with one of these exceptions on the client side on their first use of the rpc connection: [snip] I'm not an expert in socket programming, but I can't see the correlation between the listener socket being in timeout mode and a different behavior the other sockets.. Anyhow the main goal is being able to shut down the thread of the rpyc server, any other way is an appreciated suggestion. Now to the real issue. I've also had such weird problems with socket timeout in Python. The best workaround I found is to use select() to check for activity on the socket(s), and use select()'s timeout mechanism. So far, this has worked without a hitch on both WindowsXP and Solaris Sparc9 installations. - Tal reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.-,l.Z95193+179-']]*18)[3] -- http://mail.python.org/mailman/listinfo/python-list
Question about subclassing - version 2
Hi all I recently posted a question about subclassing. I did not explain my full requirement very clearly, and my proposed solution was not pretty. I will attempt to explain what I am trying to do more fully, and describe a possible solution. It is still not pretty, so I would appreciate any comments. I have a base class (ClassA), which is an abstract class. Most of the methods and attributes are common to all subclasses, so there is not much they have to override. I have a subclass (ClassB) of my base class, which is also abstract. It represents a subset of ClassA, and overrides some of its methods. When I create a concrete class (is that the correct term?) I subclass either from ClassA or from ClassB. Now I want to represent a different subset of ClassA, which overrides some of its methods. This subset can apply to ClassB as well as to ClassA. In pseudo terms, I want ClassA1, ClassA2, ClassB1, and ClassB2 where A1 is the base class, B overides some methods, and 2 overrides other methods, and I want to subclass from any of them. My original solution involved passing 1 or 2 as an argument, and putting some code into __init__ which redefined certain methods if it received a 2. This worked, but it meant that I could not then easily redefine the method again in a concrete class. My new idea is to use multiple inheritance. This is how it would work. class ClassA(object): def __init__(self): pass def test1(self): print 'Base method 1' def test2(self): print 'Base method 2' class ClassB(ClassA): def __init__(self): ClassA.__init__(self) def test1(self): print 'Overriding method 1' class Class2(object): def test2(self): print 'Overriding method 2' Now I can set up the following concrete classes - class ClassA1(ClassA): def __init__(self): ClassA.__init__(self) class ClassA2(Class2,ClassA): def __init__(self): ClassA.__init__(self) class ClassB1(ClassB): def __init__(self): ClassB.__init__(self) class ClassB2(Class2,ClassB): def __init__(self): ClassB.__init__(self) Now if I do the following, I get the results shown, which is what I want - ClassA1().test1() - 'Base method 1' ClassA1().test2() - 'Base method 2' ClassB1().test1() - 'Overriding method 1' ClassB1().test2() - 'Base method 2' ClassA2().test1() - 'Base method 1' ClassA2().test2() - 'Overriding method 2' ClassB2().test1() - 'Overriding method 1' ClassB2().test2() - 'Overriding method 2' Now for the real test - class ClassC3(Class2,ClassB): def __init__(self): ClassB.__init__(self) def test1(self): print 'Overriding method 1 from ClassC3' def test2(self): print 'Overriding method 2 from ClassC3' ClassC3().test1() - 'Overriding method 1 from ClassC3' ClassC3().test2() - 'Overriding method 2 from ClassC3' So it works. However, using multiple inheritance is not ideal, and I believe it is not even supported in some languages. Can anyone suggest a better way of tackling this problem? Thanks Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
Re: the first arg to super() must be a type, not a class obj?
metaperl wrote: On p.282 of Python Cookbook and in the Python docs on calling super: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation it is clear that the first argument to super is a class and not a type. However, for the code below, I am getting an error when attempting to provide a class as my first argument and don't understand why. Also, since this is my first attempt at writing anything of any seriousness in Python, any other feedback is welcome. super only works for new-style classes. You could make ftputilx new-style by inheriting from object and FTPHost, but FTPHost is still old-style, and I don't know if that's okay with super. So in your case it would be advisable to use FTPHost.__init__(self) instead of super(ftputilx, self).__init__() Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Frank Millman, just a short note, more expert people can give you better answers. There aren't abstract classes in Python. They are all concrete. You may have classes with undefined methods (they may raise NotImplementedError). Multiple inheritance isn't supported by Java and Ruby, but it is supported by C++ and Python, so you can use it in Python. There are also ways of mixing methods. You may define methods, and then lists of methods to add to your classes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: the first arg to super() must be a type, not a class obj?
Another thing: how does super() work wrt. multiple inheritance? It seems like it returns only the first superclass.regardsAndreOn 9/8/06, Georg Brandl [EMAIL PROTECTED] wrote: metaperl wrote: On p.282 of Python Cookbook and in the Python docs on calling super: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation it is clear that the first argument to super is a class and not a type. However, for the code below, I am getting an error when attempting to provide a class as my first argument and don't understand why. Also, since this is my first attempt at writing anything of any seriousness in Python, any other feedback is welcome.super only works for new-style classes.You could make ftputilx new-style by inheriting from object and FTPHost, but FTPHost is still old-style, and I don't know if that's okay with super.So in your case it would be advisable to useFTPHost.__init__(self)instead ofsuper(ftputilx, self).__init__() Georg--http://mail.python.org/mailman/listinfo/python-list-- Dr. Andre P. Meyer http://python.openspace.nl/meyerTNO Defence, Security and Safetyhttp://www.tno.nl/Delft Cooperation on Intelligent Systems http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: StaticText Event
Il Fri, 08 Sep 2006 10:24:52 +1000, John McMonagle ha scritto: If you want to create static text that responds to mouse events, try using the wx.lib.stattext.GenStaticText class. Add the following import: import wx.lib.stattext Then, self.st = wx.lib.stattext.GenStaticText(self.pnl, -1, 'Static Text Control', pos=(30,20)) Thankyou very much! Best regards, David -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
[EMAIL PROTECTED] wrote: Frank Millman, just a short note, more expert people can give you better answers. There aren't abstract classes in Python. They are all concrete. You may have classes with undefined methods (they may raise NotImplementedError). Multiple inheritance isn't supported by Java and Ruby, but it is supported by C++ and Python, so you can use it in Python. There are also ways of mixing methods. You may define methods, and then lists of methods to add to your classes. Bye, bearophile I use the term 'abstract class' in the abstract sense :-) Say I have three classes where 90% of the attributes and methods are common. It makes sense to create a base class with these attributes and methods, and turn each of the three classes into a subclass which inherits from the base class and overrides the bits that are unique to each one. This is what I call an abstract class. Maybe there is a more correct term. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: StaticText Event
Il Fri, 08 Sep 2006 02:32:41 +0200, Amaury Forgeot d'Arc ha scritto: I quick Google search found the following thread: http://lists.wxwidgets.org/archive/wx-users/msg31855.html or http://lists.wxwidgets.org/archive/wx-users/msg31983.html It suggest that you use another kind of control instead. Is a disabled TextCtrl acceptable? Hope this helps, Yes, it does! Thankyou! Best regards David -- http://mail.python.org/mailman/listinfo/python-list
Re: Positive lookahead assertion
tobiah wrote: Posted via a free Usenet account from http://www.teranews.com Its all about context. If you want to match something but only if it precedes something else, then you follow the regular expression for 'something' by the regular expression for 'something else' where `something else` is enclosed by (?=...) The regular expression engine will surreptitiously check that 'something else' does indeed follow, before returning any match of 'something'. How would this differ from just re.search('somethingsomething else') The difference is only significant if your pattern contains groups that should be available after the match is complete, or if the match is folloed by further match elements. A lookahead assertion does precisely that: it looks past the current cursor position and allows an assertion about the contents, but without moving the cursor position. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Javadoc style python manual?
Hi there, I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. But in python, i find it kind of inconvient. Any advice? Thx, Xiong -- http://mail.python.org/mailman/listinfo/python-list
Re: Negation in regular expressions
George Sakkis wrote: It's always striked me as odd that you can express negation of a single character in regexps, but not any more complex expression. Is there a general way around this shortcoming ? Here's an example to illustrate a use case: import re # split with '@' as delimiter [g.group() for g in re.finditer('[EMAIL PROTECTED]', 'This @ is a @ test ')] ['This ', ' is a ', ' test '] Is it possible to use finditer to split the string if the delimiter was more than one char long (say 'XYZ') ? [yes, I'm aware of re.split, but that's not the point; this is just an example. Besides re.split returns a list, not an iterator] I think you are looking for negative lookahead assertions. See the docs. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
[EMAIL PROTECTED] wrote: Frank Millman, just a short note, more expert people can give you better answers. There aren't abstract classes in Python. Well... There's no abstract modifier at least - but there still are abstract classes, ie not meant to be directly instanciated. You mentioned NotImplementedError, which is indeed the usual way to make something abstract in Python. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: the first arg to super() must be a type, not a class obj?
metaperl wrote: On p.282 of Python Cookbook and in the Python docs on calling super: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation it is clear that the first argument to super is a class and not a type. However, for the code below, I am getting an error when attempting to provide a class as my first argument and don't understand why. Also, since this is my first attempt at writing anything of any seriousness in Python, any other feedback is welcome. I believe it needs to be a class whose ultimate ancestor is object, and not an old-style class. This is probably why the docs suggest a type is required. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: help with unicode email parse
In [EMAIL PROTECTED], neoedmund wrote: john , you can look my code: it downloads email and save to local filesystem(filename and email contains non-english characters) it works now. but i still think python's unicode string is not as straightforward as java's string SHOULD always be unicode. or i'm trouble dealing them when they are in different encodings. because before using it, i must try to find what encoding it use, unicode or 8bit. and why the system use ascii to decode. you have explained some, but i cannot catch up you. however i never have encoding problem using string in java. Really? That would be true magic. Outside the program strings have to be encoded somehow so they always have to be decoded when you want a unicode string. And it's impossible to guess the encoding 100% correctly. Just go ahead and create some text files encoded in `utf-8`, `iso-8859-1`, `ibm850` and make sure they contain characters that are not encoded with the same byte values across those encodings, umlauts for instance. Hällö might be a good test string. Now read all those different text files an print the content in Java and see yourself that it's necessary to give the encoding explicitly if you want to deal with arbitrary encodings and not just the default Java uses. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Frank Millman wrote: Hi all I recently posted a question about subclassing. I did not explain my full requirement very clearly, and my proposed solution was not pretty. I will attempt to explain what I am trying to do more fully, and describe a possible solution. It is still not pretty, so I would appreciate any comments. I have a base class (ClassA), which is an abstract class. Most of the methods and attributes are common to all subclasses, so there is not much they have to override. I have a subclass (ClassB) of my base class, which is also abstract. It represents a subset of ClassA, and overrides some of its methods. When I create a concrete class (is that the correct term?) I subclass either from ClassA or from ClassB. Now I want to represent a different subset of ClassA, which overrides some of its methods. This subset can apply to ClassB as well as to ClassA. In pseudo terms, I want ClassA1, ClassA2, ClassB1, and ClassB2 where A1 is the base class, B overides some methods, and 2 overrides other methods, and I want to subclass from any of them. My original solution involved passing 1 or 2 as an argument, and putting some code into __init__ which redefined certain methods if it received a 2. This worked, but it meant that I could not then easily redefine the method again in a concrete class. My new idea is to use multiple inheritance. This is how it would work. class ClassA(object): def __init__(self): pass def test1(self): print 'Base method 1' def test2(self): print 'Base method 2' class ClassB(ClassA): def __init__(self): ClassA.__init__(self) def test1(self): print 'Overriding method 1' class Class2(object): def test2(self): print 'Overriding method 2' To be pedantic, Class2.test2 is not overridding anything, since there's no test2 method in it's parent class. Now I can set up the following concrete classes - class ClassA1(ClassA): def __init__(self): ClassA.__init__(self) If that's the only thing you do in the __init__, then don't bother write an init method at all. class ClassA2(Class2,ClassA): def __init__(self): ClassA.__init__(self) May I suggest having a look at super() ? class ClassB1(ClassB): def __init__(self): ClassB.__init__(self) class ClassB2(Class2,ClassB): def __init__(self): ClassB.__init__(self) Now if I do the following, I get the results shown, which is what I want - ClassA1().test1() - 'Base method 1' ClassA1().test2() - 'Base method 2' ClassB1().test1() - 'Overriding method 1' ClassB1().test2() - 'Base method 2' ClassA2().test1() - 'Base method 1' ClassA2().test2() - 'Overriding method 2' ClassB2().test1() - 'Overriding method 1' ClassB2().test2() - 'Overriding method 2' Now for the real test - class ClassC3(Class2,ClassB): def __init__(self): ClassB.__init__(self) def test1(self): print 'Overriding method 1 from ClassC3' def test2(self): print 'Overriding method 2 from ClassC3' ClassC3().test1() - 'Overriding method 1 from ClassC3' ClassC3().test2() - 'Overriding method 2 from ClassC3' So it works. However, using multiple inheritance is not ideal, Why so ? Multiple inheritence is a pretty useful tool - but it can become tricky very soon. IMHO, it's best use is for mixin classes... and I believe it is not even supported in some languages. A lot of things aren't even supported in some languages !-) Can anyone suggest a better way of tackling this problem? Not out of my hat. Just a few considerations on Python and OO: Python being dynamically typed, inheritence is only about sharing implementation. There's another way to do share implementation - composition/delegation. It's more flexible, and can avoid cartesian product multiplication of classes. It's also less advertised than inheritance - probably because of some languages that fail to offer any support for it. The good news here is that Python makes it a breeze, thanks to the __getattr__/__setattr__ hooks. Now I don't know if it makes any sense WRT/ your current problem... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: the first arg to super() must be a type, not a class obj?
Andre Meyer wrote: Another thing: how does super() work wrt. multiple inheritance? It seems like it returns only the first superclass. The whole point of super is that it returns the first superclass in the MRO that *follows* the class of the (first) argument. It's this behaviour that makes super() useful in multiple inheritance situations (if you believe that super() is in fact useful - there are those who have their doubts). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Middle Tier Architechure?
Butternut Squash wrote: What do you guys recommend for doing middle tier in python. I want to hide the database from the application Why ? -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLwaterheadretard3 (Was: Is it just me, or is Sqlite3 goofy?)
[EMAIL PROTECTED] wrote: Bruno Desthuilliers wrote: SQLite never pretended to be a full-blown RDBMS - just a lightweight simple embedded database as SQL-compliant as possible. Ah, *you* haven't read the documentation either! as SQL-compliant as possible? ROTFLMAO! No need to be rude really. In this context as SQL-compliant as possible means, as SQL-compliant as it is possible to be within the project's restrictions, which presumably refer to code size and speed. It's a reasonable trade-off. ** * The authors argue that static typing is a bug in the * * SQL specification that SQLite has fixed in a backwards * * compatible way.* ** /quote Fixed? Up until now, I didn't think it was possible for crackpot theories to be implemented in computer science. This is absolutely the craziest thing I've ever heard. It's not a crackpot theory. It's a completely reasonable theory. SQL is based on relational algebra, which provides a mathematical set of operators for grouping data that is stored in separate sets. That data is selected and projected according to its value, and nothing else. The concept of it having a 'type' has been overlaid on top of this, presumably to facilitate efficient implementation, which tends to require fixed-width rows (and hence columns). It's not necessary in any sense, and it's reasonable to argue that if it was trivial to implement variable width columns as efficiently as fixed width columns, that explicit data types might never have needed to exist. So much for If switching to a larger database such as PostgreSQL or Oracle is later necessary, the switch should be relatively easy. If you rely too much on a language-enforced data type rather than the values of the underlying data, perhaps Python is not for you! Personally I've migrated from SQLite to MySQL a couple of times (on small projects, granted) and not found it to be a problem at all. Fixing the documentation is now becoming an enormous task. I don't think so... it doesn't take much to say that the module implements a subset of SQL but stores ignores data types. What are the chances that anything I send in as a bug report will simply be ignored? Kind of like the Emporer's New Clothes, eh? It would be an admission of ignorance and stupidity on the part of the Python Development Team, wouldn't it? Why get so bitter over this? I agree the docs need fixing but you make it sound like this was a deliberate attempt to make you waste your time. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
[EMAIL PROTECTED] wrote: I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. But in python, i find it kind of inconvient. My advice is to get used to it... the Python docs are not arranged in the hierarchical fashion because there isn't any real hierarchy to speak of. Python does not rely heavily on inheritance like Java does. Instead, it is used in just a few places, more like the C++ standard library than the Java library. I agree that the Python docs aren't quite as effective as reference material due to the lack of simple function and method lists though. I don't know if there's a solution to that anywhere. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
mobile phone app
hi, Can anyone tell me if python can be used for developing mobile phone apps as Java ? If yes, any comparisons ? Also pls tell me where i can get the tools and tutorials for the same... Thanks in advance... -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter listbox:get
[EMAIL PROTECTED] Wrote: | Hi, | I need help about Tkinter.I want,when somebody click on some item in | listbox,then | in new entry widget must write that item | | Regards, | Vedran I have already covered the retrieval from the listbox in another thread. You can set the entry box contents like this: NameOfStringForEntryboxContents = StringVar() Then in your definition of the Entry box, add in: textvariable = NameOfStringForEntryboxContents and when you have retreived the listbox entry: NameOfStringForEntryboxContents.set(NameOfStringWithListboxStuff) and it will appear in your entry field... HTH -Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
[EMAIL PROTECTED] wrote: Hi there, I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. But in python, i find it kind of inconvient. Any advice? With AcitvePython is distributed the htmlhelp version of python reference (ActivePython24.chm). It's really convinient to use. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
Simon Brunning wrote: It's not inconcevable that Python could behave that way, it's just that it would impose an overhead on the 99.999% of Python users who would have no use for the feature. It's a price not worth paying. I guess I don't get the problem with the OP's request, either. There is already a name-identifier mapping in place for objects. You can type the object name and python magically gives you the object by matching the name to the identifier. It would probably be pretty simple to expose the name or names associated with the identifier, if any, via built-in function or method. There would be no extra overhead. There would be no speed hit if you didn't call the function/method. There would be very little implementation expense (I would imagine), as the code that is already in place to do look-ups from the parser to the object map could probably be reused or hooked into. But seeing as it isn't a general-purpose feature, and Steven's function would be sufficient for most cases, I'm not saying it should be a core feature; I'm just saying that I don't see what the big huff is about. -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
On Fri, 08 Sep 2006 01:11:06 -0700, xiong.xu.cn wrote: Hi there, I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. But in python, i find it kind of inconvient. Any advice? Thx, Xiong pydoc is something I know, it is included in the standard distibution -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Frank Millman wrote: [EMAIL PROTECTED] wrote: There aren't abstract classes in Python. They are all concrete. (snip) I use the term 'abstract class' in the abstract sense :-) Say I have three classes where 90% of the attributes and methods are common. It makes sense to create a base class with these attributes and methods, and turn each of the three classes into a subclass which inherits from the base class and overrides the bits that are unique to each one. This is what I call an abstract class. Maybe there is a more correct term. Depends if instanciating this base class would make any sense. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Negation in regular expressions
Steve Holden wrote: George Sakkis wrote: It's always striked me as odd that you can express negation of a single character in regexps, but not any more complex expression. Is there a general way around this shortcoming ? The whole point of regexes is that they define expressions to match things. [^x] doesn't express the negation of x, it is shorthand for [a-wy-z...]. But the intent is still to match something. What you seem to want is a way of saying Match anything that doesn't match the string 'XYZ' (for example) What do you expect to get back from this? In the string abcd XYZ hhh XYZ for example, XYZ h doesn't match XYZ, nor does the empty string, nor does the entire string. I think you are looking for negative lookahead assertions. See the docs. Negative lookahead and lookbehind are great for expressing that you want to match X as long as it isn't followed by Y ( X(?!Y) ) but won't help much in your finditer example. Is there a particular reason you don't want to use split? -- http://mail.python.org/mailman/listinfo/python-list
Re: change property after inheritance
Le jeudi 07 septembre 2006 15:33, Steven Bethard a écrit : Well, lambda's not going away[1], Sure, they won't. but there's no *need* for lambda here. It could be written as:: Le jeudi 07 septembre 2006 17:16, George Sakkis a écrit : Sure, it *could*; whether it *should* is a different issue. I can't imagine a case for absolute *need* of lambda, but there are several cases where it is probably the best way, such as the one of this thread. I have no preferences here, I used lambdas because it's more compact but they have also their drawback, when the function get a little more complex the code is quickly confusing. The main advantage of the lambdas in this case is to not pollute the class namespace. Le jeudi 07 septembre 2006 23:48, Steven Bethard a écrit : Try using one of the following recipies: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408713 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418 The code i wrote was to demonstrate late binding is usually not needed (and it's not the semantic of properties so it's a bit like make Java in Python). Only the second recipe has to do with it, but is not clean IMHO, it's unnecessary complicated and it introduce a extra level of indentation which is rather confusing, the 'self' variable in accessors is not what it seems to be. Moreover, it introduce a new semantic for a functionality which is already part of the language, what's the goal ? To lost python developers reading your code ? If you really want late binding, the first recipe may be a solution, but it should be both simpler and should not introduce a new semantic (the functions passed as strings is disappointing). I'd write it like this : class LateBindingProperty(property) : __doc__ = property.__dict__['__doc__'] # see bug #576990 def __init__(self, fget=None, fset=None, fdel=None, doc=None) : if fget : fget = lambda s, n=fget.__name__ : getattr(s, n)() if fset : fset = lambda s, v, n=fset.__name__ : getattr(s, n)(v) if fdel : fdel = lambda s, n=fdel.__name__ : getattr(s, n)() property.__init__(self, fget, fset, fdel, doc) In [4]: class A(object) : ...: def getx(self) : return self._x ...: def setx(self, v) : self._x = v ...: p=LateBindingProperty(getx, setx) ...: ...: In [5]: class B(A) : ...: def setx(self, v) : A.setx(self, 2*v) ...: ...: In [8]: a=A() In [9]: a.p = 5 In [10]: a.p Out[10]: 5 In [11]: a._x Out[11]: 5 In [12]: b=B() In [13]: b.p=5 In [14]: b.p Out[14]: 10 -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: mobile phone app
The S60 series of phones from nokia supports python http://www.google.com/search?hl=enq=s60+nokia Cheers, Bryan Rasmussen On 9/8/06, Aravind [EMAIL PROTECTED] wrote: hi, Can anyone tell me if python can be used for developing mobile phone apps as Java ? If yes, any comparisons ? Also pls tell me where i can get the tools and tutorials for the same... Thanks in advance... -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Bruno Desthuilliers wrote: Frank Millman wrote: [EMAIL PROTECTED] wrote: There aren't abstract classes in Python. They are all concrete. (snip) I use the term 'abstract class' in the abstract sense :-) Say I have three classes where 90% of the attributes and methods are common. It makes sense to create a base class with these attributes and methods, and turn each of the three classes into a subclass which inherits from the base class and overrides the bits that are unique to each one. This is what I call an abstract class. Maybe there is a more correct term. Depends if instanciating this base class would make any sense. It would not make sense, no. I have not gone to the trouble of raising NotImplementedError - the methods that the subclasses *must* override just have a 'pass' statement. I guess it would be more correct to raise the error, as it would give me a quicker indication of an error if I happened to omit one, but in practice I would find out pretty quickly anyway. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Le vendredi 08 septembre 2006 09:51, [EMAIL PROTECTED] a écrit : Frank Millman, just a short note, more expert people can give you better answers. There aren't abstract classes in Python. They are all concrete. Really ? This is like saying there is no singleton in Python... class AbstractClass(object) : def __init__(self) : raise RuntimeError('Ths class is an abstract one !') The abstract class can then define APIs (methods which raise NotImplementedError) and/or logic (fully implemented methods). With this scheme you are not stuck to the API only usage of abstract classes like in Java nad its interfaces. You may have classes with undefined methods (they may raise NotImplementedError). C++ pure virtual methods is only the C++ way of doing something which is a more general concept in OOP. -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
On 8 Sep 2006 02:24:49 -0700, MonkeeSage [EMAIL PROTECTED] wrote: I guess I don't get the problem with the OP's request, either. There is already a name-identifier mapping in place for objects. Do you mean a name-object mapping? This, I think, isn't true. There is a name-object mapping, but to make that a name-object mapping *would* carry an overhead. It might (or might not) be a *small* overhead, but since every single Python program would suffer the consequences, it's just not worth it. Especially, as others have pointed out, that it wouldn't really be very useful at all. -- Cheers, Simon B, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
MonkeeSage wrote: Simon Brunning wrote: It's not inconcevable that Python could behave that way, it's just that it would impose an overhead on the 99.999% of Python users who would have no use for the feature. It's a price not worth paying. I guess I don't get the problem with the OP's request, either. There is already a name-identifier mapping in place for objects. You can type the object name and python magically gives you the object by matching the name to the identifier. It would probably be pretty simple to expose the name or names associated with the identifier, if any, via Probably? Based on what assumptions (or knowledge of interpreter internals)? built-in function or method. There would be no extra overhead. There would be no speed hit if you didn't call the function/method. There would be very little implementation expense (I would imagine), as the Which demonstrates that imagination is a wonderful thing ... code that is already in place to do look-ups from the parser to the object map could probably be reused or hooked into. But seeing as it isn't a general-purpose feature, and Steven's function would be sufficient for most cases, I'm not saying it should be a core feature; I'm just saying that I don't see what the big huff is about. I don't think there's any big huff. It's just that Python has achieved its current popularity largely by avoiding bloat and feature creep. As you observe (or seem to), there isn't a one-to-one mapping between names and objects anyway. Put more simply, objects don't *have* names -- names are bound to objects. So modifying the interpreter in the ways you suggest would add unnecessary code to the compiler purely to meet a bogus requirement. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: mobile phone app
Aravind [EMAIL PROTECTED] writes: Can anyone tell me if python can be used for developing mobile phone apps as Java ? If yes, any comparisons ? Also pls tell me where i can get the tools and tutorials for the same... Not in the same league as J2ME, but in some restricted cases, yes. See http://forum.nokia.com/python -- Ganesan Rajagopal -- http://mail.python.org/mailman/listinfo/python-list
Re: xmingw and f2py
Flavio [EMAIL PROTECTED] wrote: has anyone tried to build extensions for win32 on Linux using xmingw? I don't know about xmingw, but we use mingw on linux to compile stuff for windows all the time. (We use the mingw package under debian) We build extensions using mingw but linked to the link library of the official python2.4 build. Here are some instructions which you'll need to adapt to your setup /misc/windows is a smb mounted windows machine # Linking with the distributed python # # http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/cygwin.html # # On a windows machine # install the latest windows python (2.4.3.msi) from www.python.org # Copy the header files into the mingw installation cp -av /misc/windows/Python24/include /usr/i586-mingw32msvc/include/python2.4 # Download pexports from here # http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html # unpack pexports.exe unzip pexports-0.43.zip # Fetch python dll from the windows machine cp -av /misc/windows/WINNT/system32/python24.dll . # Extract the exported symbols wine pexports python24.dll python24.def # Create the link library /usr/i586-mingw32msvc/bin/dlltool --dllname python24.dll --def python24.def --output-lib libpython2.4.a # Move the files into the correct place mv -i python24.dll python24.def libpython2.4.a /usr/i586-mingw32msvc/lib/ After that lot you can build python extensions with mingw under linux, using -lpython2.4 -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Lex Hider wrote: Hi, Apologies if this is against etiquette. I've just got my first python app up and running. It is a podcast aggregator depending on feedparser. I've really only learnt enough to get this up and running. Any tips on the code quality and use of python would be appreciated. I've got a feeling the overall structure is up the creek. approx 220 LOC. file: GodCast.py #!/usr/bin/python (snip) # TODO: not found log http://docs.python.org/lib/module-logging.html # TODO: # config file http://docs.python.org/lib/module-ConfigParser.html # opml feed list? # pygtk/pyqt/qtkde gui? # possible flags: test, print but don't actual do anything http://docs.python.org/lib/module-optparse.html import re, feedparser, os, sys, shutil, time, getopt import urllib2 import urllib import md5 boz = HOME = os.path.expanduser(~) # user configurable #maxChecksPerDay = 8 #maxChecksPerDay = 12 maxChecksPerDay = 24 myTemp = '/tmp' http://docs.python.org/lib/module-tempfile.html BTW, note that the most common naming convention in Python is all_lower_with_underscore (except for ClasseName). #podDir = os.path.join(HOME, 'Audio/Podcasts') podDir = os.path.join(HOME, 'Podcasts') # end user configurable downDir = os.path.join(myTemp, 'Podcasts') dotDir = os.path.join(HOME, '.aGodCast') logFile = os.path.join(dotDir, 'log') #list of downloaded urls cacheDir = os.path.join(dotDir, 'cache') ignoreNotFound = False # if true, add files not found to log # list of feeds, ignore lines not beginning ^http feedList = os.path.join(dotDir, 'feeds.txt') def exitFunc(): #f.close() #log.close() if boz: print boz def makeDirs(*dirs): for dir in dirs: if not os.path.exists(dir): os.makedirs(dir) # render is used because feeds use a lot of html, not just plain text. def render(html): if html: html = re.sub('', '\\', html.encode('utf8')) #command = 'echo ' + html + ' | w3m -dump -T text/html' #command = 'echo ' + html + ' | html2text' command = 'echo ' + html + ' | lynx -dump -stdin -force_html' another way : command = 'echo %s | lynx -dump -stdin -force_html' % html os.system(command) def localMD5(url): hash = md5.new(url).hexdigest() + '.xml' #unique name from url return os.path.join(cacheDir, hash) def cache(url): max = 60 * 60 * 24 / maxChecksPerDay #seconds myfile = localMD5(url) if os.path.isfile(myfile): elapsed = int(time.time()) - os.path.getmtime(myfile) if elapsed = max: return print FETCHING:, url + ' ...' Note that stdout is usually meant for normal program outputs (so one can pipe programs). Error reporting and verbosities should go to stderr urllib.urlretrieve(url, myfile) # handle half finish? def updateCache(feeds): l = [] print updating local xml cache... for feed in file(feeds, r).read().split('\n'): if not re.match('^http://', feed): # feedList ignores anything but urls continue # TODO: handle whitespace, strip trailing cache(feed) l.append([localMD5(feed), feed]) print cache up to date return l def geturl(url): try: redir = urllib2.urlopen(url).geturl() except urllib2.HTTPError, e: if e.code != 404: print url print geturl HTTPError:, e.code return e.code except urllib2.URLError, e: # (110, 'Connection timed out') print e.reason #print geturl URLError:, e.code else: return redir return 0 I'm afraid you didn't get the point of exception handling - it's meant to free function results from error code. Your above code totally defeats this - as is obvious when reading the calling code. redirect = geturl(url) # TRAFFIC if type(redirect) != int: #success do_something_useful_here() elif redirect == 404: print 'NOT FOUND:', url if ignoreNotFound: print '\tWILL NO LONGER ATTEMPT TO DOWNLOAD\n' log(url) else: sys.exit(2) may I suggest a rewrite : try: redirect = urllib2.urlopen(url).geturl() except urllib2.HTTPError, e: if e.code == 404: print 'NOT FOUND:', url if ignoreNotFound: print '\tWILL NO LONGER ATTEMPT TO DOWNLOAD\n' log(url) else: print geturl HTTPError %s on url %s % (e.code, url) raise except urllib2.URLError, e: print geturl URLError %s on url %s % (e.reason, url) else: do_something_useful_here() def htmlTitle(mainTitle, subTitle): s = 'HR' s += 'H2' + mainTitle + '/H2' s += 'H3' + subTitle + '/H3' return s html_title_template = hr h2%(title)s/h2 h3%(subtitle)s/h3 def html_title(title, subtitle): return
Re: A Sort Optimization Technique: decorate-sort-dedecorate
i just want to make it known that i think most if not all of the replies in this thread are of not much technical value. They are either wrong and or misleading, and the perl module mentioned about sorting or the Java language aspect on sorting, as they are discussed or represented, are rather stupid. I may or may not write a detailed account later. If you have specific questions, or want to know specific reasons of my claims, please don't hesitate to email. (privately if you deem it proper) Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ [EMAIL PROTECTED] wrote: Last year, i've posted a tutorial and commentary about Python and Perl's sort function. (http://xahlee.org/perl-python/sort_list.html) In that article, i discussed a technique known among juvenile Perlers as the Schwartzian Transform, which also manifests in Python as its “key” optional parameter. Here, i give a more detailed account on why and how of this construct. ... This post is archived at: http://xahlee.org/perl-python/sort_list.html I would be interested in comments about how Common Lisp, Scheme, and Haskell deal with the decorate-sort-dedecorate technique. In particular, does it manifest in the language itself? If not, how does one usually do it in the code? (note: please reply to approprate groups if it is of no general interest. Thanks) (am also interested on how Perl6 or Python3000 does this, if there are major changes to their sort function) Thanks. Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: xmingw and f2py
Thanks Nick, It seems that xmingw package in gentoo is the same as the mingw on debian, from the directory structure and executables you mention. I'll give it a try and if works with f2py, I'll post a complete tutorial after I am done for other people to follow. Thanks a lot. Nick Craig-Wood wrote: Flavio [EMAIL PROTECTED] wrote: has anyone tried to build extensions for win32 on Linux using xmingw? I don't know about xmingw, but we use mingw on linux to compile stuff for windows all the time. (We use the mingw package under debian) We build extensions using mingw but linked to the link library of the official python2.4 build. Here are some instructions which you'll need to adapt to your setup /misc/windows is a smb mounted windows machine # Linking with the distributed python # # http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/cygwin.html # # On a windows machine # install the latest windows python (2.4.3.msi) from www.python.org # Copy the header files into the mingw installation cp -av /misc/windows/Python24/include /usr/i586-mingw32msvc/include/python2.4 # Download pexports from here # http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html # unpack pexports.exe unzip pexports-0.43.zip # Fetch python dll from the windows machine cp -av /misc/windows/WINNT/system32/python24.dll . # Extract the exported symbols wine pexports python24.dll python24.def # Create the link library /usr/i586-mingw32msvc/bin/dlltool --dllname python24.dll --def python24.def --output-lib libpython2.4.a # Move the files into the correct place mv -i python24.dll python24.def libpython2.4.a /usr/i586-mingw32msvc/lib/ After that lot you can build python extensions with mingw under linux, using -lpython2.4 -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Is it just me, or is Sqlite3 goofy?
While I can understand your frustration, I think it is important to think about the tone in our postings here. Hydrocephalus is one of the most common birth defects, and it's not terribly unlikely that someone who reads this has a family member or someone else in his proximity who suffers from this condition. [EMAIL PROTECTED] wrote: Fixed? Up until now, I didn't think it was possible for crackpot theories to be implemented in computer science. This is absolutely the craziest thing I've ever heard. Still, many people with lots of experience in databases use it, and prefer it for certain kinds of applications. All systems have limitations and deviations, and those limitations and deviations are stated more clearly for SQLite than for most commercial products at least. The market leader Oracle still can't store empty strings in VARCHAR fields for instance. They are silently converted to NULL. I'm pretty sure that has been in clear violation to the official spec since 1986 at least. As far as I understand, noone here is forcing you to use SQLite, and with your long experience of MS Access I'd expect you to be fairly used to almost SQL... It's some time since I used Jet/Access now, but I had much more problems with that than I've had with SQLite. SQLite is built in Tcl, by someone who appreciates the way Tcl works, with its weak typing. I don't think Tcl's type handling is nearly as clever as Python's, but I think it's a good thing that Python's standard lib finally has a DB-API compliant module, and while I would have preferred something that was closer to standard SQL, I don't know of a better candidate than SQLite. It's good that it's usable without a server setup, and that it's very light weight. A Jet engine is obviously not an option, and I would have preferred SQLite even if Jet was open source and worked on all platforms. (Well, if JET *was* open source, I suspect it would have been fixed by now.) It's possible that one could have used the embedded version of Firebird instead, but in my experience that's not nearly as lean or easy to deploy. With your long experience of Access and SQL Server I'm sure you know well that any attempt to build a working database application requires extensive knowledge of the backend to understand its peculiarities and limitations. The list of software projects where not quite competent developers built Access applications that worked ok in small scale tests and failed catastrophically in real life is looong... Of course, if you've stayed with one vendor for 15 years, I can imagine that you've forgotten how long it took you Having worked with half a dozen backends or so, I'm no longer surprised that SQL can be interpreted in so many ways... I agree that SQLite is unique in it's approach to typing, but if you are aware of this, it's really not a big problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Add NTLM proxy authentication to urllib2
Thanks for the answers. I've done some tests with urllib2 and pywin32 and managed to partialy implement the NTLM authentication, but it look like you need a persistent connection (http 1.1 or 'Keep-Alive') to complete the authentication. Unfortunatly, urllib2 use a new connection for each request and changing this behavior look difficult. So I will probably write my own library. Maybe there is something to do with the urlgrabber module ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Beautiful Soup to entangle bookmarks.html
Hi, thanks for the helpful reply. I wanted to do two things - learn to use Beautiful Soup and bring out all the information in the bookmarks file to import into another application. So I need to be able to travel down the tree in the bookmarks file. bookmarks seems to use header tags which can then contain a tags where the href attributes are. What I don't understand is how to create objects which can then be used to return the information in the next level of the tree. Thanks again, Martin. George Sakkis wrote: Francach wrote: Hi, I'm trying to use the Beautiful Soup package to parse through the bookmarks.html file which Firefox exports all your bookmarks into. I've been struggling with the documentation trying to figure out how to extract all the urls. Has anybody got a couple of longer examples using Beautiful Soup I could play around with? Thanks, Martin. from BeautifulSoup import BeautifulSoup urls = [tag['href'] for tag in BeautifulSoup(open('bookmarks.html')).findAll('a')] Regards, George -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Le vendredi 08 septembre 2006 10:15, Bruno Desthuilliers a écrit : You mentioned NotImplementedError, which is indeed the usual way to make something abstract in Python. Hummm, some more thoughts about this. I can imagine class hierarchies where the presence of not implemented methods doesn't mean that the class is actually an abstract one. Even if partial implementation is not a common scheme it can save you from writing a lot of classes. For example : class car : #abstract def accelerate() : raise NotimplementedError def getBaseBuildPrice() : raise NotimplementedError def getOptionsPrice() : raise NotimplementedError def getPublicPrice() : raise NotimplementedError class SerieA(car) : abstract, it's before the car get out of the factory def accelerate() : ... def getBaseBuildPrice() : ... class CrashTestVendorSerieA(SerieA) : concrete, but doesn't implement getPublicPrice def getOptionsPrice() : ... class CommercialSerieA(SerieA) : def getOptionsPrice() : ... def getPublicPrice() : Doing the same with more traditional object design give : class car : #abstract def accelerate() : raise NotimplementedError def getBaseBuildPrice() : raise NotimplementedError class SerialCar : #abstract def getOptionsPrice() : raise NotimplementedError class ComercialCar : #abstract def getPublicPrice() : raise NotimplementedError class SerieA(car, SeriialCar) : #abstract def accelerate() : ... def getBaseBuildPrice() : ... class CrashTestVendorSerieA(SerieA) : # concrete def getOptionsPrice() : ... class CommercialSerieA(SerieA, CommercialCar) : # concrete def getOptionsPrice() : ... def getPublicPrice() : ... And this can become a true spider net for more complicated cases. Obviously, in practice we will choose alternatives to inheritance (strategies, visitors, ...) to work with such complex situations, but it seems to me that partial implementation is not a bad choice, specifically in regard to duck typing. -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
ctypes listing dll functions
hi all and before I start I apologise if I have this completely muddled up but here goes. I'm trying to call functions from a dll file in a python script but I can't work out what functions are available. I'm using ctypes. I've tried using dir(ctypes_object) but the resultant output looks like a list of standard functions and not the ones I'm looking for. Also how can I tell if the dll was written in C or C++ as I understand C++ dlls can't be used. I have a header file that starts; #ifndef __DIRAC__ #define __DIRAC__ // Prototypes const char *DiracVersion(void); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float **data, long numFrames, void *userData)); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float *data, long numFrames, void *userData)); long DiracSetProperty(long selector, long double value, void *dirac); long double DiracGetProperty(long selector, void *dirac); void DiracReset(bool clear, void *dirac); long DiracProcess(float **audioOut, long numFrames, void *userData, void *dirac); long DiracProcess(float *audioOut, long numFrames, void *userData, void *dirac); void DiracDestroy(void *dirac); long DiracGetInputBufferSizeInFrames(void *dirac); I would have thought that DiracCreate, DiracSetProperty etc were all callable functions. As you may have guessed I'm don't do much work in C... Thanks, MW. -- http://mail.python.org/mailman/listinfo/python-list
ctypes listing dll functions
hi all and before I start I apologise if I have this completely muddled up but here goes. I'm trying to call functions from a dll file in a python script but I can't work out what functions are available. I'm using ctypes. I've tried using dir(ctypes_object) but the resultant output looks like a list of standard functions and not the ones I'm looking for. Also how can I tell if the dll was written in C or C++ as I understand C++ dlls can't be used. I have a header file that starts; #ifndef __DIRAC__ #define __DIRAC__ // Prototypes const char *DiracVersion(void); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float **data, long numFrames, void *userData)); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float *data, long numFrames, void *userData)); long DiracSetProperty(long selector, long double value, void *dirac); long double DiracGetProperty(long selector, void *dirac); void DiracReset(bool clear, void *dirac); long DiracProcess(float **audioOut, long numFrames, void *userData, void *dirac); long DiracProcess(float *audioOut, long numFrames, void *userData, void *dirac); void DiracDestroy(void *dirac); long DiracGetInputBufferSizeInFrames(void *dirac); I would have thought that DiracCreate, DiracSetProperty etc were all callable functions. As you may have guessed I'm don't do much work in C... Thanks, MW. -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Lex Hider enlightened us with: Any tips on the code quality and use of python would be appreciated. I've got a feeling the overall structure is up the creek. I'll post some remarks about the code ;-) HOME = os.path.expanduser(~) I wouldn't use this. Just use os.environ['HOME']. In most cases it turns out to be the same directory, but it adds more flexibility. If someone wants your app to read/write to another directory, he/she can simply change the HOME environment variable. # user configurable #maxChecksPerDay = 8 #maxChecksPerDay = 12 maxChecksPerDay = 24 myTemp = '/tmp' #podDir = os.path.join(HOME, 'Audio/Podcasts') podDir = os.path.join(HOME, 'Podcasts') # end user configurable A bit of nitpicking: place a blank line between the user configurable part and the rest of the code. def exitFunc(): #f.close() #log.close() if boz: print boz Write function comments! Use the docstring to describe your function - what does it do, and what does it return? Do this for all functions you write. # render is used because feeds use a lot of html, not just plain text. def render(html): if html: html = re.sub('', '\\', html.encode('utf8')) Use a raw string for the second argument to make it more readable: html = re.sub('', r'\', html.encode('utf8')) command = 'echo ' + html + ' | lynx -dump -stdin -force_html' os.system(command) Use the subprocess module or the popen2 module to open lynx. That way, you can feed the HTML to lynx directly, and you're not bound to the maximum line length of the shell. It also removes the need to escape quotes. def updateCache(feeds): l = [] Use longer names than 'l'. print updating local xml cache... for feed in file(feeds, r).read().split('\n'): if not re.match('^http://', feed): # feedList ignores # anything but urls Here you say you only match URLs starting with http://;, but at the start you claimed to only use URLs starting with http. Be sure to keep your documentation and your code in sync. def htmlTitle(mainTitle, subTitle): s = 'HR' s += 'H2' + mainTitle + '/H2' s += 'H3' + subTitle + '/H3' return s It might be easier on the eyes if you use: s = 'hrh2%s/h2h3%s/h3' % (mainTitle, subTitle) It might also be wise to use lower-case HTML tags to remain compatible with XHTML. def downloadPod(url, dest): kb = 2 success = 0 command = 'wget --continue -O ' + dest + ' ' + url + '' status = os.system(command) Here you pass the arguments of the function to a system call. This means that before the downloadPod function is called, the 'url' and 'dest' should have been escaped or cleared of unwanted characters. This should really be documented. Overall, your code needs to be commented and documented much better. Think of other people reading the code, and explain _why_ you do something, instead of explaining _what_ you're doing. Sybren -- Sybren Stüvel Stüvel IT - http://www.stuvel.eu/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Le vendredi 08 septembre 2006 13:41, Sybren Stuvel a écrit : HOME = os.path.expanduser(~) I wouldn't use this. Just use os.environ['HOME']. In most cases it turns out to be the same directory, but it adds more flexibility. If someone wants your app to read/write to another directory, he/she can simply change the HOME environment variable. and ? [EMAIL PROTECTED] jeu sep 07 09:17:51:~/test$ export HOME=/etc [EMAIL PROTECTED] ven sep 08 13:53:17:/home/maric/test$ cd ~ [EMAIL PROTECTED] ven sep 08 13:53:22:~$ pwd /etc [EMAIL PROTECTED] ven sep 08 13:55:46:~$ python -c 'import os print os.path.expanduser(~) ' /etc -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: xmingw and f2py
Hi Nick, I followed the steps you describe exactly and I am still gettin this error message when i try to compile. here is the command I give: f2py -c --compiler=/opt/xmingw/bin/i386-mingw32msvc-gcc --f77exec=opt/xmingw/bi n/i386-mingw32msvc-g77 -L /opt/xmingw/i386-mingw32msvc/lib/ -lpython2.4 -m flib flib.f and this is the error: copying /usr/lib/python2.4/site-packages/numpy-1.0b5-py2.4-linux-i686.egg/numpy/f2py/src/fortranobject.c - /tmp/tmpIkxhAr/src.linux-i686-2.4 copying /usr/lib/python2.4/site-packages/numpy-1.0b5-py2.4-linux-i686.egg/numpy/f2py/src/fortranobject.h - /tmp/tmpIkxhAr/src.linux-i686-2.4 adding '/tmp/tmpIkxhAr/src.linux-i686-2.4/flib-f2pywrappers.f' to sources. running build_ext error: don't know how to compile C/C++ code on platform 'posix' with '/opt/xmingw/bin/i386-mingw32msvc-gcc' compiler any further suggestions? Nick Craig-Wood wrote: Flavio [EMAIL PROTECTED] wrote: has anyone tried to build extensions for win32 on Linux using xmingw? I don't know about xmingw, but we use mingw on linux to compile stuff for windows all the time. (We use the mingw package under debian) We build extensions using mingw but linked to the link library of the official python2.4 build. Here are some instructions which you'll need to adapt to your setup /misc/windows is a smb mounted windows machine # Linking with the distributed python # # http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/cygwin.html # # On a windows machine # install the latest windows python (2.4.3.msi) from www.python.org # Copy the header files into the mingw installation cp -av /misc/windows/Python24/include /usr/i586-mingw32msvc/include/python2.4 # Download pexports from here # http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html # unpack pexports.exe unzip pexports-0.43.zip # Fetch python dll from the windows machine cp -av /misc/windows/WINNT/system32/python24.dll . # Extract the exported symbols wine pexports python24.dll python24.def # Create the link library /usr/i586-mingw32msvc/bin/dlltool --dllname python24.dll --def python24.def --output-lib libpython2.4.a # Move the files into the correct place mv -i python24.dll python24.def libpython2.4.a /usr/i586-mingw32msvc/lib/ After that lot you can build python extensions with mingw under linux, using -lpython2.4 -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Le vendredi 08 septembre 2006 13:56, Maric Michaud a écrit : [EMAIL PROTECTED] jeu sep 07 09:17:51:~/test$ export HOME=/etc [EMAIL PROTECTED] ven sep 08 13:53:17:/home/maric/test$ cd ~ [EMAIL PROTECTED] ven sep 08 13:53:22:~$ pwd /etc [EMAIL PROTECTED] ven sep 08 13:55:46:~$ python -c 'import os print os.path.expanduser(~) ' /etc Of course it's not the same as : [EMAIL PROTECTED] ven sep 08 13:58:25:~$ export HOME=/etc [EMAIL PROTECTED] ven sep 08 14:00:11:~$ python -c 'import os print os.path.expanduser(~maric) ' /home/maric -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Middle Tier Architechure?
2006/9/7, Butternut Squash [EMAIL PROTECTED]: right now we are using c# and .net remoting in a way that just is not efficient. I want to rewrite a lot of what we do in python. I have seen XML-RPC and soap. Are there other options? It surely depends on what's going to be on the other sides. If everything is Python, you may use Twisted.Spread. If you have to communicate with different languages and plataforms, maybe CORBA helps. Well, I'm sure a lot of people know more options than I do here. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Beautiful Soup to entangle bookmarks.html
Francach wrote: George Sakkis wrote: Francach wrote: Hi, I'm trying to use the Beautiful Soup package to parse through the bookmarks.html file which Firefox exports all your bookmarks into. I've been struggling with the documentation trying to figure out how to extract all the urls. Has anybody got a couple of longer examples using Beautiful Soup I could play around with? Thanks, Martin. from BeautifulSoup import BeautifulSoup urls = [tag['href'] for tag in BeautifulSoup(open('bookmarks.html')).findAll('a')] Hi, thanks for the helpful reply. I wanted to do two things - learn to use Beautiful Soup and bring out all the information in the bookmarks file to import into another application. So I need to be able to travel down the tree in the bookmarks file. bookmarks seems to use header tags which can then contain a tags where the href attributes are. What I don't understand is how to create objects which can then be used to return the information in the next level of the tree. Thanks again, Martin. I'm not sure I understand what you want to do. Originally you asked to extract all urls and BeautifulSoup can do this for you in one line. Why do you care about intermediate objects or if the anchor tags are nested under header tags or not ? Read and embrace BeautifulSoup's philosophy: You didn't write that awful page. You're just trying to get some data out of it. Right now, you don't really care what HTML is supposed to look like. George -- http://mail.python.org/mailman/listinfo/python-list
ANN: Leo 4.4.1.1 final released
Leo 4.4.1.1 final September 3, 2006 Leo 4.4.1.1 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Leo 4.4.1.1 corrects a last-minute unicode bug in Leo 4.4.1. This version also adds the new slideshow plugin. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: - Leo outputs decorators correctly, provided that the decorator is not a Leo directive. - A new colorizer plugin controlled by jEdit language description files. - A new shadow files plugin that allows derived files not to have sentinel lines. - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - Several new commands including run-unit-test, python-help, toggle-invisibles, and scroll-outline-left/right. - The help-for-command commands now contains information for almost all commands. - A new shortcut_button plugin. Quote of the month: --- Thanks for creating the most useful and amazing application that I've come across in years. I use Leo every day. Links: -- 4.4.1:http://webpages.charter.net/edreamleo/new-4-4-1.html 4.4: http://webpages.charter.net/edreamleo/new-4-4.html Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
A static pychecker?
I am wondering whether anyone knows of a static source-code analyzer for Python, kinda like a static pychecker. That is, instead of being a run-time tool as pychecker is, it would be a 'compile-time' tool. If I were writing such a thing it would use the ast returned from compiler.parse. Unlike the inspect module, it would peruse the code looking for possible problems. Thanks. Edward Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
Re: A static pychecker?
On Fri, 8 Sep 2006 08:00:25 -0500, Edward K. Ream [EMAIL PROTECTED] wrote: I am wondering whether anyone knows of a static source-code analyzer for Python, kinda like a static pychecker. That is, instead of being a run-time tool as pychecker is, it would be a 'compile-time' tool. If I were writing such a thing it would use the ast returned from compiler.parse. Unlike the inspect module, it would peruse the code looking for possible problems. pyflakes is this. It looks for significantly fewer problems than pychecker, but it doesn't require modules to be importable to examine them and it is significantly faster. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: A static pychecker?
Edward I am wondering whether anyone knows of a static source-code Edward analyzer for Python, kinda like a static pychecker. Pychecker v2 was supposed to use source analysis instead of importing the modules. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it just me, or is Sqlite3 goofy?
I've made the following edits: Index: whatsnew25.tex === --- whatsnew25.tex (revision 51828) +++ whatsnew25.tex (working copy) @@ -2116,14 +2116,16 @@ SQLite embedded database, has been added to the standard library under the package name \module{sqlite3}. -SQLite is a C library that provides a SQL-language database that -stores data in disk files without requiring a separate server process. +SQLite is a C library that provides a lightweight disk-based database +that doesn't require a separate server process and allows accessing +the database using a nonstandard variant of the SQL query language. +Some applications can use SQLite for internal data storage. It's also +possible to prototype an application using SQLite and then port the +code to a larger database such as PostgreSQL or Oracle. + pysqlite was written by Gerhard H\aring and provides a SQL interface compliant with the DB-API 2.0 specification described by -\pep{249}. This means that it should be possible to write the first -version of your applications using SQLite for data storage. If -switching to a larger database such as PostgreSQL or Oracle is -later necessary, the switch should be relatively easy. +\pep{249}. If you're compiling the Python source yourself, note that the source tree doesn't include the SQLite code, only the wrapper module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Beautiful Soup to entangle bookmarks.html
Hi George, Firefox lets you group the bookmarks along with other information into directories and sub-directories. Firefox uses header tags for this purpose. I'd like to get this grouping information out aswell. Regards, Martin. the idea is to extract. George Sakkis wrote: Francach wrote: George Sakkis wrote: Francach wrote: Hi, I'm trying to use the Beautiful Soup package to parse through the bookmarks.html file which Firefox exports all your bookmarks into. I've been struggling with the documentation trying to figure out how to extract all the urls. Has anybody got a couple of longer examples using Beautiful Soup I could play around with? Thanks, Martin. from BeautifulSoup import BeautifulSoup urls = [tag['href'] for tag in BeautifulSoup(open('bookmarks.html')).findAll('a')] Hi, thanks for the helpful reply. I wanted to do two things - learn to use Beautiful Soup and bring out all the information in the bookmarks file to import into another application. So I need to be able to travel down the tree in the bookmarks file. bookmarks seems to use header tags which can then contain a tags where the href attributes are. What I don't understand is how to create objects which can then be used to return the information in the next level of the tree. Thanks again, Martin. I'm not sure I understand what you want to do. Originally you asked to extract all urls and BeautifulSoup can do this for you in one line. Why do you care about intermediate objects or if the anchor tags are nested under header tags or not ? Read and embrace BeautifulSoup's philosophy: You didn't write that awful page. You're just trying to get some data out of it. Right now, you don't really care what HTML is supposed to look like. George -- http://mail.python.org/mailman/listinfo/python-list
Re: split string problems
Tempo wrote: Hey. I am trying to grab the prices from the string below but I get a few errors when I try to do it: Take a look at the code and error messages below for me and thanks you in advanced to all that help. Thank you. Here's the code error messages: p [span class=sale $14.99 /span, span class=sale $27.99 /span, span class=sale $66.99 /span, span class=sale $129.99 /span, span class=sale $254.99 /span] p.split()[2] Traceback (most recent call last): File pyshell#11, line 1, in -toplevel- p.split()[2] AttributeError: 'ResultSet' object has no attribute 'split' The contents of p is rather odd looking. It isn't html that was read from a website (note the commas after /span). You show it as if it is a list of strings, but the strings don't have quotes around them. How are you creating the object p? If you would just get it into a single string (with something like: x=urllib.urlopen(url) p=x.read() then you can use elementree, or beautiful soup to get your prices quite easily. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: PILGraph Upgrade or Alternative Suggestion
Roger wrote: Anyone have an updated version of PILGraph beyond 0.1a7 or a suggestion for a light-weight alternative? By light-weight I mean something that doesn't require many/any packages other than PIL and will create plain old round pie-chart PNG graphics with titles and legends. I do need multi-platform for both Linux and Windows. The intended use is to create graphics for web pages on the fly. TIA, Roger ReportLab Graphics works pretty well for me. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Middle Tier Architechure?
On Fri, 8 Sep 2006 03:59:46 +0200, Butternut Squash wrote (in article [EMAIL PROTECTED]): I have seen XML-RPC and soap. Are there other options? OmniORBpy Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove .nospam to reply. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Beautiful Soup to entangle bookmarks.html
Francach wrote: Firefox lets you group the bookmarks along with other information into directories and sub-directories. Firefox uses header tags for this purpose. I'd like to get this grouping information out aswell. import libxml2dom # http://www.python.org/pypi/libxml2dom d = libxml2dom.parse(bookmarks.html, html=1) for node in d.xpath(html/body//dt/*[1]): if node.localName == h3: print Section:, node.nodeValue elif node.localName == a: print Link:, node.getAttribute(href) One exercise, using the above code as a starting point, would be to reproduce the hierarchy exactly, rather than just showing the section names and the links which follow them. Ultimately, you may be looking for a way to just convert the HTML into a simple XML document or into another hierarchical representation which excludes the HTML baggage and details irrelevant to your problem. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Negation in regular expressions
Paddy wrote: George Sakkis wrote: It's always striked me as odd that you can express negation of a single character in regexps, but not any more complex expression. Is there a general way around this shortcoming ? Here's an example to illustrate a use case: import re # split with '@' as delimiter [g.group() for g in re.finditer('[EMAIL PROTECTED]', 'This @ is a @ test ')] ['This ', ' is a ', ' test '] Is it possible to use finditer to split the string if the delimiter was more than one char long (say 'XYZ') ? [yes, I'm aware of re.split, but that's not the point; this is just an example. Besides re.split returns a list, not an iterator] George If your wiling to use groups then the following will split [g.group(1) for g in re.finditer(r'(.+?)(?:@#|$)', 'This @# is a @# test ')] ['This ', ' is a ', ' test '] Nice! This covers the most common case, that is non-consecutive delimiters in the middle of the string. There are three edge cases: consecutive delimiters, delimiter(s) in the beginning and delimiter(s) in the end. The regexp r'(.*?)(?:@#|$)' would match re.split's behavior if it wasn't for the last empty string it returns: s = '@# This @# is a @[EMAIL PROTECTED] test ' re.split(r'@#', s) ['', ' This ', ' is a ', '', ' test '] [g.group(1) for g in re.finditer(r'(.*?)(?:@#|$)', s)] ['', ' This ', ' is a ', '', ' test ', ''] Any ideas ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Frank Millman wrote: Bruno Desthuilliers wrote: Frank Millman wrote: [EMAIL PROTECTED] wrote: There aren't abstract classes in Python. They are all concrete. (snip) I use the term 'abstract class' in the abstract sense :-) Say I have three classes where 90% of the attributes and methods are common. It makes sense to create a base class with these attributes and methods, and turn each of the three classes into a subclass which inherits from the base class and overrides the bits that are unique to each one. This is what I call an abstract class. Maybe there is a more correct term. Depends if instanciating this base class would make any sense. It would not make sense, no. I have not gone to the trouble of raising NotImplementedError - the methods that the subclasses *must* override just have a 'pass' statement. I guess it would be more correct to raise the error, as it would give me a quicker indication of an error if I happened to omit one, but in practice I would find out pretty quickly anyway. Mmm... My own experience is that methods that *must* be redefined are better raising NotImplementedError. Makes things more obvious IMHO. Now there are of course methods that are only provided as hooks - here it's ok to have some no-op default behaviour. My 2 cents Frank -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
Ben Sizer wrote: I agree that the Python docs aren't quite as effective as reference material due to the lack of simple function and method lists though. http://docs.python.org/lib/modindex.html, pydoc and ipython are more than enough for me. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Negation in regular expressions
re.split(r'@#', s) ['', ' This ', ' is a ', '', ' test '] [g.group(1) for g in re.finditer(r'(.*?)(?:@#|$)', s)] ['', ' This ', ' is a ', '', ' test ', ''] If it's duplicating the behaviour of split, but returning an iterator instead, how about avoiding hacking around with messy regexes and use something like the following generator: def splititer(pattern, string): posn = 0 while True: m = pattern.search(string, posn) if not m: break yield string[posn:m.start()] posn = m.end() -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Bruno Desthuilliers wrote: Frank Millman wrote: I have not gone to the trouble of raising NotImplementedError - the methods that the subclasses *must* override just have a 'pass' statement. I guess it would be more correct to raise the error, as it would give me a quicker indication of an error if I happened to omit one, but in practice I would find out pretty quickly anyway. Mmm... My own experience is that methods that *must* be redefined are better raising NotImplementedError. Makes things more obvious IMHO. Can't argue with that. I have just gone through my app and changed them all :-) Frank -- http://mail.python.org/mailman/listinfo/python-list
Help with ctypes pointer return values
I am trying to call a DLL with a function like this: DESCRIPTION: Get a list of objects attributes matching attribute values ARGUMENTS: session: [in] the current session classId: [in] the class Id of objects owning attributes to be returned rec: [in] record initialized with attribute values used as search parameters (initialized by user) nbRecords : [out] number of returned records recordList : [out] list of returned records flags : [in] option flags RETURN: IVAPI_OK if OK NOTES: recordList must be deallocated via IVFreeRecordList. If attListSize = 0, all the attributes will be retrieved IMPORT int WINAPI IVQueryListByExample (IVSession session, unsigned long classId, IVRecord rec, unsigned long* nbRecords, IVRecordList* recordList, unsigned int flags); It is the recordList variable I am having trouble with. Now, recordList is a pointer to type IvRecordList, which is itself defined as a void* in the header file like this: typedef void *IVRecordList; That makes recordList a type void**. I need to get the pointers out of the list so I can pass them back to the API when querying the contents of each record. I am getting nbRecords telling me that the function is returning the number of records I expect, but I'm not sure how to define IVRecordList when I pass it in so that I can extract the pointers properly afterwards. I've tried this, but the record pointers seem to have a value of None. def IVQueryListByExample(session,classId,rec,flags): nbRecords = ctypes.c_ulong() recordList = ctypes.c_void_p() status = ivapidll.IVQueryListByExample(session, classId, rec, ctypes.byref(nbRecords), ctypes.byref(recordList), flags) Does anyone have a good idea how I should define recordList so that I can retrieve the record pointers? -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Leo 4.4.1.1 final released
Edward K. Ream wrote: Leo 4.4.1.1 final September 3, 2006 Leo 4.4.1.1 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Doesn't run on my system (installed with the .exe): Python 2.4.2 Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\D:\SftwLib\Leo\src\leo.py leoID = CGr (in D:\SftwLib\Leo\config) reading settings in D:\SftwLib\Leo\config\leoSettings.leo Traceback (most recent call last): File D:\SftwLib\Leo\src\leo.py, line 320, in ? run() File D:\SftwLib\Leo\src\leo.py, line 95, in run g.app.config.readSettingsFiles(fileName,verbose) File D:\SftwLib\Leo\src\leoConfig.py, line 1341, in readSettingsFiles c = self.openSettingsFile(path) File D:\SftwLib\Leo\src\leoConfig.py, line 1311, in openSettingsFile c,frame = g.app.newLeoCommanderAndFrame(path,updateRecentFiles=False) File D:\SftwLib\Leo\src\leoApp.py, line 568, in newLeoCommanderAndFrame c.finishCreate() File D:\SftwLib\Leo\src\leoCommands.py, line 181, in finishCreate def finishCreate (self): # New in 4.4. File D:\SftwLib\Leo\src\leoCommands.py, line 187, in finishCreate c = self ; p = c.currentPosition() TypeError: currentPosition() takes exactly 2 arguments (1 given) --- ??? Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
Michele Simionato wrote: Ben Sizer wrote: I agree that the Python docs aren't quite as effective as reference material due to the lack of simple function and method lists though. http://docs.python.org/lib/modindex.html, pydoc and ipython are more than enough for me. modindex is comprehensive but too 'flat'. Sometimes you want to see all of one object's methods and properties listed together. I was unaware of pydoc until this thread; its existence seems to be buried, somewhat. Looking at pydoc.org (assuming that is a good example of it in use), it looks more like what the original poster and I might want, but sadly it's still very inconsistent, with many things undescribed. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Debugging Builds
Hi, Is there any documentation concerning the Python debugging builds beyond section 1.5 in the Python/C API reference manual and Misc/ SpecialBuilds.txt file in the source code? I'd like to know how people generally go about debugging memory leaks in C extensions. Thanks, David -- http://mail.python.org/mailman/listinfo/python-list
Re: xmingw and f2py
Flavio [EMAIL PROTECTED] wrote: I followed the steps you describe exactly and I am still gettin this error message when i try to compile. here is the command I give: f2py -c --compiler=/opt/xmingw/bin/i386-mingw32msvc-gcc n/i386-mingw32msvc-g77 -L /opt/xmingw/i386-mingw32msvc/lib/ -lpython2.4 -m flib flib.f and this is the error: copying /usr/lib/python2.4/site-packages/numpy-1.0b5-py2.4-linux-i686.egg/numpy/f2py/src/fortranobject.c - /tmp/tmpIkxhAr/src.linux-i686-2.4 copying /usr/lib/python2.4/site-packages/numpy-1.0b5-py2.4-linux-i686.egg/numpy/f2py/src/fortranobject.h - /tmp/tmpIkxhAr/src.linux-i686-2.4 adding '/tmp/tmpIkxhAr/src.linux-i686-2.4/flib-f2pywrappers.f' to sources. running build_ext error: don't know how to compile C/C++ code on platform 'posix' with '/opt/xmingw/bin/i386-mingw32msvc-gcc' compiler any further suggestions? That looks like a distutils error. We don't use distutils to build our stuff and I haven't really used it before so I can't help you there. You want to tell distutils that the compiler is just gcc somehow and takes the same options. Not sure how you do that. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Looking for a regexp generator based on a set of known string representative of a string set
Hello I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). Thanks for any idea -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Lex Hider wrote: Any tips on the code quality and use of python would be appreciated. I've got a feeling the overall structure is up the creek. [...] for opt, arg in opts: if opt in (-l, --latest): latest = int(arg) elif opt in (--notfound): ignoreNotFound = True #add notfound files to log Subtle bug here: (--notfound) is not a tuple, is just a string, so what you are actually testing is whether opt is a substring of --not-found. To actually build a 1-element tuple, you have to put a trailing comma: elif opt in (--notfound, ): but it would be clearer if you just use: elif opt == --notfound: -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
Ben Sizer wrote: Michele Simionato wrote: Ben Sizer wrote: I agree that the Python docs aren't quite as effective as reference material due to the lack of simple function and method lists though. http://docs.python.org/lib/modindex.html, pydoc and ipython are more than enough for me. modindex is comprehensive but too 'flat'. Sometimes you want to see all of one object's methods and properties listed together. I was unaware of pydoc until this thread; its existence seems to be buried, somewhat. Looking at pydoc.org (assuming that is a good example of it in use), it looks more like what the original poster and I might want, but sadly it's still very inconsistent, with many things undescribed. -- Ben Sizer Don't miss IPython, too. $ ipython Python 2.4.1 (#2, Aug 25 2005, 18:20:57) Type copyright, credits or license for more information. IPython 0.6.15 -- An enhanced Interactive Python. ? - Introduction to IPython's features. %magic - Information about IPython's 'magic' % functions. help- Python's own help system. object? - Details about 'object'. ?object also works, ?? prints more. In [1]: import email.FeedParser In [2]: email.FeedParser.FeedParser? Type: classobj String Form:email.FeedParser.FeedParser Namespace: Interactive File: /usr/lib/python2.4/email/FeedParser.py Docstring: A feed-style parser of email. Constructor information: Definition: email.FeedParser.FeedParser(self, _factory=class email.Message.Message at 0xb77f5ddc) Docstring: _factory is called with no arguments to create a new message obj In [3]: help(email.FeedParser.FeedParser) Help on class FeedParser in module email.FeedParser: class FeedParser | A feed-style parser of email. | | Methods defined here: | | __init__(self, _factory=class email.Message.Message) | _factory is called with no arguments to create a new message obj | | close(self) | Parse all remaining data and return the root message object. | | feed(self, data) | Push more data into the parser. In [4]: email.FeedParser.FeedParser?? Type: classobj String Form:email.FeedParser.FeedParser Namespace: Interactive File: /usr/lib/python2.4/email/FeedParser.py Source: class FeedParser: A feed-style parser of email. def __init__(self, _factory=Message.Message): _factory is called with no arguments to create a new message obj self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().next self._cur = None ... Unfortunately, the nice colors of IPython are lost in the post :-( Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Frank Millman wrote: Bruno Desthuilliers wrote: Frank Millman wrote: I have not gone to the trouble of raising NotImplementedError - the methods that the subclasses *must* override just have a 'pass' statement. I guess it would be more correct to raise the error, as it would give me a quicker indication of an error if I happened to omit one, but in practice I would find out pretty quickly anyway. Mmm... My own experience is that methods that *must* be redefined are better raising NotImplementedError. Makes things more obvious IMHO. Can't argue with that. I have just gone through my app and changed them all :-) Yup, if a thing can't go wrong, it won't regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
[EMAIL PROTECTED] wrote: Hello I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). Thanks for any idea def getRegex(list_of_strings): return .* ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
[EMAIL PROTECTED] wrote: I am looking for python code that takes as input a list of strings [...] and outputs the python regular expression (s1|s2|s3|s4|s5) for strings of s1 etc. Regex compilers are themselves quite good at optimising beyond this -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
[EMAIL PROTECTED]: I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). This may be a very simple starting point: import re strings = [foo, bar, $spam] strings2 = |.join(re.escape(s) for s in strings) strings2 'foo|bar|\\$spam' finds = re.compile(strings2) But I don't know how well this may work with many longer strings. If that's not enoug we can think about more complex solutions. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
Andy Dingley [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am looking for python code that takes as input a list of strings [...] and outputs the python regular expression (s1|s2|s3|s4|s5) for strings of s1 etc. Regex compilers are themselves quite good at optimising beyond this It turns out this problem is a little trickier, especially when one of your strings is a leading subset of another. For instance, let's say we are looking for comparison operators, one of , , =, =, =, or !=. Simply concatenating with intervening '|' characters gives this regexp: ||=|=|=|!= However, the leading '' and '' alternatives mask the later '=', '', and '=' alternatives, and so the regexp never matches the longer options (I was not able to find a greediness switch that would override this). So when searching a = b we get this: re.findall(||=|=|=|!=, a = b) ['', '='] By moving the longer option to the front of the regexp, the longer option is no longer masked by the shorter: re.findall(=|||=|=|!=, a = b) ['='] You also can't just concatenate input strings, since it is very likely they will contain one of the magic re symbols ()[]?*./\+, etc. So re.escape needs to be called to add the necessary '\'s. Here is an extract from pyparsing's oneOf function that does something similar, that handles the leading substring masking problem, and escapes the input strings, before concatenating them to a valid regexp. Of course, the simplest approach would be to just sort the symbols by descending length, but you may have some a priori knowledge that 'X' is a very common match, and want that option tested as early as possible. So this method only reorders strings if there is a masking problem. def createREfrom( symbols ): #symbols is a list of strings isequal = ( lambda a,b: a == b ) masks = ( lambda a,b: b.startswith(a) ) i = 0 while i len(symbols)-1: cur = symbols[i] for j,other in enumerate(symbols[i+1:]): if ( isequal(other, cur) ): del symbols[i+j+1] break elif ( masks(cur, other) ): del symbols[i+j+1] symbols.insert(i,other) cur = other break else: i += 1 return |.join( [ re.escape(sym) for sym in symbols] ) print createREfrom([ABC,ABCDEF,ABCGHI]) ABCDEF|ABCGHI|ABC print createREfrom( = = = !=.split()) \\=|\\\|\\|\|\\=|\\\|\\|\|\=|\!\= re.findall( createREfrom( = = = !=.split()), a = b) ['='] Note, this does not do any optimization, such as collapsing ABCDEF|ABCGHI to ABC(DEF|GHI). I think there are some recipes in the Python cookbook for such optimization. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
Ben Sizer wrote: [EMAIL PROTECTED] wrote: I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. I was going to recommend running something like epydoc [1] over the standard library, but this has its pitfalls. But in python, i find it kind of inconvient. My advice is to get used to it... the Python docs are not arranged in the hierarchical fashion because there isn't any real hierarchy to speak of. Python does not rely heavily on inheritance like Java does. Instead, it is used in just a few places, more like the C++ standard library than the Java library. Generating API documentation using epydoc really shows this aspect of the Python standard library: a huge list of names (sched, sets, sgmllib, shelve, shlex, shutil, site, stmpd, smtplib, sndheader, socket, sre, ...) which have little inherent organisation on their own. I agree that the Python docs aren't quite as effective as reference material due to the lack of simple function and method lists though. I don't know if there's a solution to that anywhere. Well, I used a very simple approach to get epydoc to format the standard library documentation: epydoc --parse-only --output=apidocs \ `find Lib -name test -prune -o -name *.py -print` Better usage of the find command could be made, and the resulting process occupied over 0.5GB before producing 581MB of API documents on disk. The resulting output reveals some major differences between some modules and in the quality of the documentation; for example, lots of empty docstrings cannot always be explained away by the --parse-only mode employed by epydoc in this case. Certainly, those with ideas of reorganising the standard library ought to consider the perspective of the questioner, along with the possibilities for generating documentation using the various tools available, in order to find inspiration in such matters. Paul [1] http://epydoc.sf.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with ctypes pointer return values
[EMAIL PROTECTED] wrote: Does anyone have a good idea how I should define recordList so that I can retrieve the record pointers? POINTER(POINTER(c_void)) ? Maybe I misunderstood tough... -- Lawrence - http://www.oluyede.org/blog Nothing is more dangerous than an idea if it's the only one you have - E. A. Chartier -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Add/Remove Programs Details
Tim Golden wrote: [Phoe6] and perhaps you need something like this (altho' obviously more sophisticated): code import wmi appname = Python 2.4.3 c = wmi.WMI () for product in c.Win32_Product (Caption=appname): print product.Caption # product.Uninstall () /code Thanks Tim for the reply. I started looking along the same lines. It looks like, I need to give the Product details exactly as it is registered(?). Trying out stuff like: import wmi appname = IsoBuster 1.9.1 c = wmi.WMI() for product in c.Win32_Product(Caption=appname): print product.Caption ret_val = product.Uninstall() print ret_val Did not work. There is script example given the M$ site: example_snippet strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ _ strComputer \root\cimv2) Set colSoftware = objWMIService.ExecQuery _ (Select * from Win32_Product _ Where Name = 'Personnel database') For Each objSoftware in colSoftware objSoftware.Uninstall() Next /example_snippet I guess to convert the same to python. I shall try more and keep posted. Thanks, Senthil -- http://mail.python.org/mailman/listinfo/python-list
Re: threading support in python
Where is Guido ? would be great to hear his opinion on GIL/ GC issues in future versionsofPython. regards, KM On 7 Sep 2006 08:02:57 GMT, Antoon Pardon [EMAIL PROTECTED] wrote: On 2006-09-06, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Paul Rubin wrote: [EMAIL PROTECTED] [EMAIL PROTECTED] writes: (1) I think is here to stay, if you're going to tell programmers that their destructors can't make program-visible changes (e.g. closing the database connection when a dbconn is destroyed), that's a _huge_ change from current practice that needs serious debate. We had that debate already (PEP 343).Yes, there is some sloppy current practice by CPython users that relies on the GC to close the db conn. This point is unrelated to with or ref-counting.Even the standard library will close file objects when they are GC'd.This is not totally true. My experience is that if you use the tarfile module any tarfile that was opened for appending orwriting risks being corrupted if it isn't closed explicedly.--Antoon Pardon-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Get CPU usage of a single process in Windows
Hi, This should be possible as Taskmanager tracks CPU usage for every process... Anyone know how this can be done? regards -- http://mail.python.org/mailman/listinfo/python-list
Re: change property after inheritance
Maric Michaud wrote: Le jeudi 07 septembre 2006 15:33, Steven Bethard a écrit : Well, lambda's not going away[1], Sure, they won't. but there's no *need* for lambda here. It could be written as:: Le jeudi 07 septembre 2006 17:16, George Sakkis a écrit : Sure, it *could*; whether it *should* is a different issue. I can't imagine a case for absolute *need* of lambda, but there are several cases where it is probably the best way, such as the one of this thread. I have no preferences here, I used lambdas because it's more compact but they have also their drawback, when the function get a little more complex the code is quickly confusing. The main advantage of the lambdas in this case is to not pollute the class namespace. Le jeudi 07 septembre 2006 23:48, Steven Bethard a écrit : Try using one of the following recipies: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408713 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418 The code i wrote was to demonstrate late binding is usually not needed (and it's not the semantic of properties so it's a bit like make Java in Python). If you're really this uncomfortable with writing your own descriptors, sure, you don't have to. But descriptors are an integral part of Python -- new-style classes wouldn't have methods without them, nor could classmethod or staticmethod have been defined. So defining a new descriptor is far from un-Pythonic. If you really want late binding, the first recipe may be a solution, but it should be both simpler and should not introduce a new semantic (the functions passed as strings is disappointing). If you want to use the functions instead of their names, it's as simple as changing the __init__ to: def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.getname = fget.__name__ self.setname = fset.__name__ self.delname = fdel.__name__ self.__doc__ = doc Then you can use the same signature as property. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
[EMAIL PROTECTED] schrieb: Hello I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). For matching the exact set, of course a concatenation can be used. However, this is of limited use, because then simple string find will suffice. In general, this can't be done. It might be possible that the underlying structure of the language isn't regular at all - for example, the simple language of palindromes isn't. And even if it was - the search space is just to large to explore. You could generate a bazillion matching expressions, but .* will always match - so how do you prevent the generator from converging towards that? If all you have are those strings, you are better off trying to infer some structure yourself. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Add/Remove Programs Details
Phoe6 wrote: Tim Golden wrote: [Phoe6] and perhaps you need something like this (altho' obviously more sophisticated): code import wmi appname = Python 2.4.3 c = wmi.WMI () for product in c.Win32_Product (Caption=appname): print product.Caption # product.Uninstall () /code Thanks Tim for the reply. I started looking along the same lines. It looks like, I need to give the Product details exactly as it is registered(?). Trying out stuff like: [... snip ...] did not work There is script example given the M$ site: example_snippet strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ _ strComputer \root\cimv2) That's exactly equivalent to: c = wmi.WMI () Set colSoftware = objWMIService.ExecQuery _ (Select * from Win32_Product _ Where Name = 'Personnel database') For Each objSoftware in colSoftware objSoftware.Uninstall() Next That's the same as: for product in c.Win32_Product (Name=Personnel database): product.Uninstall () (all the module is doing is wrapping the MS code a bit more pythonically). TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Get CPU usage of a single process in Windows
Tor Erik wrote: Hi, This should be possible as Taskmanager tracks CPU usage for every process... Anyone know how this can be done? WMI can probably do the trick. If you can find something on Google for wmi cpu usage (or something similar) then translation to Python's usually quite easy. I'm fairly sure I've got an example somewhere, but I can't lay my hands on it at the mo. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Add NTLM proxy authentication to urllib2
looping [EMAIL PROTECTED] writes: I've done some tests with urllib2 and pywin32 and managed to partialy implement the NTLM authentication, but it look like you need a persistent connection (http 1.1 or 'Keep-Alive') to complete the authentication. Unfortunatly, urllib2 use a new connection for each request and changing this behavior look difficult. So I will probably write my own library. Maybe there is something to do with the urlgrabber module ? urlgrabber does indeed claim to do persistent connections in a way at least somewhat integrated with urllib2. I think I must have imagined there being an NTLM impl. for urllib2, because ISTR you're right about needing a persistent connection. I don't think it's too hard to fix urllib2 to reuse connections, but I forget exactly why it doesn't do it already... John -- http://mail.python.org/mailman/listinfo/python-list
mysqldb + multi-threading
Hi, I am writing a transaction server (socket-based) under windows. I use mysqldb to log info into MySQL. It is all working and I need now to decide whether to use forks (CreateProcess I guess) or threads. I saw in another thread that some db engines did have issues with being called from threads. My gut feeling is to use threads (note: each transaction is finite, so the process/thread die fairly quickly). Any insight ? hg -- http://mail.python.org/mailman/listinfo/python-list
Re: should urlparse return user and pass in separate components?
metaperl [EMAIL PROTECTED] writes: The urlparse with Python 2.4.3 includes the user and pass in the site aspect of its parse: scheme, site, path, parms, query, fid = urlparse.urlparse(http://bill:[EMAIL PROTECTED]/lib/module-urlparse.html) site 'bill:[EMAIL PROTECTED]' I personally would prefer that it be broken down a bit further. What are existing opinions on this? Module urlparse should be deprecated in Python 2.6, to be replaced with a new module (or modules) that implements the relevant parts of RFC 3986 and 3987 (read the python-dev archives for discussion and several people's first cuts at implementation). Splitting userinfo (the bit before the '@' in user:[EMAIL PROTECTED]) should be a separate function. Mostly because RFC 3986 talks a lot about 5-tuples into which ANY URL can be split, and that splitting process doesn't involve splitting out userinfo. So it makes sense to have one function do the splitting into RFC 3986 5-tuples, and another split out the userinfo. Also, though, the userinfo syntax is deprecated, because people use it for semantic spoofing attacks: people don't understand (or don't notice) that http://microsoft.comrhubarb=custard[EMAIL PROTECTED]/more/stuff.htm is not a microsoft.com URL. Note that userinfo has always been illegal in HTTP URLs, and is no longer supported by newer browsers. So relegating it to a separate function is a good thing, IMO. John -- http://mail.python.org/mailman/listinfo/python-list
cx_Oracle question
I'm having trouble getting started using Python's cx_Oracle binding to Oracle XE. In forthcoming programs, I need to set variables within sql statements based on values read in from flat files. But I don't seem to be able to get even the following stripped-down test program to work: import cx_Oracle connection = cx_Oracle.connect(username, password) cursor = connection.cursor() arg_1 = 2 #later, arg_1, arg_2, etc. will be read in files cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,arg_1) for row in cursor.fetchone(): print row cursor.close() connection.close() The program above produces the following error message: C:\pythonappspython oracle_test.py Traceback (most recent call last): File oracle_test.py, line 7, in ? cursor.execute('select mean_eng_txt from mean where mean_id=:arg_1',arg_1) TypeError: expecting a dictionary, sequence or keyword args What do I need to do to get this sort of program working? TIA, Richard Schulman For email reply, remove the xx characters -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle question
Richard Schulman schrieb: cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,arg_1) cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,{arg_1:arg_1}) Traceback (most recent call last): File oracle_test.py, line 7, in ? cursor.execute('select mean_eng_txt from mean where mean_id=:arg_1',arg_1) TypeError: expecting a dictionary, sequence or keyword args -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle question
Richard Schulman schrieb: I'm having trouble getting started using Python's cx_Oracle binding to Oracle XE. In forthcoming programs, I need to set variables within sql statements based on values read in from flat files. But I don't seem to be able to get even the following stripped-down test program to work: import cx_Oracle connection = cx_Oracle.connect(username, password) cursor = connection.cursor() arg_1 = 2 #later, arg_1, arg_2, etc. will be read in files cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,arg_1) for row in cursor.fetchone(): print row cursor.close() connection.close() The program above produces the following error message: C:\pythonappspython oracle_test.py Traceback (most recent call last): File oracle_test.py, line 7, in ? cursor.execute('select mean_eng_txt from mean where mean_id=:arg_1',arg_1) TypeError: expecting a dictionary, sequence or keyword args What do I need to do to get this sort of program working? Do what it tells you to do: use a dictionary as parameters or keyword-args. Not sure what they mean by a sequence though. So it should work like this: cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,{arg_1=arg_1}) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle question
cursor.execute(select mean_eng_txt from mean where mean_id=:arg_1,{arg_1=arg_1}) Needs quotes of course. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
[EMAIL PROTECTED] writes: Hi there, I'm new to python and I'm from the java world. Though I love to learn python, I'm not very comfortable with the python documentation. Because when i read jdk doc, i can see the class hierachy, class member, class methods etc in html docs. It's very easy for me to understand the Java language. But in python, i find it kind of inconvient. Are you talking about the Python standard library (the stdlib), or the set of all Python modules in the world? The stdlib docs have a pretty rigid format (though a few modules do vary -- and I don't in principle begrudge authors some wiggle room, to allow them to say what they want to say more clearly). It's just a different format to Java. That's not *always* a capital offence ;-) Outside any one project, in general, it has always seemed 10x more important to me that the docs are set out in a way that suits that project than it is to conform to some global standard. In fact, some peoples' complacent assertions that Python docs are inferior for this reason really winds me up ;-) Mind you, the last person who said that to me was also Chinese, and I guess I can understand that, if Python documentation were written in Chinese, the relative benefits of flexibility and consistency in doc structure would be very different for me! In a few years it will be us English monoglots who will have to learn Chinese to read *your* docs :-) I have to say that, very recently, I've found making use of the various API doc tools in Python of pretty painful, though -- but that pain is precisely because of my decision to do exactly what's right for my project, seeing little value -- other than implementation convenience -- in following some global standard. If I just wanted standard input and output formats, it is just as easy as in the Java world -- for example, epydoc supports JavaDoc syntax (amongst other formats), and PythonDoc follows JavaDoc's syntax fairly closely. (Personally, I ended up using epydoc with my own patched HTML output module, to get simpler and fewer pages out of it. PythonDoc is nice for being far simpler, but I hate the XML-ish markup syntax.) The Perl story used to be that the POD format was great because it made people actually sit down and write docs. I can't say I've noticed it stopping Python module authors writing docs, though: docstrings and plain text or HTML work pretty well as a never mind the format, sit down and write the docs format. foolish-consistency-and-all-that-ly y'rs John -- http://mail.python.org/mailman/listinfo/python-list
super and __init__
Am I the only one that finds the super function to be confusing? I have a base class that inherits from object. In other words new style class: class foo (object): def __init__ (self, arg_A, arg_B): self.a = arg_A self.b = arg_B # Do I need to call __init__ on object base class? class bar (foo): def __init__ (self, arg_Z): self.z = Z + arg_Z foo.__init__(self, 'A', arg_Z)# this is the old-style class way def __str__ (self): return self.a + self.b + self.z I don't know how people will use the bar class in terms of inheritance. I don't want to lock anyone out of multiple inheritance, but I'd like to have to worry about it as little as possible. From what I've read using the old style of calling the base class __init__ can cause conflicts if the class is later part of a diamond relationship. I just want bar to initialize the properties that it add to the base class and to have it tell the base class to initialize the inherited properties. The old way seemed clear enough; although, a bit ugly. The super function seems like it would make this more clear, but it doesn't (to me). Is there a just do this answer for 90% of the use cases? Yours, Noah -- http://mail.python.org/mailman/listinfo/python-list
Best Python Books and Sites
I have been enjoying the discussion here for a while, and would like to ask for some help. I recently launched a question answer site that connects people with problems to those with solutions. We let people with problems pay solution providers $0.25 for problems in over 100 categories. As part of our service we let people review past problems and also provide resources for their own research. Can anyone tell me (in their opinion)? What are the best three sites for python information? What are the best three python books they own? I would like to compile a list and include it on my site. Regards. Vibi Varghese www.problima.com A place to bring problems ..and to get paid to solve them -- http://mail.python.org/mailman/listinfo/python-list
Re: Linear regression in 3 dimensions
Bernhard, Levenberg-Marquardt is a good solution when you want to solve a general non-linear least-squares problem. As Robert said, the OPs problem is linear and Robert's solution exploits that. Using LM here is unnecessary and I suspect a fair bit less efficient (i.e. slower). - Andrew [EMAIL PROTECTED] wrote: Hi Robert, I'm using the scipy package for such problems. In the submodule scipy.optimize there is an implmentation of a least-square fitting algorithm (Levenberg-Marquardt) called leastsq. You have to define a function that computes the residuals between your model and the data points: import scipy.optimize def model(parameter, x, y): a, b, c = parameter return a*x + b*y + c def residual(parameter, data, x, y): res = [] for _x in x: for _y in y: res.append(data-model(parameter,x,y) return res params0 = [1., 1.,1.] result = scipy.optimize.leastsq(resdiual, params0, (data,x,y)) fittedParams = result[0] If you haven't used numeric, numpy or scipy before, you should take a look at an introduction. It uses some nice extended array objects, where you can use some neat index tricks and compute values of array items without looping through it. Cheers! Bernhard Robert Kern wrote: [EMAIL PROTECTED] wrote: Hi all, I am seeking a module that will do the equivalent of linear regression in 3D to yield a best fit a plane through a set of points (X1, Y1, Z1), (X1, Y1, Z1),... (Xn, Yn, Zn). The resulting equation to be of the form: Z = aX + bY + c The function I need would take the set of points and return a,c c Any pointers to existing code / modules would be very helpful. Well, that's a very unspecified problem. You haven't defined best. But if we make the assumption that you want to minimize the squared error in Z, that is minimize Sum((Z[i] - (a*X[i] + b*Y[i] + c)) ** 2) then this is a standard linear algebra problem. In [1]: import numpy as np In [2]: a = 1.0 In [3]: b = 2.0 In [4]: c = 3.0 In [5]: rs = np.random.RandomState(1234567890) # Specify a seed for repeatability In [6]: x = rs.uniform(size=100) In [7]: y = rs.uniform(size=100) In [8]: e = rs.standard_normal(size=100) In [9]: z = a*x + b*y + c + e In [10]: A = np.column_stack([x, y, np.ones_like(x)]) In [11]: np.linalg.lstsq? Type: function Base Class: type 'function' String Form:function lstsq at 0x6df070 Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-1.0b2.dev3002-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py Definition: np.linalg.lstsq(a, b, rcond=1e-10) Docstring: returns x,resids,rank,s where x minimizes 2-norm(|b - Ax|) resids is the sum square residuals rank is the rank of A s is the rank of the singular values of A in descending order If b is a matrix then x is also a matrix with corresponding columns. If the rank of A is less than the number of columns of A or greater than the number of rows, then residuals will be returned as an empty array otherwise resids = sum((b-dot(A,x)**2). Singular values less than s[0]*rcond are treated as zero. In [12]: abc, residuals, rank, s = np.linalg.lstsq(A, z) In [13]: abc Out[13]: array([ 0.93104714, 1.96780364, 3.15185125]) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter text Key event
That makes sense, but it's not working. John McMonagle wrote: On Wed, 2006-09-06 at 17:54 -0700, Jay wrote: I'm having trouble with using the Key event with the Text object. When I use them together (which is a logical combination), I use this code: textbox = Text(root, wrap=word, height=15, width=50) textbox.bind(Key, resolveGlyphs) def resolveGlyphs(event): textBuf = textbox.get(1.0, END) print(textBuf) What it prints out for me is everything except for the last character -- the one that triggered the event. How can I get the entire contents? bind the textbox to the KeyRelease event because by then it has been drawn on the Text widget. The Key event is equivalent to the KeyPress event Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Python Books and Sites
VV wrote: I recently launched a question answer site that connects people with problems to those with solutions. We let people with problems pay solution providers $0.25 for problems in over 100 categories. ... What are the best three sites for python information? What are the best three python books they own? Sounds great! Send me $1.50 and I'll send you my six answers. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter text Key event
Nevermind. It works. Sorry. I got my files mixed up! :-) John McMonagle wrote: On Wed, 2006-09-06 at 17:54 -0700, Jay wrote: I'm having trouble with using the Key event with the Text object. When I use them together (which is a logical combination), I use this code: textbox = Text(root, wrap=word, height=15, width=50) textbox.bind(Key, resolveGlyphs) def resolveGlyphs(event): textBuf = textbox.get(1.0, END) print(textBuf) What it prints out for me is everything except for the last character -- the one that triggered the event. How can I get the entire contents? bind the textbox to the KeyRelease event because by then it has been drawn on the Text widget. The Key event is equivalent to the KeyPress event Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- http://mail.python.org/mailman/listinfo/python-list