Re: Headers for Form Submision, and also HTTPrequests
[EMAIL PROTECTED] wrote: > action="http://login.myspace.com/index.cfm?fuseaction=login.process"; > method="post" name="theForm" id="theForm"> > > > What happens when you add the form param "submit" with value "Login" to the request you're doing? Perhaps the page needs this third parameter --Irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Error type for shelve.open()
I reported the bug to python.org and apparently it has already been fixed in the latest SVN build :). [EMAIL PROTECTED] wrote: > Yes, the problem was that I hadn't imported anydbm.error... it's > working now. > > As for the AttributeError at the end, I talked to someone else, and he > looked at the source and said it was a bug in shelve. I think I will > report it to python.org. > > Anyway, thanks :). > Simon Forman wrote: > > [EMAIL PROTECTED] wrote: > > > I tried what you said and it looked like maybe AttributeError, but that > > > didn't work either. > > > > > > This code snippet: > > > > > > import shelve > > > from traceback import format_exc > > > > > > try: > > >db = shelve.open("meh", "r") > > > except: > > >print format_exc() > > > > > > Gave me this output: > > > Traceback (most recent call last): > > > File "test.py", line 5, in ? > > > db = shelve.open("meh", "r") > > > File "/usr/lib/python2.4/shelve.py", line 231, in open > > > return DbfilenameShelf(filename, flag, protocol, writeback, binary) > > > File "/usr/lib/python2.4/shelve.py", line 212, in __init__ > > > Shelf.__init__(self, anydbm.open(filename, flag), protocol, > > > writeback, binary) > > > File "/usr/lib/python2.4/anydbm.py", line 77, in open > > > raise error, "need 'c' or 'n' flag to open new db" > > > error: need 'c' or 'n' flag to open new db > > > > > > Exception exceptions.AttributeError: "DbfilenameShelf instance has no > > > attribute 'writeback'" in ignored > > > > > > Do you know what the error is? > > > > No. If you tried catching AttributeError and it didn't work then I'd > > guess that the AttributeError is a secondary result of the initial > > error. > > > > This part of the traceback, > > > > > File "/usr/lib/python2.4/anydbm.py", line 77, in open > > > raise error, "need 'c' or 'n' flag to open new db" > > > error: need 'c' or 'n' flag to open new db > > > > indicates that some sort of custom error, probably defined in the > > anydbm.py module. > > > > Catching the execption and binding it to a var, > > > > >>> try: > > ... db = shelve.open("meh", "r") > > ... except Exception, err: > > ... E = err > > ... > > Exception exceptions.AttributeError: "DbfilenameShelf instance has no > > attribute 'writeback'" in ignored > > >>> E > > > > > > > > > > So: > > >>> from anydbm import error > > >>> try: > > ... db = shelve.open("meh", "r") > > ... except error: > > ... print 'Aha! got it!' > > ... > > Aha! got it! > > Exception exceptions.AttributeError: "DbfilenameShelf instance has no > > attribute 'writeback'" in ignored > > > > > > Well, that catches the error, but I don't know what's going on with the > > additional AttributeError or what to do about it. > > > > Peace, > > ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
I <[EMAIL PROTECTED]> wrote: > Incidentally, I'm not saying that such a feature would be a good idea. > It generally isn't provided in languages specifically because it gets to > be a big pain to maintain all of the type specifications for this kind > of stuff. There are other good reasons, too, as it turns out. I don't want to overstate the "possible" until it starts to sound like "easy, even if it's a pain". This kind of stuff is rarely done in mainstream programming languages because it has serious negative consequences. For example, I wrote that example using variables of type int. If we were to suppose that we were actually working with variables of type Person, then things get a little more complicated. We would need a few (infinite classes of) derived subtypes of Person that further constrain the possible values for state. For example, we'd need types like: Person{age:{18..29}} But this starts to look bad, because we used to have this nice property called encapsulation. To work around that, we'd need to make one of a few choices: (a) give up encapsulation, which isn't too happy; (b) rely on type inference for this kind of stuff, and consider it okay if the type inference system breaks encapsulation; or (c) invent some kind of generic constraint language so that constraints like this could be expressed without exposing field names. Choice (b) is incomplete, as there will often be times when I need to ascribe a type to a parameter or some such thing, and the lack of ability to express the complete type system will be rather limiting. Choice (c), though, looks a little daunting. So I'll stop there. The point is that while it is emphatically true that this kind of stuff is possible, it is also very hard in Java. Partly, that's because Java is an imperative language, but it's also because there are fundamental design trade-offs involved between verbosity, complexity, expressive power, locality of knowledge, etc. that are bound to be there in all programming languages, and which make it harder to take one design principle to its extreme and produce a usable language as a result. I don't know that it's impossible for this sort of thing to be done in a usable Java-like language, but in any case, the way to accomplish it is not obvious. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation -- http://mail.python.org/mailman/listinfo/python-list
Re: type comparison and wxpython
borris wrote: > ive been trying to do a test for type with wxpython objects > > like > > passing in a wx.TextCtrl into > > def XXX(obj) > if type(obj) is type(self.Button) > > I have to make an object self.Button to get its type. > as I tried is type("wx.Button") which didnt work. type("wx.Button") would return , did you mean type(wx.Button)? That still wouldn't be what you wanted.. For "classic" classes type() returns ; for new style classes it returns Assuming that wx.Button is the class of your Button objects then what you want is the isinstance() function. if isinstance(obj, wx.Button): >>> help(isinstance) Help on built-in function isinstance in module __builtin__: isinstance(...) isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). > > trouble is the button must have a parent, which appears on the frame (Ill > try to get rid of it) > > but I should be able to use text to set the type > Ive tried "wx._controls.TextCtrl" which didnt work huh? > > any hints welcome > > btw Im newbie to python, coming from Java and I reckon its cool and sleek > and coming from java Swing, I reckon wxPython is probably better -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting 64bit vs. 32bit Linux
In article <[EMAIL PROTECTED]>, dwelch91 <[EMAIL PROTECTED]> wrote: >I need to detect whether the operating system I am running on (not the >Python version) is 64bit or 32bit. One requirement is that I need to >include support for non-Intel/AMD architectures. The standard C way would be to check sizeof(void *). -- http://mail.python.org/mailman/listinfo/python-list
Re: Error type for shelve.open()
[EMAIL PROTECTED] wrote: > I reported the bug to python.org and apparently it has already been > fixed in the latest SVN build :). Awesome! Open Source at work! :D -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith wrote: > > But this starts to look bad, because we used to have this nice property > called encapsulation. To work around that, we'd need to make one of a > few choices: (a) give up encapsulation, which isn't too happy; (b) rely > on type inference for this kind of stuff, and consider it okay if the > type inference system breaks encapsulation; or (c) invent some kind of > generic constraint language so that constraints like this could be > expressed without exposing field names. Choice (b) is incomplete, as > there will often be times when I need to ascribe a type to a parameter > or some such thing, and the lack of ability to express the complete type > system will be rather limiting. Choice (c), though, looks a little > daunting. Damn the torpedoes, give me choice c! I've been saying for a few years now that encapsulation is only a hack to get around the lack of a decent declarative constraint language. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
This is probably my last response to you in this thread. My impression is that for the moment nothing productive can come from this exchange. I have the feeling that you are not reading so much with the interntion of understanding what I want to say, but with the intention of confirming your suspition that I just don't have a clue. It seems this is turing into some competition where I have somehow to defend my understanding of python an you trying to show how little I really understand. Since I don't feel the need to prove myself here, I will simply bow out. On 2006-07-09, Piet van Oostrum <[EMAIL PROTECTED]> wrote: >> Antoon Pardon <[EMAIL PROTECTED]> (AP) wrote: > >>AP> When someone gets confused over the difference between rebinding or >>AP> mutating a variable on an intermediate scope, the explanation he >>AP> mostly seems to get boils down to: one is rebinding, the other is >>AP> mutation, this is a fundametal difference in python. > >>AP> My impression is that they seem to say that the fundamental difference >>AP> between mutation and rebinding implies the specific behaviour python >>AP> has now. IMO this explanation is incomplete. The python developers >>AP> could have chosen that a line like 'c.a = ...' would have resulted >>AP> in c being included in the local scope. Then rebinding and mutation >>AP> would still be fundamentally different from each other but the specific >>AP> confusion over why 'k[0] = ...' worked as expeced but 'k = ...' didn't, >>AP> will disappear. > > That seems nonsense to me. If they had chosen that 'c.a = ...' would imply > that c would become a local variable, what would the value of c have to be > then, if there was no prior direct assignment to c? I'm sorry to see you missed it, but since I had answered this already in this thread I saw at the moment no need to repeat it: There would be no value for c, the line would raise an UnboundLocalError. I also don't understand why you take the trouble of attacking this possibility. It's wasn't presented as a suggestion for changing python. It was used as an illustration of why I think some explanation needs to be worked out more. So even if this turns out to be the worst possible that could ever happen to python, unless you think people needing the original explanation will grasp the implication of this possibility immediately, the point I wanted to illustrate seems to stand. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith schrieb: > For example, I wrote that example using variables of type int. If we > were to suppose that we were actually working with variables of type > Person, then things get a little more complicated. We would need a few > (infinite classes of) derived subtypes of Person that further constrain > the possible values for state. For example, we'd need types like: > > Person{age:{18..29}} > > But this starts to look bad, because we used to have this nice > property called encapsulation. To work around that, we'd need to > make one of a few choices: [...] (c) invent some kind of generic > constraint language so that constraints like this could be expressed > without exposing field names. [...] Choice (c), though, looks a > little daunting. That's not too difficult. Start with boolean expressions. If you need to check everything statically, add enough constraints that they become decidable. For the type language, you also need to add primitives for type checking, and if the language is stateful, you'll also want primitives for accessing earlier states (most notably at function entry). > So I'll stop there. The point is that while it is emphatically true > that this kind of stuff is possible, it is also very hard in Java. No surprise: It's always very hard to retrofit an inference system to a language that wasn't designed for it. This doesn't mean it can't be done. Adding genericity to Java was a pretty amazing feat. (But I won't hold my breath for a constraint-style type system in Java anyway... *gg*) Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Marshall <[EMAIL PROTECTED]> wrote: > Chris Smith wrote: > > > > But this starts to look bad, because we used to have this nice property > > called encapsulation. To work around that, we'd need to make one of a > > few choices: (a) give up encapsulation, which isn't too happy; (b) rely > > on type inference for this kind of stuff, and consider it okay if the > > type inference system breaks encapsulation; or (c) invent some kind of > > generic constraint language so that constraints like this could be > > expressed without exposing field names. Choice (b) is incomplete, as > > there will often be times when I need to ascribe a type to a parameter > > or some such thing, and the lack of ability to express the complete type > > system will be rather limiting. Choice (c), though, looks a little > > daunting. > > Damn the torpedoes, give me choice c! You and I both need to figure out when to go to sleep. :) Work's gonna suck tomorrow. > I've been saying for a few years now that encapsulation is only > a hack to get around the lack of a decent declarative constraint > language. Choice (c) was meant to preserve encapsulation, actually. I think there's something fundamentally important about information hiding that can't be given up. Hypothetically, say I'm writing an accounting package and I've decided to encapsulate details of the tax code into one module of the application. Now, it may be that the compiler can perform sufficient type inference on my program to know that it's impossible for my taxes to be greater than 75% of my annual income. So if my income is stored in a variable of type decimal{0..10}, then the return type of getTotalTax may be of type decimal{0..75000}. Type inference could do that. But the point here is that I don't WANT the compiler to be able to infer that, because it's a transient consequence of this year's tax code. I want the compiler to make sure my code works no matter what the tax code is. The last thing I need to to go fixing a bunch of bugs during the time between the release of next year's tax code and the released deadline for my tax software. At the same time, though, maybe I do want the compiler to infer that tax cannot be negative (or maybe it can; I'm not an accountant; I know my tax has never been negative), and that it can't be a complex number (I'm pretty sure about that one). I call that encapsulation, and I don't think that it's necessary for lack of anything; but rather because that's how the problem breaks down. Note that even without encapsulation, the kind of typing information we're looking at can be very non-trivial in an imperative language. For example, I may need to express a method signature that is kind of like this: 1. The first parameter is an int, which is either between 4 and 8, or between 11 and 17. 2. The second parameter is a pointer to an object, whose 'foo' field is an int between 0 and 5, and whose 'bar' field is a pointer to another abject with three fields 'a', 'b', and 'c', each of which has the full range of an unconstrained IEEE double precision floating point number. 3. After the method returns, it will be known that if this object previously had its 'baz' field in the range m .. n, it is now in the range (m - 5) .. (n + 1). 4. After the method returns, it will be known that the object reached by following the 'bar' field of the second parameter will be modified so that the first two of its floating point numbers are guaranteed to be of the opposite sign as they were before, and that if they were infinity, they are now finite. 5. After the method returns, the object referred to by the global variable 'zab' has 0 as the value of its 'c' field. Just expressing all of that in a method signature looks interesting enough. If we start adding abstraction to the type constraints on objects to support encapsulation (as I think you'd have to do), then things get even more interesting. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenate Numeric
Robert Kern wrote: > Sheldon wrote: > > Hi, > > > > I am trying to build a large array using concatenate function in > > python. > > So as I loop over the number of arrays, of which there are 12 (4 down > > and 3 across), I create 3 long arrays by concatenating them at the > > bottom and then concatenating them side by side: > > [snip] > > > print 'Max lat', max(max(ppslat_all)), '\t','Min lat', > > min(min(ppslat_all)) > > print 'Max lon', max(max(ppslon_all)), '\t','Min lon', > > min(min(ppslon_all)) > > > > * > > Now this works, the array size is correct but the longitude values > > given for max and min are wrong. What is even stranger to me is that > > when I write the array in binary format to a file and read it with > > Matlab, the max and min are correct but when I read it back with python > > the max and min are again incorrect for only the longitude data. I > > saved the max and min for the longitude for each array and then check > > it in the python program and they are correct at the end but the > > max(max(ppslon)) values is incorrect. Does anyone knows why this is > > so? > > If I was doing something wrong then Matlab would not have returned > > correct values. > > Don't use min() and max() on multidimensional arrays. They won't give sensible > answers. > > > In [11]: a = RA.random([3,5]) > > In [12]: a > Out[12]: > array([[ 0.01721657, 0.64291363, 0.33210659, 0.89887972, 0.24437849], > [ 0.88205348, 0.00839329, 0.35999039, 0.9966411 , 0.54957126], > [ 0.59983864, 0.18983323, 0.13727718, 0.8987289 , 0.05425076]]) > > In [13]: min(a) > Out[13]: array([ 0.59983864, 0.18983323, 0.13727718, 0.8987289 , > 0.05425076]) > > > The builtin min() and max() compare the values in the sequence. In this case, > those values are the rows of the arrays. Numeric uses rich comparisons, so the > result of a comparison is a boolean array. Numeric also has the convention > that > if any of the elements of an array are considered to be True, then the whole > array is. > > > In [16]: a[1] < a[2] > Out[16]: array([0, 1, 0, 0, 0]) > > In [17]: bool(_) > Out[17]: True > > In [18]: a[2] < a[1] > Out[18]: array([1, 0, 1, 1, 1]) > > In [19]: bool(_) > Out[19]: True > > > This makes min(a) incorrect when len(a.shape) > 1. Instead, use the minimum > and > maximum ufuncs provided with Numeric: > > > In [21]: N.minimum.reduce(a.flat) > Out[21]: 0.0083932917161983426 > > In [22]: N.maximum.reduce(a.flat) > Out[22]: 0.99664110397663608 > > > -- > 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 Hi Robert, Thanks again for showing me this. I have been trying to read up on reduce() as I have never used it before. I would like to know what it does. So far my search has found nothing that I can grasp. The reference library notes are estoteric at best. Can you enlighten me on this matter?' /Sheldon -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith schrieb: > I think > there's something fundamentally important about information hiding that > can't be given up. Indeed. Without information hiding, with N entities, you have O(N^2) possible interactions between them. This quickly outgrows the human capacity for managing the interactions. With information hiding, you can set up a layered approach, and the interactions are usually down to something between O(log N) and O(N log N). Now that's far more manageable. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith <[EMAIL PROTECTED]> writes: > But the point here is that I don't WANT the compiler to be able to infer > that, because it's a transient consequence of this year's tax code. I > want the compiler to make sure my code works no matter what the tax code > is. The last thing I need to to go fixing a bunch of bugs during the > time between the release of next year's tax code and the released > deadline for my tax software. At the same time, though, maybe I do want > the compiler to infer that tax cannot be negative (or maybe it can; I'm > not an accountant; I know my tax has never been negative), Yes, it can. For example in Spain. Theorically, in France IVA can also come out negative, and you have the right to ask for reimbursement, but I've never seen a check from French Tax Administration... > and that it > can't be a complex number (I'm pretty sure about that one). I wouldn't bet on it. For example, French taxes consider "advantages in nature", so your income has at least two dimensions, Euros and and "advantages in nature". Thanksfully, these advantages are converted into Euros, but you could consider it a product by (complex 0 (- some-factor))... > I call that > encapsulation, and I don't think that it's necessary for lack of > anything; but rather because that's how the problem breaks down. -- __Pascal Bourguignon__ http://www.informatimago.com/ You never feed me. Perhaps I'll sleep on your face. That will sure show you. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Alex Martelli wrote: > Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: >... > >>>This would allow things like: >>>key = '',join( list(word.lower().strip()).sort() ) >> >>key = ''.join(list(sorted(word.lower().strip())) > > > No need to make yet another list here (also, I think each of you omitted > a needed closed-paren!-) Possibly > -- you could just use: > > key = ''.join(sorted(word.lower().strip())) Yes, of course - too quick answer, half-backed answer... (snip) -- 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: concatenate Numeric
Sheldon wrote: > Thanks again for showing me this. I have been trying to read up on > reduce() as I have never used it before. I would like to know what it > does. So far my search has found nothing that I can grasp. The > reference library notes are estoteric at best. > Can you enlighten me on this matter?' The .reduce() method on ufuncs works pretty much like the reduce() builtin function. It applies the binary ufunc along the given axis of the array (the first one by default) cumulatively. a = [3, 2, 1, 0] minimum.reduce(a) == minimum(minimum(minimum(a[0], a[1]), a[2]), a[3]) I will note, in the form of enticement to get you to try the currently active array package instead of Numeric, that in numpy, arrays have methods to do minimums and maximum rather more conveniently. >>> import numpy as N >>> a = N.rand(3, 5) >>> a array([[ 0.49892358, 0.11931907, 0.37146848, 0.07494308, 0.91973863], [ 0.92049698, 0.35016683, 0.01711571, 0.59542456, 0.49897077], [ 0.57449315, 0.99592033, 0.20549262, 0.25135288, 0.04111402]]) >>> a.min() 0.017115711878847639 >>> a.min(axis=0) array([ 0.49892358, 0.11931907, 0.01711571, 0.07494308, 0.04111402]) >>> a.min(axis=1) array([ 0.07494308, 0.01711571, 0.04111402]) -- 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: language design question
Steven Bethard wrote: > Terry Reedy wrote: > >> "Gregory Guthrie" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> >>> - why is len() not a member function of strings? Instead one says >>> len(w). >> >> >> Consider >> > map(len, ('abc', (1,2,3), [1,2], {1:2})) >> >> [3, 3, 2, 1] >> >> Now try to rewrite this using methods (member functions). > map(lambda obj: obj.__len__(), ('abc', (1,2,3), [1,2], {1:2})) > For all the doubters out there, here's an example you can't really > rewrite with a list comprehension:: > > >>> sorted(['aaa', 'bb', 'c']) > ['aaa', 'bb', 'c'] > >>> sorted(['aaa', 'bb', 'c'], key=len) > ['c', 'bb', 'aaa'] Nope, but it still doesn't require len() being a function > If len() were a method of string objects, you could try using the > unbound method and writing this as:: > > >>> sorted(['aaa', 'bb', 'c'], key=str.len) > ['c', 'bb', 'aaa'] > > But then your code would break on lists that weren't strings. sorted(['aaa', 'bb', 'c'], key=lambda obj: obj.__len__()) Note that in both cases, my lambda is mostly a reimplementation of len() - and as far as I'm concerned, len() is quite ok... -- 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: language design question
Steven Bethard <[EMAIL PROTECTED]> writes: > If len() were a method of string objects, you could try using the > unbound method and writing this as:: > > >>> sorted(['aaa', 'bb', 'c'], key=str.len) > ['c', 'bb', 'aaa'] > > But then your code would break on lists that weren't strings. sorted(['aaa', 'bb', 'c'], key=lambda x: x.len()) -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
guthrie wrote: > Good point, thanks. > > But if (as I proposed..!) the user interface is better if presented as a > method. one could porovide convenience methods which would then > interface to these underlying library functions; yes? > Actually, and AFAIK, len(obj) = lambda obj : obj.__len__(). -- 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: [wwwsearch-general] ClientForm request re ParseErrors
On Sun, 9 Jul 2006, bruce wrote: [...] > sgmllib.SGMLParseError: expected name token at ' > > partial html > --- > > > Action="/servlets/iclientservlet/a2k_prd/?ICType=Panel&Menu=SA_LEARNER_SERVI > CES&Market=GBL&PanelGroupName=CLASS_SEARCH" autocomplete=off> > > > [...] You don't include the HTML mentioned in the exception message (''. The comment sgmllib is complaining about is missing the '--'. You can work around bad HTML using the .set_data() method on response objects and the .set_response() method on Browser. Call the latter before you call any other methods that would require parsing the HTML. r = br.response() r.set_data(clean_html(br.get_data())) br.set_response(r) You must write clean_html yourself (though you may use an external tool to do so, of course). Alternatively, use a more robust parser, e.g. br = mechanize.Browser(factory=mechanize.RobustFactory()) (you may also integrate another parser of your choice with mechanize, with more effort) John -- http://mail.python.org/mailman/listinfo/python-list
Re: Running multiple versions of Python on the same host..
In article <[EMAIL PROTECTED]>, "Cowmix" <[EMAIL PROTECTED]> wrote: >What is the best way to run multiple version of Python on the same >system? You could use chroot. Ask if you want more details. -- http://mail.python.org/mailman/listinfo/python-list
compiling 2.3.5 on ubuntu
Hi, list.I'm having a hard time trying to get a couple of tests to pass when compling Python 2.3.5 on Ubuntu Server Edition 6.06 LTS. I'm sure it's not too far removed from the desktop edition but, clearly, I need to tweak something or install some missling libs.uname -aLinux server 2.6.15-23-server #1 SMP Tue May 23 15:10:35 UTC 2006 i686 GNU/Linux When I compile Python I get these failing4 skips unexpected on linux2: test_dbm test_mpz test_bsddb test_localeI've got libgdbm-dev and libgdbm3 packages installed.Help! Sneak preview the all-new Yahoo.com. It's not radically different. Just radically better. -- http://mail.python.org/mailman/listinfo/python-list
Re: help a newbie with a IDE/book combination
I use PyScripter. http://www.mmm-experts.com/ I find it easy to use. It runs on Windows and it does have a good help file. <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > > I already have a couple of newbie books on Python itself, but would > rather get started with a nice to use IDE and I am therefore looking > for a good IDE to learn Python. On my computer I have installed eric > (http://ericide.python-hosting.com/) but it lacks any kind of useful > documentation on its use. > > Is there a good IDE which would be well documented out there? > > Many thanks > > Mamadu > > PS: I use Debian GNU/Linux on all my computers, a 500MHz proc, 256MB > RAM. > -- http://mail.python.org/mailman/listinfo/python-list
Re: help a newbie with a IDE/book combination
I think SPE is a terrific IDE, a real pleasure to work with! Also it's very complete in terms of functionality. http://stani.be/python/spe/page_download -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenate Numeric
Robert Kern skrev: > Sheldon wrote: > > Thanks again for showing me this. I have been trying to read up on > > reduce() as I have never used it before. I would like to know what it > > does. So far my search has found nothing that I can grasp. The > > reference library notes are estoteric at best. > > Can you enlighten me on this matter?' > > The .reduce() method on ufuncs works pretty much like the reduce() builtin > function. It applies the binary ufunc along the given axis of the array (the > first one by default) cumulatively. > >a = [3, 2, 1, 0] >minimum.reduce(a) == minimum(minimum(minimum(a[0], a[1]), a[2]), a[3]) > > I will note, in the form of enticement to get you to try the currently active > array package instead of Numeric, that in numpy, arrays have methods to do > minimums and maximum rather more conveniently. > > >>> import numpy as N > >>> a = N.rand(3, 5) > >>> a > array([[ 0.49892358, 0.11931907, 0.37146848, 0.07494308, 0.91973863], > [ 0.92049698, 0.35016683, 0.01711571, 0.59542456, 0.49897077], > [ 0.57449315, 0.99592033, 0.20549262, 0.25135288, 0.04111402]]) > >>> a.min() > 0.017115711878847639 > >>> a.min(axis=0) > array([ 0.49892358, 0.11931907, 0.01711571, 0.07494308, 0.04111402]) > >>> a.min(axis=1) > array([ 0.07494308, 0.01711571, 0.04111402]) > > -- > 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 Thanks for the explanation! Super. I am trying to get my bosses to purchase the Numpy documentation and upgrade to Numpy as well as matplotlib and other necessary scientific modules. But it is not entirely up to me. Still I need to learn more about Python and installing these modules myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
"guthrie" wrote: > But if (as I proposed..!) the user interface is better if presented as a > method. one could porovide convenience methods which would then > interface to these underlying library functions; yes? but if it isn't? and why this obsession with superficial syntax details? there's a lot more to a language than what standard syntax it uses for trivial things... -- http://mail.python.org/mailman/listinfo/python-list
Re: Augument assignment versus regular assignment
On 2006-07-09, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Frank Millman wrote: > >> So it looks as if x += [] modifies the list in place, while x = x + [] >> creates a new list. > > objects can override the += operator (by defining the __iadd__ method), > and the list type maps __iadd__ to extend. other containers may treat > += differently, but in-place behaviour is recommended by the language > reference: > >An augmented assignment expression like x += 1 can be rewritten as >x = x + 1 to achieve a similar, but not exactly equal effect. In >the augmented version, x is only evaluated once. Also, when possible, >the actual operation is performed in-place, meaning that rather than >creating a new object and assigning that to the target, the old object >is modified instead. What does it mean that x is only evaluated once. I have an avltree module, with an interface much like a directory. So I added print statements to __setitem__ and __getitem__ and then tried the following code. >>> from avltree import Tree >>> t=Tree() >>> t['a'] = 1 __setitem__, key = a >>> t['a'] __getitem__, key = a 1 >>> t['a'] = t['a'] + 1 __getitem__, key = a __setitem__, key = a >>> t['a'] += 1 __getitem__, key = a __setitem__, key = a >>> t['b'] = [] __setitem__, key = b >>> t['b'] = t['b'] + [1] __getitem__, key = b __setitem__, key = b >>> t['b'] += [2] __getitem__, key = b __setitem__, key = b So to me it seems that when we substitute t['a'] or t['b'] for x, x is evaluated twice with the augmented version, just like it is with the not augmented version. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy wrote: > I had a look Frederick but the page lead to: > http://pyref.infogami.com/subscriptions > Which again failed to mention namespace issues. it says The primary must evaluate to an object of a sequence or mapping type. and links to a page that explains what a primary is. the interesting page is the one about "atoms" (which includes identifiers), which point you to http://pyref.infogami.com/naming-and-binding which explains it all. -- http://mail.python.org/mailman/listinfo/python-list
threading troubles
Hi folks What am I doing wrong in the following? I just want to run fluidsynth in the background. # class MyThread(threading.Thread): def __init__(self, cmd, callback): self.__cmd = cmd self.__callback = callback threading.Thread.__init__(self) def run(self): os.system(self.__cmd) self.__callback('abcd') return cmd=midiplay+' '+fmidi xc=MyThread(cmd,addlog) xc.start() ## midiplay is 'fluidsynth -ni /home/mysndfont.sf2 mymidi.mid' addlog is a function which prints the log. If I run it only with xc.start() it does not run the program as in os.system. However if I put xc.start() xc.run() then it starts and runs it in foreground with my pygtk ui non responsive. What am I missing! Thanks for any ideas sree -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
tac-tics wrote: > Philippe Martin wrote: > >>I don't know, if I were the genious that made up Python I would not believe >>in any bible (small b) > > > Take it to alt.religion please. > > Take it to alt.narrow-mondedness please. 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: Validating Python - need doctype HTML strict
PapaRandy wrote: > When I add the doctype, and other necessities to the .py page > > (i.e., "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> > http://www.w3.org/1999/xhtml""; xml:lang="en" lang="en">) > > I get an invalid script error. Bear in mind, that this isn't 'a webpage', it's a computer program that creates a webpage. So you're not 'adding a doctype', you're 'adding some code to output a doctype', and similarly it's not Python you're validating, it's the output it creates that you validate. These are important distinctions. Anyway, what is the exact line of code you use to 'add the doctype'? And what is this 'invalid script error'? It's hard to debug your code when we have to guess what it is! However, because I'm in a good mood, I'll have a go. You probably need to escape the double quotes in the doctype because they unintentionally correspond with the double quotes in your print statement. The print statement uses double quotes to delimit the output, and the doctype uses them to delimit the type. Unfortunately the print statement probably interprets the start of the doctype's type field as the end of the print statement. Add a backslash before each double quote within your doctype and see how that goes. Alternatively you could possibly use single quotes in it instead. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Help Needed !!! Browsing and Selecting More Than One File(Problem Solved)
Special Thanks to Diez B. Roggisch and Eric Brunel. Last week on Friday I solved the problems I encountered thanks to your helpful indications. I think I covered all the ambiguity in my code. Here's the code: # executing with Python from Tkinter import * from tkFileDialog import * import tkMessageBox import os # Creating App Class class App: b_file = "" # Function to browse files, the files selected will be the items of a tuple # This tuple is assigned to the instance of App class # browseFile Function is triggered by a label in Menu def browseFile(self): App.b_file App.b_file = askopenfilename(filetypes = [("C Source Code", "*.c"), ("C Header Files", "*.h"), ("All Files", "*.*")], multiple=1) # Function to Run Code Analyzer def run(self, event): # Controls if a file is browsed and selected # If a selection is done the code continues from here if App.b_file != "": cmd_tup = "" for i in range(len(App.b_file)): cmd_tup += App.b_file[i]+' '# The type of the a tuple's items are all strings, here parameter for are arranged cmd = ' ' + cmd_tup #according to the #command prompt syntax, command is created return os.system(cmd) # command is executed else: tkMessageBox.showinfo("Window Text", "Please Firstly Browse and Select A File") # if no file is selected a warning pop-ups def __init__(self, master): frame = Frame(master) frame.pack(fill="both") self.menubar = Menu(master) self.menubar.add_command(label="Browse File", command=self.browseFile) master.config(menu=self.menubar) self.Run = Button(frame, text="Run ", fg="red") self.Run.bind("", self.run) self.Run.pack(side=LEFT, padx=10, pady=20) self.close = Button(frame, text="QUIT", fg="red", command=frame.quit) self.close.pack(side=LEFT, padx=10, pady=20) root = Tk() app=App(root) root.mainloop() __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Browser Pygame Plug-in?
Gregory Piñero wrote: > I was just idley curious on what it would take to make a web plug-in > for Pygame. I'm picturing it working the way my browser currently > shows flash games. Is such an idea even possible? Has anyone > attempted this? I doubt you can get PyGame to work this way - at least, not without some significant hacking around in the source - since PyGame relies on the underlying SDL library, and from my experience with it, I can't see it playing well with a browser whatsoever. I think SDL would have to acquire a new backend to translate input to the plugin into their event structure, and would require some way of creating an appropriate video mode that can draw to a browser's window, etc. Java applets and Flash are built for this purpose whereas PyGame is built on a technology that was designed for programs that have their own window and tend to capture all the OS's input. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
Tim Golden wrote: > Claudio Grondi wrote: > >> I am aware, that it is maybe the wrong group to ask this question, but >> as I would like to know the history of past file operations from >> within a Python script I see a chance, that someone in this group was >> into it already and is so kind to share here his experience. >> >> I can't believe, that using NTFS file system in Microsoft Windows 2000 >> or XP it is not possible to track file events as: >> >> - updating/modifying of an existing file/directory >> - deleting an existing file/directory >> - creating a new file/directory >> - _moving_ an existing file/directory (should _NOT_ be covered by the >> event duo of deleting an existing and creating a new file/directory) >> >> Any hints towards enlightenment? >> >> Claudio Grondi > > > On the offchance that you haven't seen it, you might > look at this: > > http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges > > > > but since it doesn't fulfil your criterion of *not* > representing renames by a delete and an add, it may > well not be suitable. Apart from that, I think it does > what you want. > > TJG Here a small update to the code at http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges : ACTIONS = { 1 : "Created", 2 : "Deleted", 3 : "Updated", 4 : "Renamed from something" 5 : "Renamed to something", } The correction above is according to entries: #define FILE_ACTION_ADDED 0x0001 #define FILE_ACTION_REMOVED 0x0002 #define FILE_ACTION_MODIFIED 0x0003 #define FILE_ACTION_RENAMED_OLD_NAME 0x0004 #define FILE_ACTION_RENAMED_NEW_NAME 0x0005 in ..\PlatformSDK\Include\WinNT.h Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
On Sun, 09 Jul 2006 21:31:00 -0700, placid wrote: > > greenflame wrote: >> I want to make a function that does the following. I will call it >> thefunc for short. >> >> >>> s = "Char" >> >>> thefunc(s) >> >>> s >> '||Char>>' >> >> I tried the following >> >> def thefunc(s): >> s = "||" + s + ">>" >> >> The problem is that if I look at the string after I apply the function >> to it, it is not modified. I realized that I am having issues with the >> scope of the variables. The string in the function, s, is local to the >> function and thus I am not changing the string that was inputed, but a >> copy. I cannot seem to figure out how to get what I want done. Thank >> you for your time. > > quick hack > > def thefunc(s): > return s = "||" + s + ">>" > s = "hello" s = thefunc(s) print s >||hello>> That's not a quick hack. That's the right way to solve the problem. Of course, another right way would be to have mutable strings in Python. I understand why strings need to be immutable in order to work with dicts, but is there any reason why (hypothetical) mutable strings should be avoided in situations where they aren't needed as dictionary keys? Python has mutable lists and immutable tuples, mutable sets and immutable frozen sets, but no mutable string type. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
Claudio Grondi wrote: > Here a small update to the code at > http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges > : > > ACTIONS = { >1 : "Created", >2 : "Deleted", >3 : "Updated", >4 : "Renamed from something" >5 : "Renamed to something", > } > > The correction above is according to entries: > #define FILE_ACTION_ADDED 0x0001 > #define FILE_ACTION_REMOVED 0x0002 > #define FILE_ACTION_MODIFIED 0x0003 > #define FILE_ACTION_RENAMED_OLD_NAME 0x0004 > #define FILE_ACTION_RENAMED_NEW_NAME 0x0005 >in ..\PlatformSDK\Include\WinNT.h > > Claudio Grondi Thanks. I've updated the site. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
[Tim Golden] >> On the offchance that you haven't seen it, you might >> look at this: >> >> http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges >> [Claudio Grondi] > It seems, that it will be necessary to use some logic based on the > sequence of events to exactly detect rename and move changes done to > files/directories, but in principle it is the best approach I know about > yet. > > By the way: >Is there something similar/same available for Linux? I've never used them, but I seem to think there are a couple of similar things for Linux, based on FAM or inotify: (result of Googling) http://python-fam.sourceforge.net/ http://www.gnome.org/~veillard/gamin/python.html http://rudd-o.com/projects/python-inotify/ YMMV TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: help a newbie with a IDE/book combination
[EMAIL PROTECTED] wrote: > Hi, > > I already have a couple of newbie books on Python itself, but would > rather get started with a nice to use IDE and I am therefore looking > for a good IDE to learn Python. On my computer I have installed eric > (http://ericide.python-hosting.com/) but it lacks any kind of useful > documentation on its use. > > Is there a good IDE which would be well documented out there? > > Many thanks > > Mamadu > > PS: I use Debian GNU/Linux on all my computers, a 500MHz proc, 256MB > RAM. -- http://mail.python.org/mailman/listinfo/python-list
Re: help a newbie with a IDE/book combination
[EMAIL PROTECTED] wrote: > Hi, > > I already have a couple of newbie books on Python itself, but would > rather get started with a nice to use IDE and I am therefore looking > for a good IDE to learn Python. On my computer I have installed eric > (http://ericide.python-hosting.com/) but it lacks any kind of useful > documentation on its use. > > Is there a good IDE which would be well documented out there? > > Many thanks > > Mamadu > > PS: I use Debian GNU/Linux on all my computers, a 500MHz proc, 256MB > RAM. I have used spe and pyscripter on windows. I currently use Eclipse and this it is the best of the lot in terms of functionality. However, it does take some effort to get comfortable with. I only wish it had a GUI builder for python. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
>- why is len() not a member function of strings? Instead one says len(w). Coming from a Java background, I also thought this a weird setup. However IMHO there is another good reason to have len(obj) as we do in Python: it helps to enforce some sort of uniformity across code. If I want to find out the length of some object, then I know to try len(obj). If it were merely convention that objects had a obj.len() method, then some objects would be written to conform to this. As things stand, it is common knowledge that len(obj) returns the length of an object, and that the way to give you own objects the same functionality is to give it a __len__() method. The alternative of having a obj.len() function as a convention is less compelling to use - if the users are reading your api, why not call the method size() or magnitude() or just give it a length attribute, and suddenly objects become less polymorphic as far as writing generic functions is concerned. Look at Java's Standard API for examples. An array has a length attribute. A String has a length() method. Collections have a size() method. Buffer objects have a capacity() method. One of Python's strengths is that I can write a generic method: def printSize(obj): print "The size of this object is %d" % len(obj) If we had a Java-like situation we'd have to test for different object types before deciding on which method/attribute to call: def printSize(obj): len = None if type(obj) == str: len = obj.len() elif type(obj) == Buffer: len = obj.capacity() ... print "The size of this object is %d" % len Just my view on the matter :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: pyXLWriter - grid lines and if formula
Waldemar Osuch escreveu: > Luis P. Mendes wrote: >> Gregory Piñero escreveu: >>> On 7/7/06, Luis P. Mendes <[EMAIL PROTECTED]> wrote: Hi, I know that pyExelerator is the supported project now, but I can't use it because I'd need it to generate files from a web platform. Since I can not save a file to a file-like object, I have to use pyXLWriter. > >> So, perhaps you could show me how to generate an excel file as a http >> response in django? > > If it is a simple one sheet Workbook you can produce HTML document with > a table and set the headers to indicate it is Excel. > > Content-Type: application/vnd.ms-excel > Content-Disposition: attachment;filename=report.xls > > Lookup documentation on how to generate formula: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnoffxml/html/ofxml2k.asp > > Waldemar > Thanks, but it's a workbook with several sheets. Luis P. Mendes -- http://mail.python.org/mailman/listinfo/python-list
Need help in xml
i have two xml documemts of type test 2006-12-12 12:12:12 /home/ test2 12:12:12 /home/test test3 12:12:12 i have to compare 2 similar xml document and get the add, changed and deleted files.and write it into acd.xml file. can u help me with the python code for this. I am using SAX. -- http://mail.python.org/mailman/listinfo/python-list
Re: xml aggregator
thanks a lot for the code. It was not working the first time (do not recognize item and existing_time --> i changed item by r[-1] and existing_time by existing_equip). however, it is not producing the result i expected, as in it doesn't group by same category the elements, it creates a new block of xml - - - my first value - - - my second value - - - my third value - - - my fourth value - - - my fifth value - my sixth value The idea behind all that is : i want to create an xml file that'll have a XSL instructions. The xsl will sort the entries and display something like : Route 23: *jr1 *3pm value value value *5pm value value *jr2 *3pm value value value *5pm value value Route 29 *jr1 *3pm value value value *5pm value value *jr2 *3pm value value value *5pm value value I know this is feasible with XSL2 , but i need something compatible with quite old browser, and XSL2 is not even working on my comp( i could upgrade but i cannot ask all the users to do so). That's why I thought rearranging the xml would do it. Do you have other idea? Do u think it is the best choice? More information abt the application I am writing : i am parsing a feed, extracting some data and producing reports. the application is running on spyce, so i don't have to produce a file in output, just print the xml to the screen and it is automatically wrting to the html page we view. Thanks again for your help. Gerard Flanagan wrote: > Gerard Flanagan wrote: > > kepioo wrote: > > > Hi all, > > > > > > I am trying to write an xml aggregator, but so far, i've been failing > > > miserably. > > > > > > what i want to do : > > > > > > i have entries, in a list format :[[key1,value],[key2,value],[ > > > key3,value]], value] > > > > > > example : > > > [["route","23"],["equip","jr2"],["time","3pm"]],"my first value"] > > > [["route","23"],["equip","jr1"],["time","3pm"]],"my second value"] > > > [["route","23"],["equip","jr2"],["time","3pm"]],"my third value"] > > > [["route","24"],["equip","jr2"],["time","3pm"]],"my fourth value"] > > > [["route","25"],["equip","jr2"],["time","3pm"]],'"my fifth value"] > > > > > > > [snip example data] > > > > > > > > > > > If anyone has an idea of implemetation or any code ( i was trying with > > > ElementTree... > > > > > > > (You should have posted the code you tried) > > > > The code below might help (though you should test it more than I have). > > The 'findall' function comes from here: > > > > http://gflanagan.net/site/python/elementfilter/elementfilter.py > > > > it's not the elementtree one. > > > > Sorry, elementfilter.py was a bit broken - fixed now. Use the current > one and change the code I posted to: > > [...] > existing_route = findall(results, "[EMAIL PROTECTED]" % routeid) > #changed line > if existing_route: > route = existing_route[0] > existing_equip = findall(route, "[EMAIL PROTECTED]'%s']" % equipid) > if existing_equip: > [...] > > ie. don't quote the route id since it's numeric. > > Gerard -- http://mail.python.org/mailman/listinfo/python-list
Accessors in Python (getters and setters)
Hello, What is the Pythonic way of implementing getters and setters. I've heard people say the use of accessors is not Pythonic. But why? And what is the alternative? I refrain from using them because they smell "Javaish." But now my code base is expanding and I'm beginning to appreciate the wisdom behind them. I welcome example code and illustrations. Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
mystilleef <[EMAIL PROTECTED]> wrote: > What is the Pythonic way of implementing getters and setters. Using public members and turning them into properties when needed > I've > heard > people say the use of accessors is not Pythonic. But why? Because there's no need to have them everywhere > But now my code base is expanding and I'm beginning to appreciate the > wisdom behind them. I welcome example code and illustrations. Search for "python property" -- 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: Augument assignment versus regular assignment
In article <[EMAIL PROTECTED]>, Antoon Pardon <[EMAIL PROTECTED]> wrote: >On 2006-07-09, Fredrik Lundh <[EMAIL PROTECTED]> wrote: >> Frank Millman wrote: >> >>> So it looks as if x += [] modifies the list in place, while x = x + [] >>> creates a new list. >> >> objects can override the += operator (by defining the __iadd__ method), >> and the list type maps __iadd__ to extend. other containers may treat >> += differently, but in-place behaviour is recommended by the language >> reference: >> >>An augmented assignment expression like x += 1 can be rewritten as >>x = x + 1 to achieve a similar, but not exactly equal effect. In >>the augmented version, x is only evaluated once. Also, when possible, >>the actual operation is performed in-place, meaning that rather than >>creating a new object and assigning that to the target, the old object >>is modified instead. > >What does it mean that x is only evaluated once. I have an avltree module, >with an interface much like a directory. So I added print statements to >__setitem__ and __getitem__ and then tried the following code. > from avltree import Tree t=Tree() t['a'] = 1 >__setitem__, key = a t['a'] >__getitem__, key = a >1 t['a'] = t['a'] + 1 >__getitem__, key = a >__setitem__, key = a t['a'] += 1 >__getitem__, key = a >__setitem__, key = a t['b'] = [] >__setitem__, key = b t['b'] = t['b'] + [1] >__getitem__, key = b >__setitem__, key = b t['b'] += [2] >__getitem__, key = b >__setitem__, key = b > >So to me it seems that when we substitute t['a'] or t['b'] for x, >x is evaluated twice with the augmented version, just like it >is with the not augmented version. $ cat x.py def getindex(ind = 0): print 'getindex() called' return ind a = [0, 1, 2, 3, 4, 5] a[getindex(0)] = a[getindex(0)] + 17 print a a[getindex(1)] += 22 print a $ python x.py getindex() called getindex() called [17, 1, 2, 3, 4, 5] getindex() called [17, 23, 2, 3, 4, 5] In this case, getindex() is a rather pointless function, but it could be an expensive one or one with side effects or even one which alters state, so that it gives different values on subsequent calls with the same argument. The += version finds the object to be operated upon once, the expanded version does it twice. -- Jim Segrave ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
mystilleef wrote: > Hello, > > What is the Pythonic way of implementing getters and setters. I've > heard > people say the use of accessors is not Pythonic. But why? And what is > the alternative? I refrain from using them because they smell > "Javaish." > But now my code base is expanding and I'm beginning to appreciate the > wisdom behind them. I welcome example code and illustrations. Which wisdom do you mean? The wisdom that a language that has no property mechanism and thus can't intercept setting and getting of instance members needs a bulky convention called JAVA Beans, so that _all_ uses of properties are tunneled through some code, even if only a few percent of these actually need that? Or the wisdom that strangling developers by putting access modifiers with approx. a dozen different rules in place is an annoyance to adult developers to say the least? These are the reasons they are not pythonic. We can intercept property access (see the property descriptor, http://pyref.infogami.com/property), and we trust in developers being able to judge form themselves if messing with internals of code is a good idea or not. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: threading troubles
On Mon, 10 Jul 2006 11:29:37 +, sreekant <[EMAIL PROTECTED]> wrote: >Hi folks > >What am I doing wrong in the following? I just want to run fluidsynth in >the background. ># >class MyThread(threading.Thread): > def __init__(self, cmd, callback): > self.__cmd = cmd > self.__callback = callback > threading.Thread.__init__(self) > > def run(self): > os.system(self.__cmd) > self.__callback('abcd') > return > > >cmd=midiplay+' '+fmidi >xc=MyThread(cmd,addlog) >xc.start() > You don't need threads to run another process "in the background". For example, here's how you would do it with Twisted: from twisted.internet import gtk2reactor gtk2reactor.install() from twisted.internet import reactor def main(): reactor.spawnProcess( None, '/usr/bin/fluidsynth', ['fluidsynth', '-ni', '/home/mysndfont.sf2', 'mymidi.mid']) reactor.run() Your Gtk app won't block and you won't have to worry about the threading/forking/signal interaction that is messing you up now. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
Learning Python, Perl, or Ruby would help you create admin scripts that would save you lots of manual work. For me automated log file alerting, SQL query parsing, SQL table updates, Internet file uploading/downloading, etc. has been a huge plus. Perl is likely the most widely used in terms of existing scripts that you can review, modify, borrow ideas from, etc. But from a long term maintainability and readability standpoint I would recommend Python or Ruby over Perl. Just my $0.02... IOANNIS MANOLOUDIS wrote: > I thank everybody for your replies. > I think I'll get Hertland's book since it's newer than O'reillys. > I don't want to become a programmer. Neither Python is part of my studies. > I've finished with my studies. I want to become a Unix/Linux admin and > knowledge of either Python or Perl is an asset. > Do you think that this book is the right one for me? > Ioannis -- http://mail.python.org/mailman/listinfo/python-list
Looking for a HTML like rendering library (wishlist)
Hello, I'm looking for a library that can do the following: * Parse a simple structured text file (XML or HTML etc.) * Render its output to an image * I would like to give the maximum width of the image (but not the minimum) * I would like to use my custom TrueType fonts, and some basic formatting: colors, underline, numbered and bulleted lists * I would like to embed some PNG (transparent) images, and align them inside the text * The library should be able to calculate the size of the image before rendering * The library should be able to render the image into memory * It should be reasonably fast * It should be independent of windowing toolkits (PIL is okay) Why I need this: create widgets in GUI applications, for example: * A label that can display formatted text * A new grid cell renderer that can display small images and text as well * Hint window (tooltip) that has formatted text and images * Create automatic signatures for e-mails (not GUI related) * etc I tried to implement something similar in pure Python, PyXRP and PIL. I could do it, but either it was too slow (10 frames per sec on 300x300 final size) or consumed too much memory. Do you know any alternative? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
std in and stdout
hello, i have a question! how would i fix the following problem: now i have an input file with a fix name and an output file! i have this two files hardcoded written in the sourcecode of this function! in the future i will start this script with the command line. the syntax should be look like this: Python Function | Source File| Output File --- fileanalyse.pysourcefile.csv filenalyse.txt i will call the programm always with the commandline, that i could type in various filenames for the input and output files! could anybody help me?! -- http://mail.python.org/mailman/listinfo/python-list
Re: std in and stdout
Juergen Huber írta: > hello, > > i have a question! > > how would i fix the following problem: > > now i have an input file with a fix name and an output file! > i have this two files hardcoded written in the sourcecode of this function! > > in the future i will start this script with the command line. > the syntax should be look like this: > > Python Function | Source File| Output File > --- > fileanalyse.pysourcefile.csv filenalyse.txt > > i will call the programm always with the commandline, that i could type in > various filenames for the input and output files! > > could anybody help me?! > > You might want to use sys.argv or the much nicer optparse module: http://docs.python.org/lib/module-optparse.html I might not have understood your problem, though. :) Laszlo -- http://mail.python.org/mailman/listinfo/python-list
To compile the VideoCapture module
Hello (and sorry for my English), I downloaded the VideoCapture module on the http://videocapture.sourceforge.net/ site. I tested it with a webcam and that functions. Now I want to compile his file .cpp (vidcap.cpp). Thereafter, the idea is to be able to modify the code to include my own modifications. For the moment I only try to compile, but does not arrive :( I will try to pose my problem : First of all I am under Windows xp because I must use DirectX. I use the MinGW compiler. I use following script (setup.py) to be able to compile : nomModule = 'vidcap' from distutils.core import setup, Extension setup(name = nomModule, ext_modules = [ Extension(nomModule, sources = [ nomModule+'.cpp'],\ include_dirs=["C:\DX90SDK\Include","C:\DX90SDK\Samples\C++\DirectShow\BaseClasses"],\ library_dirs=["C:\Python23\libs","C:\DX90SDK\Lib","C:\Python23\Enthought\MingW\lib"]) ]) The include_dirs enable me to indicate the access path has my .h that I need. And library_dirs in theory the libraries which I need (I say in theory because I do not have the impression that it takes into account, but we will return later). I try so the first compilation with : python setup.py build I have a few errors I try to resolve them Here the modifications which I have of bringing : In strmif.h: line 6164 : replace #ifndef _WINGDI_ by #ifndef _WINGDI_H line 20557 : Add EXTERN_GUID definition just before first EXTERN_GUID(): #ifndef EXTERN_GUID #define EXTERN_GUID(g,l1,s1,s2,c1,c2,c3,c4,c5,c6,c7,c8) DEFINE_GUID(g,l1,s1,s2,c1,c2,c3,c4,c5,c6,c7,c8) #endif line 28736 : Fix the tagVMRGUID struct (GUID -> ::GUID) ::GUID *pGUID; ::GUID GUID; Put UrlMon.h in the file include of DX90SDK (recover it in Microsoft Platform SDK) in the same way for MsXml.h. Then to define uCLSSPEC and QUERYCONTEXT, I have includes their definition directly in my file .cpp : //-- // definitions recuperées de c:\Program Files\Microsoft Plateform SDK\include\WTypes.h typedef struct tagCSPLATFORM { DWORD dwPlatformId; DWORD dwVersionHi; DWORD dwVersionLo; DWORD dwProcessorArch; } CSPLATFORM; #ifndef _LCID_DEFINED #define _LCID_DEFINED typedef DWORD LCID; #endif // !_LCID_DEFINED typedef struct tagQUERYCONTEXT { DWORD dwContext; CSPLATFORM Platform; LCID Locale; DWORD dwVersionHi; DWORD dwVersionLo; } QUERYCONTEXT; typedef WCHAR OLECHAR; typedef OLECHAR *LPOLESTR; typedef struct __MIDL___MIDL_itf_wtypes_0003_0001 { DWORD tyspec; union __MIDL___MIDL_itf_wtypes_0003_0005 { CLSID clsid; LPOLESTR pFileExt; LPOLESTR pMimeType; LPOLESTR pProgId; LPOLESTR pFileName; struct { LPOLESTR pPackageName; GUID PolicyId; } ByName; struct { GUID ObjectId; GUID PolicyId; } ByObjectId; } tagged_union; } uCLSSPEC; //-- Last thing modified in vidcap.cpp : line 774 : /*statichere*/ PyTypeObject Dev_Type = { Comment out statichere, because it was already declared in extern. After all these modifications, I compile again and no errors but... Here what I obtain with compilation : running install running build running build_ext building 'vidcap' extension C:\Python23\Enthought\MingW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\DX90SDK\Include -IC:\DX 90SDK\Samples\C++\DirectShow\BaseClasses -Ic:\Python23\include -Ic:\Python23\PC -c vidcap.cpp - o build\temp.win32-2.3\Release\vidcap.o In file included from C:/DX90SDK/Include/dshow.h:46, from vidcap.cpp:24: C:/DX90SDK/Include/strmif.h:2: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/dshow.h:46, from vidcap.cpp:24: C:/DX90SDK/Include/strmif.h:877: warning: ignoring #pragma warning C:/DX90SDK/Include/strmif.h:878: warning: ignoring #pragma warning C:/DX90SDK/Include/strmif.h:30645: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/dshow.h:49, from vidcap.cpp:24: C:/DX90SDK/Include/control.h:2: warning: ignoring #pragma warning In file included from vidcap.cpp:73: C:/DX90SDK/Include/qedit.h:2: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/qedit.h:492, from vidcap.cpp:73: C:/DX90SDK/Include/dxtrans.h:2: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/d3d.h:189, from C:/DX90SDK/Include/dxtrans.h:278, from C:/DX90SDK/Include/qedit.h:492, from vidcap.cpp:73: C:/DX90SDK/Include/d3dtypes.h:26: warning: ignoring #pragma warning C:/DX90SDK/Include/d3dtypes.h:2116: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/dxtrans.h:280, from C:/DX90SDK/Include/qedit.h:492, from vidcap.cpp:73: C:/DX90SDK/Include/urlmon.h:17: warning: ignoring #pragma warning In file included from C:/DX90SDK/Include/urlmon.h:278, from C:/DX90SDK/Include/dxtrans.h:280, from C:/DX90SDK/Include/qedit.h:492, from vidcap.cpp:73: C:/DX90
Re: Accessors in Python (getters and setters)
I decided to change the name of an attribute. Problem is I've used the attribute in several places spanning thousands of lines of code. If I had encapsulated the attribute via an accessor, I wouldn't need to do an unreliable and tedious search and replace accross several source code files to achieve my goal. I could simply change the name of the attribute and move on. Well, I'm glad python has properties. It's a feature that should be advertised more, especially for large scale python development. Diez B. Roggisch wrote: > mystilleef wrote: > > > Hello, > > > > What is the Pythonic way of implementing getters and setters. I've > > heard > > people say the use of accessors is not Pythonic. But why? And what is > > the alternative? I refrain from using them because they smell > > "Javaish." > > But now my code base is expanding and I'm beginning to appreciate the > > wisdom behind them. I welcome example code and illustrations. > > Which wisdom do you mean? The wisdom that a language that has no property > mechanism and thus can't intercept setting and getting of instance members > needs a bulky convention called JAVA Beans, so that _all_ uses of > properties are tunneled through some code, even if only a few percent of > these actually need that? > > Or the wisdom that strangling developers by putting access modifiers with > approx. a dozen different rules in place is an annoyance to adult > developers to say the least? > > These are the reasons they are not pythonic. We can intercept property > access (see the property descriptor, http://pyref.infogami.com/property), > and we trust in developers being able to judge form themselves if messing > with internals of code is a good idea or not. > > Regards, > > Diez -- http://mail.python.org/mailman/listinfo/python-list
RE: Detecting 64bit vs. 32bit Linux
The one thing I observed (just an observation) is that: a) on 32-bit machines: sizeof(int) = 32 sizeof(long) = 32 b) on 64-bit machines: sizeof(int) = 32 sizeof(long) = 64 This in C and Python. Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Lawrence D'Oliveiro Sent: Monday, July 10, 2006 3:11 AM To: python-list@python.org Subject: Re: Detecting 64bit vs. 32bit Linux In article <[EMAIL PROTECTED]>, dwelch91 <[EMAIL PROTECTED]> wrote: >I need to detect whether the operating system I am running on (not the >Python version) is 64bit or 32bit. One requirement is that I need to >include support for non-Intel/AMD architectures. The standard C way would be to check sizeof(void *). -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: converting file formats to txt
tks this ws really helpful, i used catdoc, catppt, xls2csv, pdftotext from xdf and ps2txt from ghostview!.. BJörn Lindqvist wrote: > On 4 Jul 2006 08:38:47 -0700, Gaurav Agarwal > <[EMAIL PROTECTED]> wrote: > > Thanks Steven, Actually i wanted a do text processing for my office > > where I can view all files in the system and use the first three to > > give a summary of the document. Instead of having somebody actually > > entering the summary. Seems there is no one code that can act as > > convertor across formats, i'll have to check out convertors for > > individual formats. > > I have some old code that does just that. It uses pdftotext, catdoc > and links to convert .doc, .pdf and .html to text. > > ## > import mimetypes > from subprocess import call, Popen, PIPE > import sys > > class ConversionError(Exception): > pass > > class UnknownMimeType(ConversionError): > pass > > class NotAMimeType(ConversionError): > pass > > class ParseError(ConversionError): > pass > > def has_program(progname): > return call(["which", progname], stdout = PIPE) == 0 > > def check_requirements(): > missing = [] > for prog in "catdoc", "pdftotext", "links": > if not has_program(prog): > missing.append(prog) > if missing: > print "You need to have the programs:", " ".join(missing) > return False > return True > > if not check_requirements(): > print "Needed external programs not found, quitting" > sys.exit(1) > > def get_catdoc_args(infile): > return ["catdoc", "-s", "8859-1", infile] > > def get_pdftotext_args(infile): > return ["pdftotext", infile, "-"] > > def get_links_args(infile): > return ["links", infile, "-dump"] > > def totext(document): > filetype_to_args_map = {"application/msword" : get_catdoc_args, > "application/pdf" : get_pdftotext_args, > "text/html" : get_links_args} > > ftype, ign = mimetypes.guess_type(document) > if not ftype: > raise NotAMimeType, "Couldn't detect mimetype for %s" % document > try: > argfunc = filetype_to_args_map[ftype] > except KeyError: > s = "Don't know how to handle %s documents" % ftype > raise UnknownMimeType, s > > p = Popen(argfunc(document), stdout = PIPE, stderr = PIPE) > text = p.stdout.read() > if p.wait(): > # Force a better exception to be thrown if the file doesn't exist. > open(document) > raise ParseError, "Failed to parse %s" % document > return text > > if __name__ == "__main__": > print totext("testpdf.pdf") > > > > -- > mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
mystilleef wrote: > I decided to change the name of an attribute. Problem is I've used the > attribute in several places spanning thousands of lines of code. If I > had encapsulated the attribute via an accessor, I wouldn't need to do > an unreliable and tedious search and replace accross several source > code files to achieve my goal. I could simply change the name of the > attribute and move on. You could, but then you'd be left with crap names for your accessors! In your equivalent Java code, you'd typically have used the accessors in several places throughout the code (or else why bother using them?), so you wouldn't be any better off! The main benefit for having accessors in Java is not that you can change the *name* of an attribute, but that you can change the implementation of the attribute - i.e. change the what actually happens to when the accessor is called. Which you can do in Python with properties. -- http://mail.python.org/mailman/listinfo/python-list
mod_python fails to load under wamp
Hi, Am using WAMP5 and python 2.4.3. I tried to install mod_python 3.2.5 for python2.4. When i tried starting wamp, Firstly there was no error message in the apache error log. I saw error message in windows event viewer : "The Apache service named Apache.exe reported the following error: >>> Syntax error on line 194 of c:/wamp/apache/conf/httpd.conf: <<< before the error.log file could be opened. "The Apache service named Apache.exe reported the following error: >>> Cannot load c:/wamp/apache/modules/mod_python.so into server: (126) The >>> specified module could not be found: <<< before the error.log file could be opened." I tried searching the net and found this http://www.modpython.org/FAQ/faqw.py?req=all#2.10 but i don't have depends.exe. if somebody has faced this problem before, can you please assist in fixing this bug.. thanks and regards, Gaurav Agarwal -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting 64bit vs. 32bit Linux
Michael Yanowitz wrote: .. > >> I need to detect whether the operating system I am running on (not the >> Python version) is 64bit or 32bit. One requirement is that I need to >> include support for non-Intel/AMD architectures. > > The standard C way would be to check sizeof(void *). so on those old ARM RISC OSes with 32 bit arithmetic would I get sizeof(void *) == 4 when the address bus was 26 bits wide? Seems a bit naive to assume the address bus will always be the same width as the registers, but I guess the compilers have to do something. I seem to remember some compilers allowing pure 32 bit addressing on 8088 machines (with 16 bit registers), but I think the M$ compilers all had near and far pointer mechanisms to help you get confused. -mumbling-ly yrs- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: xml aggregator
> Gerard Flanagan wrote: > > Gerard Flanagan wrote: > > > kepioo wrote: > > > > Hi all, > > > > > > > > I am trying to write an xml aggregator, but so far, i've been failing > > > > miserably. > > > > > > > > what i want to do : > > > > > > > > i have entries, in a list format :[[key1,value],[key2,value],[ > > > > key3,value]], value] > > > > > > > > example : > > > > [["route","23"],["equip","jr2"],["time","3pm"]],"my first value"] > > > > [["route","23"],["equip","jr1"],["time","3pm"]],"my second value"] > > > > [["route","23"],["equip","jr2"],["time","3pm"]],"my third value"] > > > > [["route","24"],["equip","jr2"],["time","3pm"]],"my fourth value"] > > > > [["route","25"],["equip","jr2"],["time","3pm"]],'"my fifth value"] > > > > > > > > > > [snip example data] > > > > > > > > > > > > > > > If anyone has an idea of implemetation or any code ( i was trying with > > > > ElementTree... > > > > > > > > > > (You should have posted the code you tried) > > > > > > The code below might help (though you should test it more than I have). > > > The 'findall' function comes from here: > > > > > > http://gflanagan.net/site/python/elementfilter/elementfilter.py > > > > > > it's not the elementtree one. > > > > > > > Sorry, elementfilter.py was a bit broken - fixed now. Use the current > > one and change the code I posted to: > > > > [...] > > existing_route = findall(results, "[EMAIL PROTECTED]" % routeid) > > #changed line > > if existing_route: > > route = existing_route[0] > > existing_equip = findall(route, "[EMAIL PROTECTED]'%s']" % equipid) > > if existing_equip: > > [...] > > > > ie. don't quote the route id since it's numeric. kepioo wrote: > thanks a lot for the code. > > It was not working the first time (do not recognize item and > existing_time -- Apologies, I ran the code from PythonWin which remembers names that were previously declared though deleted - should have run it as a script. > i changed item by r[-1] and existing_time by > existing_equip). > 'item' was wrong but not the other two. (I'm assuming your data is regular - ie. all the records have the same number of fields) change the for loop to the following: 8<-- for routeid, equipid, timeid, data in records: route, equip, time = None, None, None existing_route = findall(results, "[EMAIL PROTECTED]" % routeid) if existing_route: route = existing_route[0] existing_equip = findall(route, "[EMAIL PROTECTED]" % equipid) if existing_equip: equip = existing_equip[0] existing_time = findall(equip, "[EMAIL PROTECTED]" % timeid) if existing_time: time = existing_time[0] route = route or SubElement(results, 'route', id=routeid) equip = equip or SubElement(route, 'equip', id=equipid) time = time or SubElement(equip, 'time', id=timeid) dataitem = SubElement(time,'data') dataitem.text = data 8<-- > however, it is not producing the result i expected, as in it doesn't > group by same category the elements, it creates a new block of xml > [...] the changes above should give you what you want - remember, as I wrote in the previous post, it should be: "[EMAIL PROTECTED]" not "[EMAIL PROTECTED]'%s']" ie. no single quotes needed. With the above amended code I get: my first value my third value my second value my fourth value my fifth value my sixth value all the best Gerard ps. this newsgroup prefers that you don't top-post. -- http://mail.python.org/mailman/listinfo/python-list
Re: Augument assignment versus regular assignment
On 2006-07-10, Jim Segrave <[EMAIL PROTECTED]> wrote: > In article <[EMAIL PROTECTED]>, > Antoon Pardon <[EMAIL PROTECTED]> wrote: >>On 2006-07-09, Fredrik Lundh <[EMAIL PROTECTED]> wrote: >>> Frank Millman wrote: >>> So it looks as if x += [] modifies the list in place, while x = x + [] creates a new list. >>> >>> objects can override the += operator (by defining the __iadd__ method), >>> and the list type maps __iadd__ to extend. other containers may treat >>> += differently, but in-place behaviour is recommended by the language >>> reference: >>> >>>An augmented assignment expression like x += 1 can be rewritten as >>>x = x + 1 to achieve a similar, but not exactly equal effect. In >>>the augmented version, x is only evaluated once. Also, when possible, >>>the actual operation is performed in-place, meaning that rather than >>>creating a new object and assigning that to the target, the old object >>>is modified instead. >> >>What does it mean that x is only evaluated once. I have an avltree module, >>with an interface much like a directory. So I added print statements to >>__setitem__ and __getitem__ and then tried the following code. >> > from avltree import Tree > t=Tree() > t['a'] = 1 >>__setitem__, key = a > t['a'] >>__getitem__, key = a >>1 > t['a'] = t['a'] + 1 >>__getitem__, key = a >>__setitem__, key = a > t['a'] += 1 >>__getitem__, key = a >>__setitem__, key = a > t['b'] = [] >>__setitem__, key = b > t['b'] = t['b'] + [1] >>__getitem__, key = b >>__setitem__, key = b > t['b'] += [2] >>__getitem__, key = b >>__setitem__, key = b >> >>So to me it seems that when we substitute t['a'] or t['b'] for x, >>x is evaluated twice with the augmented version, just like it >>is with the not augmented version. > > $ cat x.py > > def getindex(ind = 0): > print 'getindex() called' > return ind > > a = [0, 1, 2, 3, 4, 5] > a[getindex(0)] = a[getindex(0)] + 17 > print a > a[getindex(1)] += 22 > print a > > $ python x.py > getindex() called > getindex() called > [17, 1, 2, 3, 4, 5] > getindex() called > [17, 23, 2, 3, 4, 5] > > In this case, getindex() is a rather pointless function, but it could > be an expensive one or one with side effects or even one which alters > state, so that it gives different values on subsequent calls with the > same argument. > > The += version finds the object to be operated upon once, the expanded > version does it twice. I disagree. The += version only evaluates the index once, but still has to find the object twice. Let us start with the following: t['b'] = [] Now with x being evaluated once, I would expect that t[getindex('b')] += [1] would be equivallent to: _key = getindex('b') _lst = t[_key] _lst += [1] And not to the following: _key = getindex('b') _lst = t[_key] _lst += [1] t[_key] = _lst But as far as I can interpret what is happening from the printed lines the second is happening and not the first. So in this example some optimisation has happened, by calculating the key only once, but the search for the object using that precalculated key happens twice, once with __getitem__ and once with __setitem__. >>> t['b'] = [] __setitem__, key = b >>> t[getindex('b')] += [1] getindex() called __getitem__, key = b __setitem__, key = b -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python fails to load under wamp
> "The Apache service named Apache.exe reported the following error: > >>> Cannot load c:/wamp/apache/modules/mod_python.so into server: (126) The > >>> specified module could not be found: <<< > before the error.log file could be opened." I have just had a similar problem (same error message), not with mod_python, but with another apache module. It turned out that the latest version of XAMPP (the lamp-type stack distribution I'm using) bundled Apache 2.2, where the module was only compatible with Apache 2.0 or earlier. I guess they must have changed the module interface in 2.2. Anyway, I solved the problem by downgrading to Apache 2.0. Sounds like a similar problem here - I'll bet WAMP bundles Apache 2.2. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting 64bit vs. 32bit Linux
Michael Yanowitz wrote: > The one thing I observed (just an observation) is that: > a) on 32-bit machines: > sizeof(int) = 32 > sizeof(long) = 32 > b) on 64-bit machines: > sizeof(int) = 32 > sizeof(long) = 64 > > This in C and Python. As I've said previously in this thread, not all systems work like that. Specifically, on Win64 sizeof(long) == 32. -- 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: first book about python
IOANNIS MANOLOUDIS wrote: > I want to learn python. > I plan to buy a book. I always find printed material more convenient than > reading on-line tutorials. > I don't know PERL or any other scripting language. I only know some BASH > programming. I am looking for a book which will help me get started and > should contain the foundations. I am not looking for the Python bible. > Any recommendations? > Ioannis > I definitely recommend Learning Python (2nd ed.) from O'Reilly. Despite what some may say, I do *not* recommend Beginning Python (Apress) because it moves too quickly for a beginner and doesn't explain everything fully. -- http://mail.python.org/mailman/listinfo/python-list
Re: threading troubles
you don't need twisted to run processes in the background, either. os.popen* returns a file or set of files representing std streams immediately subprocess.Popen is a spiffy little object new in 2.4 and available for download for 2.3. check the module docstrings for usage tips. you can use threads, but try doing it the python way instead of the java way. ;-) def func(cmd, callback): os.system(cmd) callback() xc = threading.Thread(target=func, args=(cmd, callback)) xc.start() sreekant wrote: > Hi folks > > What am I doing wrong in the following? I just want to run fluidsynth in > the background. > # > class MyThread(threading.Thread): > def __init__(self, cmd, callback): > self.__cmd = cmd > self.__callback = callback > threading.Thread.__init__(self) > > def run(self): > os.system(self.__cmd) > self.__callback('abcd') > return > > > cmd=midiplay+' '+fmidi > xc=MyThread(cmd,addlog) > xc.start() > > > ## > midiplay is 'fluidsynth -ni /home/mysndfont.sf2 mymidi.mid' > addlog is a function which prints the log. > > If I run it only with xc.start() it does not run the program as in > os.system. However if I put > xc.start() > xc.run() > > then it starts and runs it in foreground with my pygtk ui non responsive. > > What am I missing! > > Thanks for any ideas > sree -- http://mail.python.org/mailman/listinfo/python-list
RE: [wwwsearch-general] ClientForm request re ParseErrors
is this where i've seen references to integrating Beautifulsoup in the wb browsing app? -bruce -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of John J Lee Sent: Monday, July 10, 2006 2:29 AM To: [EMAIL PROTECTED] Cc: python-list@python.org Subject: RE: [wwwsearch-general] ClientForm request re ParseErrors On Sun, 9 Jul 2006, bruce wrote: [...] > sgmllib.SGMLParseError: expected name token at ' > > partial html > --- > > > Action="/servlets/iclientservlet/a2k_prd/?ICType=Panel&Menu=SA_LEARNER_SERVI > CES&Market=GBL&PanelGroupName=CLASS_SEARCH" autocomplete=off> > > > [...] You don't include the HTML mentioned in the exception message (''. The comment sgmllib is complaining about is missing the '--'. You can work around bad HTML using the .set_data() method on response objects and the .set_response() method on Browser. Call the latter before you call any other methods that would require parsing the HTML. r = br.response() r.set_data(clean_html(br.get_data())) br.set_response(r) You must write clean_html yourself (though you may use an external tool to do so, of course). Alternatively, use a more robust parser, e.g. br = mechanize.Browser(factory=mechanize.RobustFactory()) (you may also integrate another parser of your choice with mechanize, with more effort) John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
re question
Hello, consider the following code >>> re.search("[a-z](?i)[a-z]","AA") <_sre.SRE_Match object at 0x40177e20> this gives a match if we provide an extra group for the first character it still works >>> re.search("([a-z])(?i)[a-z]","AA").group(1) 'A' >>> it doesn't matter where (?i) is placed, right? the re engine would glance at once on the entire pattern string analize it (complain if pattern doesn't make sense, eg invalid) and it would be the same as if the option was given expicitely as re.IGNORECASE. Is there a way to switch-off the option resp. switch-on the option in the middle of the pattern? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance, types, operator overload, head ache
Thanks very much for the reply. I'll give that a shot and post back with the result. -- matthew Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a écrit : > > I'm working with the following code. I included some tests to make it > > easy to see--if you run the code--what troubles I'm having. > > > > Can some one *please* splain me why str(obj) works but not print obj, > > May have something to do with escape chars... I tried with: >def __str__(self): > return repr(self) > > and it did the trick for printing. Now it may have other side-effects, I > don't know. > > > and why obj.__int__() works, but not int(obj). >\ > I've added tracing to __int__, and it isn't called. FWIW, str type has > no attribute __int__, so I guess there's something special in the > implementation here. > > > I just don't get it. :( > > FWIW, you have another problem to solve: > > >>> b1 = Byte(1) > >>> b1 > '\x01' > >>> b1.__int__() > 1 > >>> b2 = Byte(2) > >>> b2 > '\x02' > >>> b2.__int__() > 2 > >>> b1.__int__() > 2 > > cf below... > > (snip) > > > > > > import struct > > class Byte(str): # Implement Bytes as str for easy adding and joining > (snip) > > def __new__(self, val): > > Actually, __new__ is a static method, and it takes the class as first > argument. So... > > > if type(val) == str and not val.isdigit(): > > val = struct.unpack('B', val) #ensure input is valid struct > > byte > > self._byte = struct.pack('B', val) > > self._int = int(val) > > .. since the name "self" really references the class, not the instance, > the two previous lines (re)bind *class* attributes "_byte" and "_int" to > class Byte. > > > return str.__new__(self, self._byte) > > What you want here is to first create the instance, and only then bind > to it: > > def __new__(cls, val): > if type(val) == str and not val.isdigit(): > val = struct.unpack('B', val) > _byte = struct.pack('B', val) > self = str.__new__(cls, _byte) > self._byte = _byte > self._int = int(val) > return self > > (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
mystilleef wrote: > I decided to change the name of an attribute. Problem is I've used the > attribute in several places spanning thousands of lines of code. If I > had encapsulated the attribute via an accessor, I wouldn't need to do > an unreliable and tedious search and replace accross several source > code files to achieve my goal. I could simply change the name of the > attribute and move on. Well, I'm glad python has properties. It's a > feature that should be advertised more, especially for large scale > python development. Ergh, I don't see how the name-changing of an attribute makes any difference with respect to the application of getters/setters. Where is the difference in searching my_attribute vs. getMyAttribute throughout your code? Or do you mean that you changed def getFoo(self): return self.foo to something like def getFoo(self): return self.fooSomething ? I'd say that whatever reasoning which inspired you to change foo to fooSomething applies to getFoo as well. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
Fredrik Lundh <[EMAIL PROTECTED]> wrote: >Ant wrote: >> It seems that there must be a way to use eval safely, as there are >> plenty of apps that embed python as a scripting language - and what's >> the point of an eval function if impossible to use safely, and you have >> to write your own Python parser!! >embedding python != accepting scripts from anywhere. And also using eval (or exec or execfile) != accepting scripts from anywhere. You've got to consider where the data can have come from and what (broad) context it's being eval()'d in. Last time I did something like this was with execfile for advanced configuration of a server, and if a hostile party were in a position to inject malicious code into *that* then subversion of our program would be the least of anyone's concern. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
Steven D'Aprano <[EMAIL PROTECTED]> wrote: >Of course, another right way would be to have mutable strings in Python. What significant advantage would mutable strings have over StringIO and wrapping list manipulation in list(s) and ''.join(l). Other than that pleasing symmetry with sets/frozensets etc. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: split a line, respecting double quotes
Jim <[EMAIL PROTECTED]> wrote: >Is there some easy way to split a line, keeping together double-quoted >strings? > >I'm thinking of > 'a b c "d e"' --> ['a','b','c','d e'] >. I'd also like > 'a b c "d \" e"' --> ['a','b','c','d " e'] >which omits any s.split('"')-based construct that I could come up with. >>> csv.reader(StringIO.StringIO('a b c "d e"'), delimiter=' ').next() ['a', 'b', 'c', 'd e'] It can't quite do the second one, but: >>> csv.reader(StringIO.StringIO('a b c "d "" e"'), delimiter=' ').next() ['a', 'b', 'c', 'd " e'] isn't far off. On the other hand, it's kind of a stupid solution. I'd really go with shlex as someone suggested up thread. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
> Of course, another right way would be to have mutable strings in Python. > I understand why strings need to be immutable in order to work with dicts, > but is there any reason why (hypothetical) mutable strings should be > avoided in situations where they aren't needed as dictionary keys? Python > has mutable lists and immutable tuples, mutable sets and immutable frozen > sets, but no mutable string type. What's wrong about arrays of chars? Diez -- http://mail.python.org/mailman/listinfo/python-list
Full splitting of a file's pathname
I know about os.path.split(), but Is there any standard function for "fully" splitting a file's pathname? A function that is the opposite of the os.path.join() function? For example: >>> ret = myster_function(./foo/bar/moo/lar/myfile.txt) >>> print ret ['.', 'foo', 'bar', 'moo', 'lar', 'myfile.txt'] In the meanwhile, I'll do this by hand. I'm just curious if there is a standard way to do this. -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
Diez B. Roggisch wrote: > > Of course, another right way would be to have mutable strings in Python. > > I understand why strings need to be immutable in order to work with dicts, > > but is there any reason why (hypothetical) mutable strings should be > > avoided in situations where they aren't needed as dictionary keys? Python > > has mutable lists and immutable tuples, mutable sets and immutable frozen > > sets, but no mutable string type. > > What's wrong about arrays of chars? Arrays of chars are dangerous. If you insist, use Python lists of Python "chars" (strings of length 1). If you really want a mutable string type, there's nothing in python that keeps you from writting one yourself. You just have to be more careful than you would be in C++, because your MutableString type would always be passed by reference to functions, and so you'd have to be very careful to copy it unless you want weird, unfindable bugs to crop up in your program. -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
> As Fredrik points out, embedded Python isn't the same as running > untrusted code. The reality is, Python has not been designed for running > untrusted code safely. So how do python app's typically embed python? For example things like Zope and idle are scripted using Python - presumably they restrict the execution of the scripts to a restricted set of modules/objects - but how is this done? Perhaps idle doesn't require safety from untrusted code, but surely Zope does. So there must be some way of executing arbitrary untrusted code in an app within some kind of sandbox... -- http://mail.python.org/mailman/listinfo/python-list
Python-2.5beta1 crash
I'm testing ReportLab against Python-2.5beta1 and am getting some kind of problem as below === C:\Python24\reportlab\test>\python25\python runAll.py .C:\Python24\reportlab\test\test_docstrings.py:54: ImportWarning: Not importing directory 'C:\python25\reportlab\tools\utils': missing __init__.py module = __import__(mName) C:\Python24\reportlab\test\test_docstrings.py:54: ImportWarning: Not importing d irectory 'C:\python25\reportlab\tools\pythonpoint\demos': missing __init__.py module = __import__(mName) C:\Python24\reportlab\test\test_docstrings.py:54: ImportWarning: Not importing d irectory 'C:\python25\reportlab\docs': missing __init__.py module = __import__(mName) C:\Python24\reportlab\test\test_docstrings.py:54: ImportWarning: Not importing d irectory 'C:\python25\reportlab\demos': missing __init__.py module = __import__(mName) Fatal Python error: non-string found in code slot This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. === First off there may be a bunch of other C extensions involved including PIL, but I built them all against this beta. What should I do to refine the error? Do I start with trying to establish which of the tests is guilty or build from source in debug mode and attempt to find the problem from below. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
> Bruno Desthuilliers <[EMAIL PROTECTED]> (BD) wrote: >BD> Actually, and AFAIK, len(obj) = lambda obj : obj.__len__(). You mean: len = lambda obj : obj.__len__(). -- Piet van Oostrum <[EMAIL PROTECTED]> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Joachim Durchholz wrote: > Chris Smith schrieb: > > For example, I wrote that example using variables of type int. If we > > were to suppose that we were actually working with variables of type > > Person, then things get a little more complicated. We would need a few > > (infinite classes of) derived subtypes of Person that further constrain > > the possible values for state. For example, we'd need types like: > > > > Person{age:{18..29}} > > > > But this starts to look bad, because we used to have this nice > > property called encapsulation. To work around that, we'd need to > > make one of a few choices: [...] (c) invent some kind of generic > > constraint language so that constraints like this could be expressed > > without exposing field names. [...] Choice (c), though, looks a > > little daunting. > > That's not too difficult. > Start with boolean expressions. > If you need to check everything statically, add enough constraints that > they become decidable. I'm not sure I understand. Could you elaborate? > For the type language, you also need to add primitives for type > checking, and if the language is stateful, you'll also want primitives > for accessing earlier states (most notably at function entry). Again I'm not entirely clear what this means. Are you talking about pre/post conditions, or are you talking about having the constraint language itself be something other than functional? Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: Full splitting of a file's pathname
I don't know if it's "standard," but why not just: dir = './foo/bar/moo/lar/myfile.txt' dir.split('/') ['.', 'foo', 'bar', 'moo', 'lar', 'myfile.txt'] rd -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
tac-tics wrote: > > Diez B. Roggisch wrote: >> > Of course, another right way would be to have mutable strings in >> > Python. I understand why strings need to be immutable in order to work >> > with dicts, but is there any reason why (hypothetical) mutable strings >> > should be avoided in situations where they aren't needed as dictionary >> > keys? Python has mutable lists and immutable tuples, mutable sets and >> > immutable frozen sets, but no mutable string type. >> >> What's wrong about arrays of chars? > > Arrays of chars are dangerous. If you insist, use Python lists of > Python "chars" (strings of length 1). Why are they more dangerous than a self-written mutable string? > If you really want a mutable string type, there's nothing in python > that keeps you from writting one yourself. You just have to be more > careful than you would be in C++, because your MutableString type would > always be passed by reference to functions, and so you'd have to be > very careful to copy it unless you want weird, unfindable bugs to crop > up in your program. I don't buy that. You are right about the dangers - but I fail to see where C++ gives you any protection from these pitfalls. And what disqualifies an array of characters in python that exists and has all the methods I can think of for a mutable string. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
RE: [wwwsearch-general] ClientForm request re ParseErrors
hi john... this is in regards to the web/parsing/factory/beautifulsoup to reiterate, i have python 2.4, mechanize, browser, beatifulsoup installed. i have the latest mech from svn. i'm getting the same err as reported by john t. the code/err follows.. (i can resend the test html if you need) any thoughts/pointers/etc would be helpful... thanks -bruce test code #! /usr/bin/env python #test python script import re import libxml2dom import urllib import urllib2 import sys, string #import numarray import httplib from mechanize import Browser, RobustFactory import mechanize import BeautifulSoup # # Parsing App Information # datafile tfile = open("stanford.dat", 'wr+') cj = mechanize.CookieJar() br = Browser() if __name__ == "__main__": # main app # # start trying to get the stanford pages cj = mechanize.CookieJar() br = Browser(factory=RobustFactory()) fh = open('axess.dat') s = fh.read() fh.close() br.open("file:///home/test/axess.dat") . . . . err/output Traceback (most recent call last): File "./axess.py", line 45, in ? br.open("file:///home/test/axess.dat") File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 130, in open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 170, in _mech_open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 213, in set_response File "build/bdist.linux-i686/egg/mechanize/_html.py", line 577, in set_response File "build/bdist.linux-i686/egg/mechanize/_html.py", line 316, in __init__ File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 1326, in __init__ BeautifulStoneSoup.__init__(self, *args, **kwargs) File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 973, in __init__ self._feed() File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 987, in _feed smartQuotesTo=self.smartQuotesTo) File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 1580, in __init__ u = self._convertFrom(proposedEncoding) File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 1614, in _convertFrom proposed = self.find_codec(proposed) File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 1731, in find_codec return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ File "/usr/lib/python2.4/site-packages/BeautifulSoup.py", line 1740, in _codec codecs.lookup(charset) TypeError: lookup() argument 1 must be string, not bool is this where i've seen references to integrating Beautifulsoup in the wb browsing app? -bruce -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of John J Lee Sent: Monday, July 10, 2006 2:29 AM To: [EMAIL PROTECTED] Cc: python-list@python.org Subject: RE: [wwwsearch-general] ClientForm request re ParseErrors On Sun, 9 Jul 2006, bruce wrote: [...] > sgmllib.SGMLParseError: expected name token at ' > > partial html > --- > > > Action="/servlets/iclientservlet/a2k_prd/?ICType=Panel&Menu=SA_LEARNER_SERVI > CES&Market=GBL&PanelGroupName=CLASS_SEARCH" autocomplete=off> > > > [...] You don't include the HTML mentioned in the exception message (''. The comment sgmllib is complaining about is missing the '--'. You can work around bad HTML using the .set_data() method on response objects and the .set_response() method on Browser. Call the latter before you call any other methods that would require parsing the HTML. r = br.response() r.set_data(clean_html(br.get_data())) br.set_response(r) You must write clean_html yourself (though you may use an external tool to do so, of course). Alternatively, use a more robust parser, e.g. br = mechanize.Browser(factory=mechanize.RobustFactory()) (you may also integrate another parser of your choice with mechanize, with more effort) John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Browser Pygame Plug-in?
That's interesting, Ben. So we'd be better off making a new library similiar to Pygame in functionality but designed from the ground up to work in a browser. I guess that XPCOM technology that someone mentioned might be the way to go? On 10 Jul 2006 03:54:33 -0700, Ben Sizer <[EMAIL PROTECTED]> wrote: > Gregory Piñero wrote: > > I was just idley curious on what it would take to make a web plug-in > > for Pygame. I'm picturing it working the way my browser currently > > shows flash games. Is such an idea even possible? Has anyone > > attempted this? > > I doubt you can get PyGame to work this way - at least, not without > some significant hacking around in the source - since PyGame relies on > the underlying SDL library, and from my experience with it, I can't see > it playing well with a browser whatsoever. I think SDL would have to > acquire a new backend to translate input to the plugin into their event > structure, and would require some way of creating an appropriate video > mode that can draw to a browser's window, etc. Java applets and Flash > are built for this purpose whereas PyGame is built on a technology that > was designed for programs that have their own window and tend to > capture all the OS's input. > > -- > Ben Sizer > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gregory Piñero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) -- http://mail.python.org/mailman/listinfo/python-list
RE: Full splitting of a file's pathname
Unless it's the sort of operating system that uses something like : Sys$disk:[foo.bar.moo.lar]myfile.txt (VaxVMS, from quite a few years ago) And if I recall, the parsing function provided would also separate the extension from the main part of the file's name. Unhelpfully, Richard. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of BartlebyScrivener Sent: 10 July 2006 15:52 To: python-list@python.org Subject: Re: Full splitting of a file's pathname I don't know if it's "standard," but why not just: dir = './foo/bar/moo/lar/myfile.txt' dir.split('/') ['.', 'foo', 'bar', 'moo', 'lar', 'myfile.txt'] rd -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
On Mon, 10 Jul 2006 15:23:36 +0100, Sion Arrowsmith wrote: > Steven D'Aprano <[EMAIL PROTECTED]> wrote: >>Of course, another right way would be to have mutable strings in Python. > > What significant advantage would mutable strings have over StringIO > and wrapping list manipulation in list(s) and ''.join(l). Other than > that pleasing symmetry with sets/frozensets etc. Some algorithms (e.g. genetic algorithms) have natural implementations in terms of mutable strings. StringIO is more like a kind of file than a kind of string. It has no methods for upper/lowercase, searching, etc. While files do have random access, they don't have random access insertion and deletion like lists or hypothetical mutable strings, so StringIO is no replacement at all. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Chris Smith wrote: > Marshall <[EMAIL PROTECTED]> wrote: > > Chris Smith wrote: > > > > > > But this starts to look bad, because we used to have this nice property > > > called encapsulation. To work around that, we'd need to make one of a > > > few choices: (a) give up encapsulation, which isn't too happy; (b) rely > > > on type inference for this kind of stuff, and consider it okay if the > > > type inference system breaks encapsulation; or (c) invent some kind of > > > generic constraint language so that constraints like this could be > > > expressed without exposing field names. Choice (b) is incomplete, as > > > there will often be times when I need to ascribe a type to a parameter > > > or some such thing, and the lack of ability to express the complete type > > > system will be rather limiting. Choice (c), though, looks a little > > > daunting. > > > > Damn the torpedoes, give me choice c! > > You and I both need to figure out when to go to sleep. :) Work's gonna > suck tomorrow. It's never been a strong point. Made worse now that my daughter is one of those up-at-the-crack-of-dawn types, and not old enough to understand why it's not nice to jump on mommy and daddy's bed while they're still asleep. But aren't you actually a time zone or two east of me? > > I've been saying for a few years now that encapsulation is only > > a hack to get around the lack of a decent declarative constraint > > language. > > Choice (c) was meant to preserve encapsulation, actually. I think > there's something fundamentally important about information hiding that > can't be given up. Hypothetically, say I'm writing an accounting > package and I've decided to encapsulate details of the tax code into one > module of the application. Now, it may be that the compiler can perform > sufficient type inference on my program to know that it's impossible for > my taxes to be greater than 75% of my annual income. So if my income is > stored in a variable of type decimal{0..10}, then the return type of > getTotalTax may be of type decimal{0..75000}. Type inference could do > that. The fields of an object/struct/what have you are often hidden behind a method-based interface (sometimes callled "encapsulated") only because we can't control their values otherwise. (The "exposing the interface" issue is a non-issue, because we're exposing some interface or another no matter what.) The issue is controlling the values, and that is better handled with a declarative constraint language. The specific value in the fields aren't known until runtime. However for a function, the "fields" are the in and out parameters. The specific values in the relation that the function is aren't known until runtime either, (and then only the subset for which we actually perform computation.) Did that make sense? > But the point here is that I don't WANT the compiler to be able to infer > that, because it's a transient consequence of this year's tax code. I > want the compiler to make sure my code works no matter what the tax code > is. The last thing I need to to go fixing a bunch of bugs during the > time between the release of next year's tax code and the released > deadline for my tax software. At the same time, though, maybe I do want > the compiler to infer that tax cannot be negative (or maybe it can; I'm > not an accountant; I know my tax has never been negative), and that it > can't be a complex number (I'm pretty sure about that one). I call that > encapsulation, and I don't think that it's necessary for lack of > anything; but rather because that's how the problem breaks down. There's some significant questions in my mind about how much of a constraint language would be static and how much would be runtime checks. Over time, I'm starting to feel like it should be mostly runtime, and only occasionally moving into compile time at specific programmer request. The decidability issue comes up. Anyone else? > Just expressing all of that in a method signature looks interesting > enough. If we start adding abstraction to the type constraints on > objects to support encapsulation (as I think you'd have to do), then > things get even more interesting. There are certainly syntactic issues, but I believe these are amenable to the usual approaches. The runtime/compile time question, and decidability seem bigger issues to me. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
On Mon, 10 Jul 2006 16:27:03 +0200, Diez B. Roggisch wrote: >> Of course, another right way would be to have mutable strings in Python. >> I understand why strings need to be immutable in order to work with dicts, >> but is there any reason why (hypothetical) mutable strings should be >> avoided in situations where they aren't needed as dictionary keys? Python >> has mutable lists and immutable tuples, mutable sets and immutable frozen >> sets, but no mutable string type. > > What's wrong about arrays of chars? Nice suggestion. However, I should point out that the methods available to array.array('c') are quite limited compared to the methods available to strings. Still, it would make a good basis to start with, and far better than my initial thought of a list of chars. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
> Antoon Pardon <[EMAIL PROTECTED]> (AP) wrote: >AP> I'm sorry to see you missed it, but since I had answered this already in >AP> this thread I saw at the moment no need to repeat it: There would be no >AP> value for c, the line would raise an UnboundLocalError. OK. That could have been chosen. But that would mean that instead of c.a = b, where c is bound in a non-local scope, you have to write something like: cc = c cc.a = b I don't find that useful. -- Piet van Oostrum <[EMAIL PROTECTED]> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a type error?
Marshall schrieb: > Joachim Durchholz wrote: >> Chris Smith schrieb: >>> For example, I wrote that example using variables of type int. If we >>> were to suppose that we were actually working with variables of type >>> Person, then things get a little more complicated. We would need a few >>> (infinite classes of) derived subtypes of Person that further constrain >>> the possible values for state. For example, we'd need types like: >>> >>> Person{age:{18..29}} >>> >>> But this starts to look bad, because we used to have this nice >>> property called encapsulation. To work around that, we'd need to >>> make one of a few choices: [...] (c) invent some kind of generic >>> constraint language so that constraints like this could be expressed >>> without exposing field names. [...] Choice (c), though, looks a >>> little daunting. >> That's not too difficult. >> Start with boolean expressions. >> If you need to check everything statically, add enough constraints that >> they become decidable. > > I'm not sure I understand. Could you elaborate? Preconditions/postconditions can express anything you want, and they are an absolutely natural extensions of what's commonly called a type (actually the more powerful type systems have quite a broad overlap with assertions). I'd essentially want to have an assertion language, with primitives for type expressions. >> For the type language, you also need to add primitives for type >> checking, and if the language is stateful, you'll also want primitives >> for accessing earlier states (most notably at function entry). > > Again I'm not entirely clear what this means. Are you talking > about pre/post conditions, Yes. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: Full splitting of a file's pathname
tac-tics wrote: > I know about os.path.split(), but Is there any standard function for > "fully" splitting a file's pathname? A function that is the opposite of > the os.path.join() function? For example: > > >>> ret = myster_function(./foo/bar/moo/lar/myfile.txt) > >>> print ret > ['.', 'foo', 'bar', 'moo', 'lar', 'myfile.txt'] > > In the meanwhile, I'll do this by hand. I'm just curious if there is a > standard way to do this. Simple function using os.path.split (so it should be fairly compatible): def split(path): h,t = os.path.split(path) if h == path: return [h] else: return split(h) + [t] You could throw in os.path.splitdrive and os.path.splitunc, if you wanted to be really complete. Iain -- http://mail.python.org/mailman/listinfo/python-list
PIL - Transparency Nightmares
I'm trying to make a simple script which attaches watermarks to every image in one directory and saves the output image to another. However, while I understand (in theory at least) what I need to be doing, I can't figure out where to go from here. First of all, I have a watermark image and a list of small images around 120px squared. The watermark uses alpha transparency, so the background is transparent and the anti-aliased text is partially transparent. For each image, I crop the watermark to the same size as the image. Now all I need to do is paste the watermark over the old image with respect to its transparency. I've tried Image.blend(), Image.composite(), and im.paste(), but none of them seem to do exactly what I want. What am I missing here? -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Piet van Oostrum wrote: >>Bruno Desthuilliers <[EMAIL PROTECTED]> (BD) wrote: > > >>BD> Actually, and AFAIK, len(obj) = lambda obj : obj.__len__(). > > > You mean: len = lambda obj : obj.__len__(). yes, of course - not enough caffein, I guess... Thanks -- 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
Mechanize/Browser question
hi... i can do the following br = Browser br.open("www.yahoo.com") br.open("file:///foo") but can i do s = "..." qualified html text br.open(s) i'm curious, if i have html from someother source, is there a way to simply get it into the "Browser" so i can modify it... thanks -bruce -- http://mail.python.org/mailman/listinfo/python-list
ANN: eGenix mxODBC Zope Database Adapter 1.0.10
ANNOUNCEMENT EGENIX.COM mxODBC Zope Database Adapter Version 1.0.10 Usable with Zope and the Plone CMS. Available for Zope 2.3 through 2.10 on Windows, Linux, Mac OS X, Solaris and FreeBSD INTRODUCTION The eGenix mxODBC Zope Database Adapter allows you to easily connect your Zope or Plone installation to just about any database backend on the market today, giving you the reliability of the commercially supported eGenix product mxODBC and the flexibility of the ODBC standard as middle-tier architecture. The mxODBC Zope Database Adapter is highly portable, just like Zope itself and provides a high performance interface to all your ODBC data sources, using a single well-supported interface on Windows, Linux, Mac OS X, Solaris and FreeBSD. This makes it ideal for deployment in ZEO Clusters and Zope hosting environments where stability and high performance are a top priority, establishing an excellent basis and scalable solution for your Plone CMS. NEWS We are pleased to announce a new version of our mxODBC Zope DA product. The Zope DA now fully supports 64-bit ODBC. A problem with 64-bit integers has been resolved in this release. Also new in this release is support for the upcoming Zope 2.10. We have successfully tested the mxODBC Zope DA with the latest beta of the upcoming Zope version. UPGRADING If you have already bought mxODBC Zope DA 1.0.x licenses, you can use these license for the 1.0.10 version as well. There is no need to buy new licenses. The same is true for evaluation license users. MORE INFORMATION For more information on the mxODBC Zope Database Adapter, licensing and download instructions, please visit our web-site: http://zope.egenix.com/ You can buy mxODBC Zope DA licenses online from the eGenix.com shop at: http://shop.egenix.com/ Thank you, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 10 2006) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
mystilleef wrote: > I decided to change the name of an attribute. Problem is I've used the > attribute in several places spanning thousands of lines of code. If I > had encapsulated the attribute via an accessor, I wouldn't need to do > an unreliable and tedious search and replace find and grep are usually mostly reliable for this kind of tasks. > accross several source > code files to achieve my goal. I could simply change the name of the > attribute and move on. Why did you change the name of the attribute ? If it was to better reflect the semantic, then it's a change in the API and getters/setters wouldn't have help (you'd have to do the same "tedious and unreliable" search/replace dance). If it's about implementation, then it was time to use a property - that's what they are for. -- 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
Detecting socket connection failure
Hi All, I've tried to RTFM this and am having no luck.First off, I am using Mac OSX 10.4.7 with python 2.4.2 from fink. I am trying to connect to a server that should be rejecting connections and I was surprised when it did not throw an exception or do something otherwise equally nasty. It just connects and never returns any data. First, the proof that something is there and rejecting the connection (or is it that this thing actually accepts the connection and then drops it?)... telnet localhost 31414 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host. Now if I fire up ipython and try to connect... In [1]: import socket, select In [2]: remote = socket.socket(socket.AF_INET,socket.SOCK_STREAM) In [3]: remote.connect(('localhost',31414)) In [4]: remote.recv(200) Out[4]: '' In [5]: r,w,e=select.select([remote],[remote],[remote],1) In [6]: print r,w,e [] [] [] In [7]: remote.recv(200) Out[7]: '' So it looks like it will for ever say that it is ready for read and write, but really is not. How do I detect this case? The recv may really not have any data for a long time, so a recv of no bytes is not a way to test the connection status. This is probably a FAQ, but I can't figure it out. Thanks!! -kurt -- http://mail.python.org/mailman/listinfo/python-list
Re: xml aggregator
Thank you so much, it works and it rocks ! bad thing i need ot figure out is why mozilla cannot parse my xsl sheet, but it works in IE ( most of my users are using IE) so the module u wrote is to top up element tree with Xpath capabilities, is it? Does the new element tree does that? which one is the most appropriate? btw, are u french? Regards, Nassim -- http://mail.python.org/mailman/listinfo/python-list
Re: function that modifies a string
Simon Forman wrote: > greenflame wrote: > > Jason wrote: > > > > > > There /are/ a few hacks which will do what you want. However, if you > > > really need it, then you probably need to rethink your program design. > > > Remember, you can't change a string since a string is immutable! You > > > can change a variable to bind to another string. In the following > > > example, s gets rebound to the new string while t keeps the original > > > string value: > > > > > > >>> def changeString(varName): > > > ... globalDict = globals() > > > ... globalDict[varName] = '||' + globalDict[varName] + '>>' > > > ... return > > > ... > > > >>> s = 'Char' > > > >>> t = s > > > >>> changeString('s') > > > >>> s > > > '||Char>>' > > > >>> t > > > 'Char' > > > > > > Further note that this only affects variables in the global scope. I > > > hope this helps! > > > > > > --Jason > > > > Ok so let me see if I understand. The globalDict is just a dictionary > > containing the name of the global variables as the keys and their > > values as the values of the dictionary? Thus the inputed variable is > > treated like a global variable? > > The answer to your first question is yup! You've got it. That's what > the globals() function returns. (There is also a function locals() > that returns a similar dict but for locals.) > > The answer to your second question is no. The inputed *name* (the > changeString() function must be passed a string, not a variable) must > be the name of an object in the global scope for the function to work. > > You almost certainly want to use a function like the thefunc() function > that Jason posted. > > One other thing, you could define it like so: > > def thefunc(s): > return '||%s>>' % s > > > Peace, > ~Simon Certainly. I do want to add a warning: do not modify the dictionary returned from locals(). Please note the warning given at "http://docs.python.org/lib/built-in-funcs.html#l2h-45";. --Jason -- http://mail.python.org/mailman/listinfo/python-list
compiling 2.3.5 on ubuntu
(Apologies if this appears twice. I posted it yesterday and it was held due to a 'suspicious header') I'm having a hard time trying to get a couple of tests to pass when compling Python 2.3.5 on Ubuntu Server Edition 6.06 LTS. I'm sure it's not too far removed from the desktop edition but, clearly, I need to tweak something or install some missling libs. uname -a Linux server 2.6.15-23-server #1 SMP Tue May 23 15:10:35 UTC 2006 i686 GNU/Linux When I compile Python I get these failing 4 skips unexpected on linux2: test_dbm test_mpz test_bsddb test_locale I've got libgdbm-dev and libgdbm3 packages installed. Help! -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL - Transparency Nightmares
I RTFM harder, and found that paste with an image mask (using the watermark as the mask) does the trick. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Steven Bethard a écrit : > The advantage of a functional form over a method shows up when you write > a function that works on a variety of different types. Below are > implementations of "list()", "sorted()" and "join()" that work on any > iterable and only need to be defined once:: > > [... skipped ...] > > Now, by providing these as functions, I only have to write them once, > and they work on *any* iterable, including some container object that > you invent tomorrow. Yep. Rubyphiles would probably define these 3 methods in a "module" Iterable and "mix" it in their brand new container classes. These classes then automatically have list, sorted and join *as methods*. Guess you could use this kind of trick in Python if you can live with heavy *and* implicit surgery of the inheritance chain ;) Cheers, SB -- http://mail.python.org/mailman/listinfo/python-list