Re: hi
On Fri, Sep 14, 2012 at 12:09 AM, alex23 wrote: > On Sep 14, 3:44 pm, Dwight Hutto wrote: >> CEO:http://www.hitwebdevelopment.com > > I don't know what gives more of a negative impression of your > business, your acting like a tedious douchebag or the website itself. Holy cow, that's the website of a web development company? Hopefully the brokenness of it (e.g., the "Contact Information" link leads to a 404; how are potential clients supposed to contact you?), the total lack of content, and the overall lack of graphic design are because it's a prototype and hasn't been launched yet (so why are you advertising it in your sig?) I can't see any such excuse for the 60-MB poorly rendered animated GIF on the front page or the embedded background music (that thankfully doesn't seem to play in Firefox). I don't want to be nasty about it, but as a web development company you have to consider that a website like that is going to drive away clients. Also, Dwight, you might want to reconsider the name of your company. Googling for "hit web development" turns up nothing about you, but a lot of hits about a defunct Utah company called "HIT Web Design" that apparently was running a scam and generated a lot of bad press. If it were me, I wouldn't want potential clients googling the company, seeing all that, and thinking that it's the same company or that there might be a relationship. -- http://mail.python.org/mailman/listinfo/python-list
Re: hi
On Fri, Sep 14, 2012 at 2:09 AM, alex23 wrote: > On Sep 14, 3:44 pm, Dwight Hutto wrote: >> CEO:http://www.hitwebdevelopment.com > > I don't know what gives more of a negative impression of your > business, your acting like a tedious douchebag or the website itself. > -- > http://mail.python.org/mailman/listinfo/python-list This is more than likely a projection of yourself onto others. And this just makes you a gossiping gabby, who likes to bring people down anytime they meet someone, instead of letting them make their own opinions. Completely OT for this discussion. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
On Fri, Sep 14, 2012 at 11:14 AM, Dwight Hutto wrote: > [over a hundred quoted lines snipped] > And if you look at the above in gmail, you can see the ...'s that when > not clicked, won't show some of the responses I leave just above, and > it clips my signature line as well. That's a Gmail feature, and a sop to people who can't take a moment to trim quoted text. Taking your above post as an example, there were (according to my calculation) 111 lines of text that had already been sent, being _re_sent in your post. Not everyone uses Gmail. And not everyone runs off 100Mbit internet connections. And even if everyone were to use Gmail off 100Mbit internet connections, I would still recommend trimming the text, because Gmail gives you precisely two options: all the way collapsed, or all the way expanded. If I want to read more context, I get _all_ the context. That's still not all that useful. Right while you make a post is the best time to decide how much context is needed. Spend just a few seconds thinking about how much to trim, and you can make things easier for everyone who reads your post, whether it be on python-list, comp.lang.python, or one of several web-accessible archives. And remember, this is for posterity, so be honest. How do you feel? Interesting... ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: hi
On Fri, Sep 14, 2012 at 3:08 AM, Ian Kelly wrote: > On Fri, Sep 14, 2012 at 12:09 AM, alex23 wrote: >> On Sep 14, 3:44 pm, Dwight Hutto wrote: >>> CEO:http://www.hitwebdevelopment.com >> >> I don't know what gives more of a negative impression of your >> business, your acting like a tedious douchebag or the website itself. > > Holy cow, that's the website of a web development company? Hopefully > the brokenness of it (e.g., the "Contact Information" link leads to a > 404 I'm constructing now as we speak, thanks for the note about placing in special 404 error pages. I do more than just this. I spend too much time taking the time to explain things that were blown out of proportion to people like you. And I think there might be a few avatars one person might post under. ; how are potential clients supposed to contact you?), the total > lack of content, and the overall lack of graphic design are because > it's a prototype and hasn't been launched yet (so why are you > advertising it in your sig?) For constructive criticism., and I like how it's starting to come together. People have different tastes. I can't see any such excuse for the > 60-MB poorly rendered animated GIF on the front page or the embedded I'm reducing that down later. It was originally 111 done in blender, and it's still a rough draft site. I don't mind the criticism, because I'm only placing it in my sig at this point, as I'm constructing it. > background music (that thankfully doesn't seem to play in Firefox). I > don't want to be nasty about it, but as a web development company you > have to consider that a website like that is going to drive away > clients. Why, because of a few graphics, and some music, that YOU don't happen to like. Statistically speaking, you're apparently not my target demographic. > > Also, Dwight, you might want to reconsider the name of your company. > Googling for "hit web development" turns up nothing about you, but a > lot of hits about a defunct Utah company called "HIT Web Design" that > apparently was running a scam and generated a lot of bad press. If it > were me, I wouldn't want potential clients googling the company, > seeing all that, and thinking that it's the same company or that there > might be a relationship. No, none at all. I came up with this name, and overtime, it should overshadow what the other company did. I don't see how you can go wrong, when the client tells you what they want to see, or here on their site or app. > http://mail.python.org/mailman/listinfo/python-list -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: [SOLVED] Least-lossy string.encode to us-ascii?
2012/9/14 Tim Chase : > On 09/13/12 16:44, Vlastimil Brom wrote: >> >>> import unicodedata >> >>> unicodedata.normalize("NFD", u"serviço móvil").encode("ascii", >> >>> "ignore").decode("ascii") >> u'servico movil' > > Works well for all the test-cases I threw at it. Thanks! > > -tkc > > Hi, I am glad, it works, but I agree with the other comments, that it would be preferable to keep the original accented text, if at all possible in the whole processing. The above works by decomposing the accented characters into "basic" characters and the bare accents (combining diacritics) using normalize() and just striping anything outside ascii in encode("...", "ignore") This works for "combinable" accents, and most of the Portuguese characters outside of ascii appear to fall into this category, but there are others as well. E.g. according to http://tlt.its.psu.edu/suggestions/international/bylanguage/portuguese.html there are at least ºª«»€, which would be lost completely in such conversion. ª (dec.: 170) (hex.: 0xaa) # FEMININE ORDINAL INDICATOR º (dec.: 186) (hex.: 0xba) # MASCULINE ORDINAL INDICATOR You can preprocess such cases as appropriate before doing the conversion, e.g. just: >>> u"ºª«»€".replace(u"º", u"o").replace(u"ª", u"a").replace(u"«", >>> u'"').replace(u"»", u'"').replace(u"€", u"EUR") u'oa""EUR' >>> or using a more elegant function and the replacement lists (eventually handling other cases as well). regards, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
> honest. How do you feel? Interesting... > Um, I guess like an inconsiderate bandwidth hog, but from now on I'll trim more text. First it was too little, and now it's too much. I just tend to cut out some or all depending on the scope of the conversation. If I just hit reply all, and send it out, it's not intentionally to use all of the text, and utilize the extra space, it's just a response. If the conversation is kind of just a few people, then I trim pretty much everything, which apparently set a guy name mark off, who I was polite to, but I'm not going to get slammed for a few simple posting mistakes, and more than likely a few of his aliases, or the group he tends to cheer up with. It's just a mailing list, lighten up because mistakes in posting will happen, even by accident. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: hi
Great to meet you, thank you for your advise 2012/9/14 Dwight Hutto > > You'll love it here. It's always amusing. > > But remember to hit reply all > > Unless you might want to contact someone personally. Some don't mind, > and some may complain. Me I don't care either way. > > Great to meet you though. Hope you find the it educationally stimulating. > > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com > -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
>> I think you're referring to a play on words(ramit). > > Using foreign names derogatively is a common tactic of the racist. Not really. But nice spin on my pun to make me look bad. Keep trying, and maybe you'll come up with an insult/ propaganda that's less obvious to the viewer that you're a liar, and a person who couldn't end this with out throwing a blatant race card. It's similar to if I said, this is real 'queer' of you to do ya big pansy, and next you'll be calling me a homophobe. Try harder, because no one would ever believe I was a racist, and if they did, it's an uninformed decision based off of cherry picken phrases out of context. Very text book propaganda of you though. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
On Fri, Sep 14, 2012 at 5:49 PM, Dwight Hutto wrote: >> honest. How do you feel? Interesting... >> > Um, I guess like an inconsiderate bandwidth hog, but from now on I'll > trim more text. What you may have missed was that that was a quote from Princess Bride. Don't take it personally :) > First it was too little, and now it's too much. > > I just tend to cut out some or all depending on the scope of the conversation. > > If I just hit reply all, and send it out, it's not intentionally to > use all of the text, and utilize the extra space, it's just a > response. It's all a question of courtesy, and there's no hard-and-fast rules. But as a simple rule of thumb, assume that your post is going to be read completely without any surrounding context; will it be comprehensible? > If the conversation is kind of just a few people, then I trim pretty > much everything, which apparently set a guy name mark off, who I was > polite to, but I'm not going to get slammed for a few simple posting > mistakes, and more than likely a few of his aliases, or the group he > tends to cheer up with. There's actually no such thing as a conversation of just a few people, on a big list like this. Sure, there may be only a few contributors, but there are thousands - maybe millions - of readers. You're not being slammed, though. What you're seeing is a community doing its best to maintain itself. If we all sit silently, wishing our hardest that everyone would quote nicely, cite nicely, post without trolling, and be helpful, will it happen? (Those familiar with the Bible may note a similarity with some comments in the epistle of James.) There are two ways to ensure that the community upholds its standards: Kicking out everyone who doesn't measure up, or explaining to people and inviting them to participate. The first is a great way to have a tiny community with no growth. The second... is what you're seeing. :) Of course, there's a third option, which is to simply ignore everything and try to get on with life. That basically amounts to kicking _yourself_ out of the community, because you'll quickly give up on a forum in which everyone posts sloppily. And I'm sure you don't want all the experts to do that, because you're then left with a "blind leading the blind" mailing list... not particularly conducive to good code! > It's just a mailing list, lighten up because mistakes in posting will > happen, even by accident. Accidents are understandable, but getting defensive doesn't help :) Generally, people don't speak up until there've been several similar instances. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: hi
On Sep 14, 5:22 pm, Dwight Hutto wrote: > Completely OT for this discussion. My apologies, I'll leave you to your thrashing around like a giant child then. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Sep 14, 6:04 pm, Dwight Hutto wrote: > > Using foreign names derogatively is a common tactic of the racist. > > Not really. But nice spin on my pun to make me look bad. It actually *is* common behaviour of racists. > It's similar to if I said, this is real 'queer' of you to do ya big > pansy, and next you'll be calling me a homophobe. Well, *yes*. Because your choice of that terminology as derogatory shows you view it as derogatory. > Try harder, because no one would ever believe I was a racist, and if > they did, it's an uninformed decision based off of cherry picken > phrases out of context. Oh, so *now* context is important. > Very text book propaganda of you though. I don't think that word means what you think it does. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Fri, Sep 14, 2012 at 4:20 AM, alex23 wrote: > On Sep 14, 6:04 pm, Dwight Hutto wrote: >> > Using foreign names derogatively is a common tactic of the racist. >> >> Not really. But nice spin on my pun to make me look bad. > > It actually *is* common behaviour of racists. > Not if there name is ramit. What if your name was john? I'd say I'll be right back, I have to go take a crap on the john. It's a joke about a name, not where it originates. >> It's similar to if I said, this is real 'queer' of you to do ya big >> pansy, and next you'll be calling me a homophobe. > > Well, *yes*. Because your choice of that terminology as derogatory > shows you view it as derogatory. No it was a loose analogy to show that he's just trying to use anything he can say to slam me, and everyone can know it wasn't meant as racist. >> Try harder, because no one would ever believe I was a racist, and if >> they did, it's an uninformed decision based off of cherry picken >> phrases out of context. > > Oh, so *now* context is important. Never said it wasn't. The whole conversation to me is the context, and the OP usually follows it, and that's who it is usually intended for. >> Very text book propaganda of you though. > > I don't think that word means what you think it does. from wiki: Propaganda is a form of communication that is aimed at influencing the attitude of a community toward some cause or position. Propaganda is usually repeated and dispersed over a wide variety of media in order to create the chosen result in audience attitudes. He wants people to think I'm a racist, and you now want to see that in me as well. It seems it has propagated, and that I know exactly what it means. And all over a silly post that had too little content, at the time, to have what I said require any other posts, especially if the OP is following the conversation. > http://mail.python.org/mailman/listinfo/python-list -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call is not waiting.
On 13/09/12 19:24:46, woo...@gmail.com wrote: > It possibly requires a "shell=True", That's almost always a bad idea, and wouldn't affect waiting anyway. > but without any code or any way to test, we can not say. That's very true. -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: hi
On Fri, Sep 14, 2012 at 4:16 AM, alex23 wrote: > On Sep 14, 5:22 pm, Dwight Hutto wrote: >> Completely OT for this discussion. > > My apologies, I'll leave you to your thrashing around like a giant > child then. Please explain that one. I usually keep the thrashing for inside the house, unlike your childish nature, which you like to expose to everyone. > You can start a bash David thread, and like you have been, lose the argument that I'm a bad person, just because I trimmed a post too much in the middle of a conversation. Meanwhile, I have my roughdraft site I'd like to get back to. If you have anything constructive to say, I'll be glad to listen, if not, I'll probably listen anyway. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
- Original Message - > On Sep 14, 3:54 am, Jean-Michel Pichavant > wrote: > > I don't like decorators, I think they're not worth the mental > > effort. > > Because passing a function to a function is a huge cognitive burden? > -- > http://mail.python.org/mailman/listinfo/python-list > I was expecting that. Decorators are very popular so I kinda already know that the fault is mine. Now to the reason why I have troubles writing them, I don't know. Every time I did use decorators, I spent way too much time writing it (and debugging it). I wrote the following one, used to decorate any function that access an equipment, it raises an exception when the timeout expires. The timeout is adapted to the platform, ASIC of FPGA so people don't need to specify everytime one timeout per platform. In the end it would replace def boot(self, timeout=15): if FPGA: self.sendCmd("bootMe", timeout=timeout*3) else: self.sendCmd("bootMe", timeout=timeout) with @timeout(15) def boot(self, timeout=None): self.sendCmd("bootMe", timeout) I wrote a nice documentation with sphinx to explain this, how to use it, how it can improve code. After spending hours on the decorator + doc, feedback from my colleagues : What the F... !! Decorators are very python specific (probably exists in any dynamic language though, I don't know), in some environment where people need to switch from C to python everyday, decorators add python magic that not everyone is familiar with. For example everyone in the team is able to understand and debug the undecorated version of the above boot method. I'm the only one capable of reading the decorated version. And don't flame my colleagues, they're amazing people (just in case they're reading this :p) who are not python developers, more of users. Hence my original "decorators are not worth the mental effort". Context specific I must admit. Cheers, JM PS : Here's the decorator, just to give you an idea about how it looks. Small piece of code, but took me more than 2 hours to write it. I removed some sensible parts so I don't expect it to run. class timeout(object): """Substitute the timeout keyword argument with the appropriate value""" FACTORS = { IcebergConfig().platform.ASIC : 1, IcebergConfig().platform.FPGA : 3, } def __init__(self, asic, fpga=None, palladium=None): self.default = asic self.fpga = fpga def _getTimeout(self): platform = config().platform factor = self.FACTORS[platform.value] timeout = { platform.ASIC : self.default*factor, platform.FPGA : self.fpga or self.default*factor, }[platform.value] return timeout def __call__(self, func): def decorated(*args, **kwargs): names, _, _, defaults = inspect.getargspec(func) defaults = defaults or [] if 'timeout' not in names: raise ValueError('A "timeout" keyword argument is required') if 'timeout' not in kwargs: # means the timeout keyword arg is not in the call index = names.index('timeout') argsLength = (len(names) - len(defaults)) if index < argsLength: raise NotImplementedError('This decorator does not support non keyword "timeout" argument') if index > len(args)-1: # means the timeout has not be passed using a pos argument timeoutDef = defaults[index-argsLength] if timeoutDef is not None: _log.warning("Decorating a function with a default timeout value <> None") kwargs['timeout'] = self._getTimeout() else: _log.warning('Timeout value specified during the call, please check "%s" @timeout decorator.' % func.__name__) ret = func(*args, **kwargs) return ret return decorated -- http://mail.python.org/mailman/listinfo/python-list
Re: Batching HTTP requests with httplib (Python 2.7)
On 14/09/2012 03:31, Cameron Simpson wrote: On 13Sep2012 19:34, Chicken McNuggets wrote: | I'm writing a simple library that communicates with a web service and am | wondering if there are any generally well regarded methods for batching | HTTP requests? | | The problem with most web services is that they require a list of | sequential commands to be executed in a certain order to complete a | given task (or at least the one I am using does) so having to manually | call each command is a bit of a pain. How would you go about the design | of a library to interact with these services? | | Any help is greatly appreciated :). Maybe I'm missing something. What's hard about: - wrapping the web services calls in a simple wrapper which composes the call, runs it, and returns the result parts This lets you hide all the waffle about the base URL, credentials etc in the wrapper and only supply the essentials at call time. - writing your workflow thing then as a simple function: def doit(...): web_service_call1(...) web_service_call2(...) web_service_call3(...) with whatever internal control is required? This has worked for me for simple things. What am I missing about the larger context? That is what I have at the moment but it is ugly as hell. I was wondering if there was a somewhat more elegant solution that I was missing. -- http://mail.python.org/mailman/listinfo/python-list
Asynchronous Soappy on AppEngine
Hi, I've noticed that my Soappy calls get converted to URLFetch calls on Google AppEngine. There seems to be documentation that UrlFetch can do Asynchronous operations [1] but I'm not really sure how to make the soap operations asynchronous. Tried looking at the Soapproxy class and see if I can put in callsbacks with urllib somewhere, but I think I am even more confused now. Thoughts suggestions, besides used twisted? Regards, Dennis [1] ( https://developers.google.com/appengine/docs/python/urlfetch/asynchronousrequests -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Fri, 14 Sep 2012 01:20:53 -0700, alex23 wrote: > On Sep 14, 6:04 pm, Dwight Hutto wrote: [snip] Please don't feed the trolls. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Sep 14, 6:53 pm, Dwight Hutto wrote: > Not if there name is ramit. What if your name was john? I'd say I'll > be right back, I have to go take a crap on the john. It's a joke about > a name, not where it originates. I'd recommend reading up on white privilege but I'm pretty sure it'd be a wasted suggestion. > >> It's similar to if I said, this is real 'queer' of you to do ya big > >> pansy, and next you'll be calling me a homophobe. > > > Well, *yes*. Because your choice of that terminology as derogatory > > shows you view it as derogatory. > > No it was a loose analogy You can't use something as an example to support your case, and then dismiss it as "a loose analogy" when it undermines it. > he's just trying to use anything he can say to slam me everyone > can know it wasn't meant as racist. The "anything" I'm "using" is what *you* have said. I'm not trying to "slam" you, I don't even know who you are. I just have a very short fuse for rudeness and an even shorter one for racism, even if it *was* intended in a "hyuck hyuck, I'm so punny" way. Ignorant racism is still racism. > The whole conversation to me is the context And yet: > He wants people to think I'm a racist, and you now want to see that in > me as well. It seems it has propagated, and that I know exactly what > it means. Again, so much for context. There is no "he" and me, I'm the person who made the original accusation and then followed up on it. That's not propagation, so it's not propaganda. Now, someone who starts a new thread to have a conversation *with themselves* in some bizarre piece of performance art that seems intended to brand as petty the *requests that he actually follow list etiquette*...*that* is someone I'd consider a propagandist. -- http://mail.python.org/mailman/listinfo/python-list
What's wrong with my arc tangens calculation?
I do some math with python: import math as m m.degrees(m.atan(2)) >>> 63.43494882292201 but when i lookup tg in a paper table (last decade math book) i've got these values: tg(63'10'') = 1.9768 tg(63'20'') = 1.9912 tg(63'30'') = 2.0057 For me python should return something more like 63'2x'' than 63'4x''(becasue 63'30'' is higher than 2.0) what's wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with my arc tangens calculation?
On Fri, Sep 14, 2012 at 8:49 PM, xliiv wrote: > I do some math with python: > > import math as m > m.degrees(m.atan(2)) 63.43494882292201 > > but when i lookup tg in a paper table (last decade math book) i've got these > values: > > tg(63'10'') = 1.9768 > tg(63'20'') = 1.9912 > tg(63'30'') = 2.0057 > > For me python should return something more like 63'2x'' than 63'4x''(becasue > 63'30'' is higher than 2.0) According to Google: .43494882292201 degrees = 26.0969294 arcminutes So I would say that your table and Python are in agreement. Do you know what the notation 63'30" means? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with my arc tangens calculation?
but when i lookup tg in a paper table (last decade math book) i've got these values: tg(63'10'') = 1.9768 tg(63'20'') = 1.9912 tg(63'30'') = 2.0057 For me python should return something more like 63'2x'' than 63'4x''(becasue 63'30'' is higher than 2.0) what's wrong? 63° 30" is 63.5°. So nothing is wrong. (You know, 1° = 60 arc second!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Batching HTTP requests with httplib (Python 2.7)
>> | The problem with most web services is that they require a list of >> | sequential commands to be executed in a certain order to complete a >> | given task (or at least the one I am using does) so having to manually >> | call each command is a bit of a pain. How would you go about the design >> | of a library to interact with these services? >> | >> | Any help is greatly appreciated :). >> >> Maybe I'm missing something. What's hard about: >> >>- wrapping the web services calls in a simple wrapper which >> composes the call, runs it, and returns the result parts >> This lets you hide all the waffle about the base URL, >> credentials etc in the wrapper and only supply the essentials >> at call time. >> >>- writing your workflow thing then as a simple function: >> >>def doit(...): >> web_service_call1(...) >> web_service_call2(...) >> web_service_call3(...) >> >> with whatever internal control is required? >> >> This has worked for me for simple things. >> >> What am I missing about the larger context? >> > > That is what I have at the moment but it is ugly as hell. I was wondering if > there was a somewhat more elegant solution that I was missing. > -- Well if the code works it works. There probably is a better way than what I came up with: def web_service_call0(y): print "Service call = %i)" % y def web_service_call1(y): print "Service call = %i)" % y def web_service_call2(y): print "Service call = %i)" % y def web_service_call3(y): print "Service call = %i)" % y def web_service_call4(y): print "Service call = %i)" % y service_num_list = [num for num in range(0,5)] for service_num in service_num_list: eval("web_service_call%i(%i)" % (service_num,service_num)) I just define the service calls, and iterate through them with an eval that places in the service call num, but you would have to have a matching list of the params that would go with each one. I'm almost positive there will be some more well written ones on the way. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with my arc tangens calculation?
On Friday, September 14, 2012 12:55:06 PM UTC+2, Laszlo Nagy wrote: > > but when i lookup tg in a paper table (last decade math book) i've got > > these values: > > > > > > tg(63'10'') = 1.9768 > > > tg(63'20'') = 1.9912 > > > tg(63'30'') = 2.0057 > > > > > > For me python should return something more like 63'2x'' than > > 63'4x''(becasue 63'30'' is higher than 2.0) > > > > > > what's wrong? > > > > > 63� 30" is 63.5�. So nothing is wrong. (You know, 1� = 60 arc second!) So the wrong part is me ;) The python's 63.43494882292201 is degrees (according to function math.degrees) but book's value is in minutes. Clearified Thanks, all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
Jean-Michel Pichavant wrote: > I wrote the following one, used to decorate any function that access > an equipment, it raises an exception when the timeout expires. The > timeout is adapted to the platform, ASIC of FPGA so people don't need > to specify everytime one timeout per platform. > > In the end it would replace > > def boot(self, timeout=15): > if FPGA: > self.sendCmd("bootMe", timeout=timeout*3) > else: > self.sendCmd("bootMe", timeout=timeout) > > with > > @timeout(15) > def boot(self, timeout=None): > self.sendCmd("bootMe", timeout) > > I wrote a nice documentation with sphinx to explain this, how to use > it, how it can improve code. After spending hours on the decorator + > doc, feedback from my colleagues : What the F... !! > I'd agree with your colleagues. How are you going to ensure that all relevant functions are decorated and yet no decorated function ever calls another decorated one? >From the code you posted it would seem appropriate that the adjustment of the timeout parameter happen in the `sendCmd()` method itself and nowhere else. Alternatively use named values for different categories of timeouts and adjust them on startup so instead of a default of `timeout= 15` you would have a default `timeout=MEDIUM_TIMEOUT` or whatever name is appropriate. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
> I'd recommend reading up on white privilege but I'm pretty sure it'd > be a wasted suggestion. Not really, I tend to like interdisciplinary study. But I'm a little of everything if you like Darwin. > >> >> It's similar to if I said, this is real 'queer' of you to do ya big >> >> pansy, and next you'll be calling me a homophobe. >> >> > Well, *yes*. Because your choice of that terminology as derogatory >> > shows you view it as derogatory. >> >> No it was a loose analogy > > You can't use something as an example to support your case, and then > dismiss it as "a loose analogy" when it undermines it. > How did it undermine it? It's the same thing, just transferred to another well known group subject to violent bigotry. I used a play on words in a response, and because his names foreign that makes me a racist. There's no logic in that, other than to bring me down, and use the worst thing you can say...playing the race card. >> he's just trying to use anything he can say to slam me everyone >> can know it wasn't meant as racist. > > The "anything" I'm "using" is what *you* have said. I'm not trying to > "slam" you, I don't even know who you are. I just have a very short > fuse for rudeness and an even shorter one for racism, It wasn't rude in terms of these things that have been said about me. Then lengthen your fuse, because I'm not a racist, I just play with words a lot, including foreign names. even if it *was* > intended in a "hyuck hyuck, I'm so punny" way. Ignorant racism is > still racism. Still trying to propagate a thought that I'm racist based on a guy who for all I know is white, and uses the A.K.A ramit. I have no freakin clue if ramit is an ethnic name or nickname...we're on the internet tweedledick(badumchee, and hyuck,hyuck,hyuck) > >> The whole conversation to me is the context > > And yet: > >> He wants people to think I'm a racist, and you now want to see that in >> me as well. It seems it has propagated, and that I know exactly what >> it means. > > Again, so much for context. There is no "he" and me, I'm the person > who made the original accusation and then followed up on it. That's > not propagation, so it's not propaganda. You're still trying to prove the point, when we all know I'm not a racist. > > Now, someone who starts a new thread to have a conversation *with > themselves* in some bizarre piece of performance art that seems > intended to brand as petty the *requests that he actually follow list > etiquette*...*that* is someone I'd consider a propagandist. > -- You mean like you taking over this thread to call me a racist, and go on ad nauseam about it, when everyone can see what you're doing is trying to prove a point you know is wrong? Go back to debate 101, and flunk your professor if he passed you. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
[snip] > Please don't feed the trolls. You're down here under the bridge with the rest of us trolls too, Steven. 24/7 -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python presentations
On 14.09.2012 00:38, Chris Angelico wrote: > On Fri, Sep 14, 2012 at 8:33 AM, Alexander Blinne wrote: >> def powerlist(x,n): >> if n==1: >> return [1] >> p = powerlist(x,n-1) >> return p + [p[-1]*x] > > Eh, much simpler. > > def powerlist(x,n): > return [x*i for i in xrange(n-1)] I suppose you meant: def powerlist(x,n): return [x**i for i in xrange(n-1)] But this is less efficient, because it needs more multiplications (see Horner's method) -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Fri, 14 Sep 2012 11:28:22 +0200, Jean-Michel Pichavant wrote: > PS : Here's the decorator, just to give you an idea about how it looks. > Small piece of code, but took me more than 2 hours to write it. I > removed some sensible parts so I don't expect it to run. [snip timeout class] Holy over-engineering Batman!!! No wonder you don't think much of decorators, if this example of overkill is what you consider typical of them. It does much, much more than the simple code you were replacing: def boot(self, timeout=15): if FPGA: self.sendCmd("bootMe", timeout=timeout*3) else: self.sendCmd("bootMe", timeout=timeout) # becomes: @timeout(15) def boot(self, timeout=None): self.sendCmd("bootMe", timeout) Most of my decorator functions are under a dozen lines. And that's the complicated ones! Here's my solution to the example you gave: # Untested! def timeout(t=15): # Decorator factory. Return a decorator to actually do the work. if FPGA: t *= 3 def decorator(func): @functools.wraps(func) def inner(self, timeout): self.sendCmd("bootMe", timeout=t) return inner return decorator I reckon that will pretty much do what your example showed. Of course, once you start adding more and more functionality above the simple code shown above (arbitrary platforms, argument checking of the decorated function, logging, etc.) you're going to get a much more complex decorator. On the other hand, YAGNI. http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python presentations
On Fri, Sep 14, 2012 at 9:47 PM, Alexander Blinne wrote: > On 14.09.2012 00:38, Chris Angelico wrote: >> On Fri, Sep 14, 2012 at 8:33 AM, Alexander Blinne wrote: >>> def powerlist(x,n): >>> if n==1: >>> return [1] >>> p = powerlist(x,n-1) >>> return p + [p[-1]*x] >> >> Eh, much simpler. >> >> def powerlist(x,n): >> return [x*i for i in xrange(n-1)] > > I suppose you meant: > > def powerlist(x,n): > return [x**i for i in xrange(n-1)] > > But this is less efficient, because it needs more multiplications (see > Horner's method) Err, yes, I did mean ** there. The extra multiplications may be slower, but which is worse? Lots of list additions, or lots of integer powers? In the absence of clear and compelling evidence, I'd be inclined to go with the list comp - and what's more, to skip this function altogether and use the list comp directly where it's needed. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
Am 14.09.2012 11:28, schrieb Jean-Michel Pichavant: Decorators are very popular so I kinda already know that the fault is mine. Now to the reason why I have troubles writing them, I don't know. Every time I did use decorators, I spent way too much time writing it (and debugging it). I wrote the following one, used to decorate any function that access an equipment, it raises an exception when the timeout expires. The timeout is adapted to the platform, ASIC of FPGA so people don't need to specify everytime one timeout per platform. In the end it would replace def boot(self, timeout=15): if FPGA: self.sendCmd("bootMe", timeout=timeout*3) else: self.sendCmd("bootMe", timeout=timeout) with @timeout(15) def boot(self, timeout=None): self.sendCmd("bootMe", timeout) I wrote a nice documentation with sphinx to explain this, how to use it, how it can improve code. After spending hours on the decorator + doc, feedback from my colleagues : What the F... !! Quite honestly: I think like your colleagues in this case and that in this case the decorator doesn't improve the code. Instead, I would probably have added a _get_timeout() function that takes care of adjusting the argument passed to the function according to the underlying hardware target. To be less abstract, the particular problem I have with your approach is that I can't even guess what your code means, let alone what parameters it actually takes. If you had written @default_timeout(15) def boot(self, timeout=None): instead, I would have been able to guess. OTOH, then again I would have wondered why you used a decorator to create a default argument when there is builtin support for specifying default arguments for functions. Maybe you could get away with a decorator like this: @adjust_timeout def boot(self, timeout=2.5): The idea is that the decorator modifies the timeout value passed to the function (or maybe just modifies the default value?) according to the underlying hardware. Decorators are very python specific (probably exists in any dynamic language though, I don't know), in some environment where people need to switch from C to python everyday, decorators add python magic that not everyone is familiar with. The same could be said for classes, iterators, significant whitespace, docstrings, lambdas. I think that this was just a bad example but it doesn't prove that decorators are worthless. Decorators are useful tools if they do something to a function, like doing something before or after the actual code, or modifying the context in which the code is called. Just setting a default parameter is possible as you have proved, but it's IMHO not a good use case. A bit more specific to your case, adding a timeout decorator would actually make much more sense if it transparently invoked the actual function in a second thread and the calling thread stops waiting for completion and raises an error after that timeout. This has the distinct advantage that the code doing the actual communication doesn't have any timeout handling code inside. I'm currently doing something similar here though I only monitor a TCP connection that is used for some telnet-style requests. Every function making a request over TCP is decorated with @_check_connection. That decorator does two things: 1. It checks for an existing fatal connection error. 2. It runs the request and filters resulting errors for fatal connection errors. The decorator looks like this: def _check_connection(fn): @functools.wraps(fn) def wrapper(self, *args, **kwargs): # check for sticky connection errors if self._connection_error: raise self._connection_error # run actual function try: return fn(self, *args, **kwargs) catch RequestFailed: # The other side signalled a failure, but # further requests can still succeed. raise catch ConnectionError, e: # The connection is broken beyond repair. # Store sticky connection and forward. self._connection_error = e raise return wrapper I have had other programmers here write such requests and they blindly copied the decorator from existing code. This works because the code inside that converts/formats/parses the inputs and outputs is completely unaware of the connection monitoring. Otherwise, I don't think anyone could explain what this decorator does, but they don't have to understand it either. It just works. I wish you a nice weekend! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call is not waiting.
os.system worked fine, and I found something in another section of code that was causing the "Too many open errors." (I was fooled, because output from subprocess call didn't seem to be coming out until the open files error. I'll go back and play with subprocess.call more, since os.system works. That's interesting about using shlex at run time. Is that just for the sake of computational cost? -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On 09/14/12 07:01, Steven D'Aprano wrote: > [snip timeout class] > > Holy over-engineering Batman!!! > > No wonder you don't think much of decorators, [snip] > Most of my decorator functions are under a dozen lines. And that's the > complicated ones! As are mine, and a sizable chunk of those under-a-dozen-lines are somewhat boilerplate like using @functools.wraps inside, actual def of the function, and returning that function. :-) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with my arc tangens calculation?
On 14/09/2012 11:54, Chris Angelico wrote: On Fri, Sep 14, 2012 at 8:49 PM, xliiv wrote: I do some math with python: import math as m m.degrees(m.atan(2)) 63.43494882292201 but when i lookup tg in a paper table (last decade math book) i've got these values: tg(63'10'') = 1.9768 tg(63'20'') = 1.9912 tg(63'30'') = 2.0057 For me python should return something more like 63'2x'' than 63'4x''(becasue 63'30'' is higher than 2.0) According to Google: .43494882292201 degrees = 26.0969294 arcminutes So I would say that your table and Python are in agreement. Do you know what the notation 63'30" means? ChrisA Somebody or something has a length, height or width of 63 feet 30 inches? :) -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with my arc tangens calculation?
On Fri, Sep 14, 2012 at 11:13 PM, Mark Lawrence wrote: > Somebody or something has a length, height or width of 63 feet 30 inches? :) Sounds like the height of a building with a barometer. The thirty inches, of course, being the height of the barometer. ChrisA (big, big barometer) -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
- Original Message - > Jean-Michel Pichavant wrote: > > > I wrote the following one, used to decorate any function that > > access > > an equipment, it raises an exception when the timeout expires. The > > timeout is adapted to the platform, ASIC of FPGA so people don't > > need > > to specify everytime one timeout per platform. > > > > In the end it would replace > > > > def boot(self, timeout=15): > > if FPGA: > > self.sendCmd("bootMe", timeout=timeout*3) > > else: > > self.sendCmd("bootMe", timeout=timeout) > > > > with > > > > @timeout(15) > > def boot(self, timeout=None): > > self.sendCmd("bootMe", timeout) > > > > I wrote a nice documentation with sphinx to explain this, how to > > use > > it, how it can improve code. After spending hours on the decorator > > + > > doc, feedback from my colleagues : What the F... !! > > > > I'd agree with your colleagues. How are you going to ensure that all > relevant functions are decorated and yet no decorated function ever > calls another decorated one? > > From the code you posted it would seem appropriate that the > adjustment > of the timeout parameter happen in the `sendCmd()` method itself and > nowhere else. Alternatively use named values for different categories > of > timeouts and adjust them on startup so instead of a default of > `timeout= > 15` you would have a default `timeout=MEDIUM_TIMEOUT` or whatever > name > is appropriate. > > -- > Duncan Booth http://kupuguy.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list All functions set different timeout values, I cannot use a DEFAULT_VALUE. All functions are design in the same way: def doSomeAction(self, timeout): preprocess() self.sendCmd('relatedAction', timeout) # send the command to the device CLI interface postprocess() Ultimately, the goal is to have something like @timeout(2) def doAction1 @timeout(4) def doAction2 @timeout(12) def doAction3 and so on... (1 second is important, because there's a platform I remove from my example, didn't want to advertise publicly tech used by the company, that runs 1000 times slower) Additionally, the multiple check I run within the decorator is for consistency check and argument checking. I though it was a good idea because our python engine is used by a dozen of engineers to control equipment, and any misuse of this new decorator would lead to badly configured timeouts with heavy consequences on the test sessions. Sometimes a RTFM is not enough, when you need to make this work, you slip on your Batman costume like Steven suggested, and you save the day (or so I though :) ) by raising nice exceptions about missing keyword argument. But let's forget about my poor example, I end up describing my life which is pretty pointless. Here's Steven example: # Untested! def timeout(t=15): # Decorator factory. Return a decorator to actually do the work. if FPGA: t *= 3 def decorator(func): @functools.wraps(func) def inner(self, timeout): self.sendCmd("bootMe", timeout=t) return inner return decorator I can assure you, that for some python users, it's is not easy to understand what it does, this function returning a function which returns another (wrapped) function. It requires some effort. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
I think one very nice and simple example of how decorators can be used is this: def memoize(f, cache={}, *args, **kwargs): def _memoize(*args, **kwargs): key = (args, str(kwargs)) if not key in cache: cache[key] = f(*args, **kwargs) return cache[key] return _memoize def fib(n): if n <= 1: return 1 return fib(n-1) + fib(n-2) @memoize def fib_memoized(n): if n <= 1: return 1 return fib_memoized(n-1) + fib_memoized(n-2) The second fibonacci looks exactly the same but while the first is very slow and would generate a stack overflow the second doesn't.. I might use this example for the presentation, before explaining what it is.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Sat, Sep 15, 2012 at 12:12 AM, andrea crotti wrote: > def fib(n): > if n <= 1: > return 1 > return fib(n-1) + fib(n-2) > > @memoize > def fib_memoized(n): > if n <= 1: > return 1 > return fib_memoized(n-1) + fib_memoized(n-2) > > > The second fibonacci looks exactly the same but while the first is > very slow and would generate a stack overflow the second doesn't.. Trouble is, you're starting with a pretty poor algorithm. It's easy to improve on what's poor. Memoization can still help, but I would start with a better algorithm, such as: def fib(n): if n<=1: return 1 a,b=1,1 for i in range(1,n,2): a+=b b+=a return b if n%2 else a def fib(n,cache=[1,1]): if n<=1: return 1 while len(cache)<=n: cache.append(cache[-1] + cache[-2]) return cache[n] Personally, I don't mind (ab)using default arguments for caching, but you could do the same sort of thing with a decorator if you prefer. I think the non-decorated non-recursive version is clear and efficient though. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Guides for communicating with business accounting systems
On Fri, 14 Sep 2012 16:36:58 +1000, Chris Angelico wrote: > Actually I haven't used Postgres with Python yet. Should probably do > that at some point. But the MySQL bindings for Python aren't so awesome > they can't be matched by any other. I have found psycopg2 excellent in every respect. -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: 'list' object has no attribute 'lower'
Thanks. By the way, do we have a list of explanations of error message? If so, whenever we come across error message, we can refer to it and solve the problem accordingly. -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: 'list' object has no attribute 'lower'
On Sat, Sep 15, 2012 at 1:01 AM, Token Type wrote: > Thanks. By the way, do we have a list of explanations of error message? If > so, whenever we come across error message, we can refer to it and solve the > problem accordingly. Not really, but if you paste the message into Google or DuckDuckGo or another web search engine, you'll usually find something helpful. Possibly add a few keywords about what you're doing, if the message alone is too general. By the way, you don't need to include both comp.lang.python and python-list in your addressees; they mirror each other, so sending to one will make it arrive on the other too. Have fun! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Fri, 14 Sep 2012 15:22:26 +0200, Jean-Michel Pichavant wrote: > Here's Steven example: > > # Untested! > def timeout(t=15): > # Decorator factory. Return a decorator to actually do the work. if > FPGA: > t *= 3 > def decorator(func): > @functools.wraps(func) > def inner(self, timeout): > self.sendCmd("bootMe", timeout=t) > return inner > return decorator > > I can assure you, that for some python users, it's is not easy to > understand what it does, this function returning a function which > returns another (wrapped) function. It requires some effort. Oh I agree. So does learning to tie your shoe-laces, learning to cook, and learning to drive. Learning to be a world-class chess master takes a lot of effort. Learning about decorators does not. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: 'list' object has no attribute 'lower'
On Fri, 14 Sep 2012 08:01:11 -0700, Token Type wrote: > Thanks. By the way, do we have a list of explanations of error message? > If so, whenever we come across error message, we can refer to it and > solve the problem accordingly. Forget about a "list of explanations of error message[s]". There is no such list, and there never will be, because there is no limit to the number and kind of possible error messages. Instead, you should actually read the error message you see. Python is telling you what the problem is. Pay attention to it. AttributeError: 'list' object has no attribute 'lower' This tells you that you tried to access something.lower, but "something" is a list, and lists don't have an attribute or method "lower". Normally, Python will show you the line of source code with the error, so you will even see the name of the variable. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
- Original Message - > On Fri, 14 Sep 2012 15:22:26 +0200, Jean-Michel Pichavant wrote: > > > Here's Steven example: > > > > # Untested! > > def timeout(t=15): > > # Decorator factory. Return a decorator to actually do the > > work. if > > FPGA: > > t *= 3 > > def decorator(func): > > @functools.wraps(func) > > def inner(self, timeout): > > self.sendCmd("bootMe", timeout=t) > > return inner > > return decorator > > > > I can assure you, that for some python users, it's is not easy to > > understand what it does, this function returning a function which > > returns another (wrapped) function. It requires some effort. > > Oh I agree. So does learning to tie your shoe-laces, learning to > cook, > and learning to drive. > > Learning to be a world-class chess master takes a lot of effort. > Learning > about decorators does not. > > > -- > Steven I said some effort, not a lot of effort. Something else that requires some effort it to make experts realize that some things they consider trivial and easy, aren't actually for a lot of people. Returning to my cave. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
2012/9/14 Chris Angelico : > > Trouble is, you're starting with a pretty poor algorithm. It's easy to > improve on what's poor. Memoization can still help, but I would start > with a better algorithm, such as: > > def fib(n): > if n<=1: return 1 > a,b=1,1 > for i in range(1,n,2): > a+=b > b+=a > return b if n%2 else a > > def fib(n,cache=[1,1]): > if n<=1: return 1 > while len(cache)<=n: > cache.append(cache[-1] + cache[-2]) > return cache[n] > > Personally, I don't mind (ab)using default arguments for caching, but > you could do the same sort of thing with a decorator if you prefer. I > think the non-decorated non-recursive version is clear and efficient > though. > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list The poor algorithm is much more close to the mathematical definition than the smarter iterative one.. And in your second version you include some ugly caching logic inside it, so why not using a decorator then? I'm not saying that with the memoization is the "good" solution, just that I think it's a very nice example of how to use a decorator, and maybe a good example to start with a talk on decorators.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Least-lossy string.encode to us-ascii?
Le jeudi 13 septembre 2012 23:25:27 UTC+2, Tim Chase a écrit : > I've got a bunch of text in Portuguese and to transmit them, need to > > have them in us-ascii (7-bit). I'd like to keep as much information > > as possible, just stripping accents, cedillas, tildes, etc. So > > "serviço móvil" becomes "servico movil". Is there anything stock > > that I've missed? I can do mystring.encode('us-ascii', 'replace') > > but that doesn't keep as much information as I'd hope. > Interesting case. It's where the coding of characters meets characters usage, scripts, typography, linguistic features. I cann't discuss the Portugese case, but in French and in German one way to achieve the task is to convert the text in uppercases. It preserves a correct text. >>> s = 'Lætitia cœur éléphant français LUŸ Stoß Erklärung stören' >>> libfrancais.SpecMajuscules(s) 'LAETITIA COEUR ELEPHANT FRANCAIS LUY STOSS ERKLAERUNG STOEREN' >>> r = 'LAETITIA COEUR ELEPHANT FRANCAIS LUY STOSS ERKLAERUNG STOEREN' >>> r.encode('ascii', 'strict').decode('ascii', 'strict') == r True PS Avoid Py3.3 :-) jmf -- http://mail.python.org/mailman/listinfo/python-list
PyConUK 2012 Schedule now online
Hello! PyConUK 2012, the UK Python Conference, is taking place in Coventry from Friday 28th September to Monday 1st October. That is only two weeks away! Everyone is welcome from complete beginners through to experienced experts. The core is on Saturday and Sunday so if you cannot get time off work, you will still get all the key parts of the conference. We now have a draft schedule online: * http://pyconuk.net/Schedule It includes talks, introductory and intermediate tutorials, sprints, discussions, socials, the annual Python dinner, and of course the famous Lightning Talks. An introduction to the conference can be found here: * http://pyconuk.org More information at our wiki at: * http://pyconuk.net To book a ticket, please visit: http://pyconuk2012.eventbrite.co.uk/ Best Wishes, The Python UK Team P.S. Please forward this message to your friends, colleagues, mailing lists, social networks, local user groups, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
Chris Angelico於 2012年9月14日星期五UTC+8下午10時41分06秒寫道: > On Sat, Sep 15, 2012 at 12:12 AM, andrea crotti > > wrote: > > > def fib(n): > > > if n <= 1: > > > return 1 > > > return fib(n-1) + fib(n-2) > > > > > > @memoize > > > def fib_memoized(n): > > > if n <= 1: > > > return 1 > > > return fib_memoized(n-1) + fib_memoized(n-2) > > > > > > > > > The second fibonacci looks exactly the same but while the first is > > > very slow and would generate a stack overflow the second doesn't.. > > > > Trouble is, you're starting with a pretty poor algorithm. It's easy to > > improve on what's poor. Memoization can still help, but I would start > > with a better algorithm, such as: > > > > def fib(n): > > if n<=1: return 1 > > a,b=1,1 > > for i in range(1,n,2): > > a+=b > > b+=a > > return b if n%2 else a > > > > def fib(n,cache=[1,1]): > > if n<=1: return 1 > > while len(cache)<=n: > > cache.append(cache[-1] + cache[-2]) > > return cache[n] > > > > Personally, I don't mind (ab)using default arguments for caching, but > > you could do the same sort of thing with a decorator if you prefer. I > > think the non-decorated non-recursive version is clear and efficient > > though. > > > > ChrisA Uhn, the decorator part is good for wrapping functions in python. For example a decorator can be used to add a layor of some message handlings of those plain functions to become iterators which could be used as call back functions in a more elegant way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Sat, Sep 15, 2012 at 2:15 AM, andrea crotti wrote: > The poor algorithm is much more close to the mathematical definition > than the smarter iterative one.. And in your second version you > include some ugly caching logic inside it, so why not using a > decorator then? I learned Fibonacci as a sequence, not as a recursive definition. So the algorithm I coded (the non-caching one) is pretty much how I learned it in mathematics. But yes, you're right that the caching is inherent to the second version; and yes, that's where a decorator can make it a LOT cleaner. As a demo of recursion and decorators, your original function pair is definitely the best. But if you want to be able to calculate fib(n) for any n without blowing your stack, my version will scale much more safely. But then again, who actually ever needs fibonacci numbers? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call is not waiting.
On Friday, September 14, 2012 8:22:44 AM UTC-4, pauls...@gmail.com wrote: > os.system worked fine, and I found something in another section of code that > was causing the "Too many open errors." (I was fooled, because output from > subprocess call didn't seem to be coming out until the open files error. > > > > I'll go back and play with subprocess.call more, since os.system works. > That's interesting about using shlex at run time. Is that just for the sake > of computational cost? I never got the hang of subprocess, either. I ended up wrapping os.system in a python file and using subprocess to call that with: subprocess.Popen([sys.executable, 'Wrapper.py']) This works for me. I'm using Windows 7. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On 9/13/2012 10:12 PM, Cameron Simpson wrote: On 13Sep2012 18:58, alex23 wrote: | On Sep 14, 3:54 am, Jean-Michel Pichavant | wrote: | > I don't like decorators, I think they're not worth the mental effort. | | Because passing a function to a function is a huge cognitive burden? For parameterized decorators, there is extra cognitive burden. See below. It is for me when I'm _writing_ the decorator:-) But if I get it right and name it well I find it dramaticly _decreases_ the cognitive burden of the code using the decorator... For a simple, unparameterized wrapper, the difficulty is entirely in the wrapper maker. It must define the final wrapper as a nested function and return it*. It is irrelevant whether the wrapper maker is used with pre-def decorator syntax or with an explicit post-def call. *I am here ignoring the option of a class with __call__ method. For a parameterized wrapper, using decorator syntax requires passing the parameter(s) first and the function to be wrapped later. This requires currying the wrapper maker with double nesting. The nesting order may seem inside-out to some. For most people, this is extra work compared to writing a wrapper that accepts the function and parameters together and only has a single level of nesting. In other words def make_wrapper(func, param): def wrapper(*args, **kwds): for i in range(param): func(*args, **kwds) return wrapper def f(x): print(x) f = make_wrapper(f, 2) f('simple') # is simpler, at least for some people, than the following # which does essentially the same thing. def make_outer(param): def make_inner(func): def wrapper(*args, **kwds): for i in range(param): func(*args, **kwds) return wrapper return make_inner @make_outer(2) def f(x): print(x) f('complex') Is the gain of not repeating the wrapped function name twice in the post-def wrapping call, and the gain of knowing the function will be wrapped before reading the def, worth the pain of currying the wrapper maker? -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On 9/14/2012 5:28 AM, Jean-Michel Pichavant wrote: Decorators are very popular so I kinda already know that the fault is mine. Now to the reason why I have troubles writing them, I don't know. Every time I did use decorators, I spent way too much time writing it (and debugging it). -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
2nd try, hit send button by mistake before On 9/14/2012 5:28 AM, Jean-Michel Pichavant wrote: Decorators are very popular so I kinda already know that the fault is mine. Now to the reason why I have troubles writing them, I don't know. Every time I did use decorators, I spent way too much time writing it (and debugging it). You are writing parameterized decorators, which require inverted currying of the wrapper maker. Perhaps that is why you have trouble. As I showed in response to Cameron, it may be easier to avoid that by using a traditional post-def wrapping call instead of decorator syntax. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Least-lossy string.encode to us-ascii?
On 9/14/2012 12:15 PM, wxjmfa...@gmail.com wrote: PS Avoid Py3.3 :-) pps Start using 3.3 as soon as possible. It has Python's first fully portable non-buggy Unicode implementation. The second release candidate is already out. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On 9/14/2012 4:29 PM, Terry Reedy wrote: On 9/13/2012 10:12 PM, Cameron Simpson wrote: On 13Sep2012 18:58, alex23 wrote: | On Sep 14, 3:54 am, Jean-Michel Pichavant | wrote: | > I don't like decorators, I think they're not worth the mental effort. | | Because passing a function to a function is a huge cognitive burden? For parameterized decorators, there is extra cognitive burden. See below. It is for me when I'm _writing_ the decorator:-) But if I get it right and name it well I find it dramaticly _decreases_ the cognitive burden of the code using the decorator... For a simple, unparameterized wrapper, the difficulty is entirely in the wrapper maker. It must define the final wrapper as a nested function and return it*. It is irrelevant whether the wrapper maker is used with pre-def decorator syntax or with an explicit post-def call. *I am here ignoring the option of a class with __call__ method. For a parameterized wrapper, using decorator syntax requires passing the parameter(s) first and the function to be wrapped later. This requires currying the wrapper maker with double nesting. The nesting order may seem inside-out to some. For most people, this is extra work compared to writing a wrapper that accepts the function and parameters together and only has a single level of nesting. In other words def make_wrapper(func, param): def wrapper(*args, **kwds): for i in range(param): func(*args, **kwds) return wrapper def f(x): print(x) f = make_wrapper(f, 2) f('simple') # is simpler, at least for some people, than the following # which does essentially the same thing. def make_outer(param): def make_inner(func): def wrapper(*args, **kwds): for i in range(param): func(*args, **kwds) return wrapper return make_inner @make_outer(2) def f(x): print(x) f('complex') Is the gain of not repeating the wrapped function name twice in the post-def wrapping call, and the gain of knowing the function will be wrapped before reading the def, worth the pain of currying the wrapper maker? -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Least-lossy string.encode to us-ascii?
On 9/13/2012 10:09 PM, Mark Tolonen wrote: On Thursday, September 13, 2012 4:53:13 PM UTC-7, Tim Chase wrote: On 09/13/12 18:36, Terry Reedy wrote: 'keep as much information as possible' would mean an effectively lossless transliteration, which you could do with a dict. {: 'o', : 'c,' (or pick something that would Vlastimil's solution kept the characters but stripped them of their accents/tildes/cedillas/etc, doing just what I wanted, all using the stdlib. Hard to do better than that :-) You mean, hard to do better than what you think you want, as opposed to what you said you wanted in both the subject line and the text line I quoted. What you need depends on why you need ascii only text and what the recipient will do with the ascii only text. Print it on an ascii-only printer? Or something similar? If so, a lossy encoding may be sufficient, but why not let the recipient decide to toss info? How about using UTF-7 for transmission and decode on the other end? > This keeps the transmission all 7-bit, and no loss. >>> s=u"serviço móvil".encode('utf-7') >>> print s servi+AOc-o m+APM-vil >>> print s.decode('utf-7') serviço móvil Nice. I was barely aware of and forgot that option. This and similar suggestions to use existing methods is much better than my hackish approach. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Fri, Sep 14, 2012 at 2:29 PM, Terry Reedy wrote: > For a simple, unparameterized wrapper, the difficulty is entirely in the > wrapper maker. It must define the final wrapper as a nested function and > return it*. It is irrelevant whether the wrapper maker is used with pre-def > decorator syntax or with an explicit post-def call. > > *I am here ignoring the option of a class with __call__ method. > > For a parameterized wrapper, using decorator syntax requires passing the > parameter(s) first and the function to be wrapped later. This requires > currying the wrapper maker with double nesting. The nesting order may seem > inside-out to some. For most people, this is extra work compared to writing > a wrapper that accepts the function and parameters together and only has a > single level of nesting. > > In other words > > def make_wrapper(func, param): > def wrapper(*args, **kwds): > for i in range(param): > func(*args, **kwds) > return wrapper > > def f(x): print(x) > f = make_wrapper(f, 2) > f('simple') > > # is simpler, at least for some people, than the following > # which does essentially the same thing. > > def make_outer(param): > def make_inner(func): > def wrapper(*args, **kwds): > for i in range(param): > func(*args, **kwds) > return wrapper > return make_inner > > @make_outer(2) > def f(x): print(x) > f('complex') > > Is the gain of not repeating the wrapped function name twice in the post-def > wrapping call, and the gain of knowing the function will be wrapped before > reading the def, worth the pain of currying the wrapper maker? If only there were a conceptually simpler way to do this. Actually, there is. I give you: metadecorators! First, the simple, non-parameterized case: from functools import partial def make_wrapper(wrapper): return lambda wrapped: partial(wrapper, wrapped) With that simple function buried in a utility module somewhere, we can do: @make_wrapper def simple_decorator(func, *args, **kwargs): do_stuff() result = func(*args, **kwargs) do_more_stuff() return result Which I think is certainly easier to understand than the nested functions approach. Parameterized decorators are not much more difficult this way. This function: def make_parameterized_wrapper(wrapper): return lambda *params: lambda wrapped: partial(wrapper, wrapped, params) enables us to write: @make_parameterized_wrapper def complex_decorator(func, (param1, param2, param3), *args, **kwargs): do_stuff(param1, param2) result = func(*args, **kwargs) do_more_stuff(param2, param3) return result And now we have a fancy parameterized decorator that again requires no thinking about nested functions at all. Sadly, that last bit of syntax will only work in Python 2; tuple parameter unpacking was removed in Python 3. It's not a complicated upgrade path, however: @make_parameterized_wrapper def complex_decorator(func, params, *args, **kwargs): (param1, param2, param3) = params do_stuff(param1, param2) result = func(*args, **kwargs) do_more_stuff(param2, param3) return result Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On 14 September 2012 18:30, Chris Angelico wrote: > On Sat, Sep 15, 2012 at 2:15 AM, andrea crotti > wrote: > > The poor algorithm is much more close to the mathematical definition > > than the smarter iterative one.. And in your second version you > > include some ugly caching logic inside it, so why not using a > > decorator then? > > I learned Fibonacci as a sequence, not as a recursive definition. So > the algorithm I coded (the non-caching one) is pretty much how I > learned it in mathematics. But yes, you're right that the caching is > inherent to the second version; and yes, that's where a decorator can > make it a LOT cleaner. > > As a demo of recursion and decorators, your original function pair is > definitely the best. But if you want to be able to calculate fib(n) > for any n without blowing your stack, my version will scale much more > safely. > > But then again, who actually ever needs fibonacci numbers? > I thought the example was good, not because a recursive fib is useful but because memoizing is. There are a lot of times one would like to memoize a function: not just recursive ones. Thus, the example of the decorator was valid. [offtopic] Anyhow, the "best" method has to be this: >>> from decimal import Decimal as Dec >>> def fib(n): ... rootFive = Dec(5).sqrt() ... phi = (1 + rootFive) / 2 ... return round(phi**n / rootFive) >>> fib(100) 354224848179261915075 It's just so obvious why it works. [/offtopic] -- http://mail.python.org/mailman/listinfo/python-list
RE: Comparing strings from the back?
Dwight Hutto wrote: > On Thu, Sep 13, 2012 at 5:17 PM, Mark Lawrence > wrote: > > On 13/09/2012 21:34, Joshua Landau wrote: > >> > >> On 13 September 2012 20:53, Mark Lawrence > wrote:acci sequence > >> > >>> On 13/09/2012 19:39, Prasad, Ramit wrote: > >>> > Dwight Hutto wrote: > > > Why don' you just time it,eit lops through incrementing thmax input/ > > > > What? Without context I have no idea what this means. > > >>> > >>> You're wasting your time, I've been described as a jackass for having > >>> the > >>> audacity to ask for context :) > >> Mark, Sometimes it is the style in which something is asked, and not what specifically is asked. ;) > >> > >> > >> I'm pretty sure you are in the wrong, acting as if what he said didn't > >> make > >> sense! Just read it, he obviously was telling you to time it, as eit lops > >> are inside thmax input/ which, as you should know if you *bothered to read > >> the thread*, is incrementing. > >> > >> > >> "don'" is short for "don't", by the way. > > > > I do grovellingly apologize for my appalling breach of netiquette. I am of > > course assuming that the rules have changed and that it's now my > > responsibility to wade back through maybe a couple of hundred responses on a > > long thread to find the context. > I also guess that I'm never going to > > achieve my ambition of being a pot smoking hippy CEO of a web development > > company :( > > -- > > Cheers. > Cheers usually implies you're an alcoholic pressing buttons, with the > half of rest of the coders on the net. Dwight/David: Not necessarily true if you happen to be from the UK (or maybe just England). It seems to be a cultural signature equivalent to "Thanks"--at least in the UK (not sure about other places). [snip] Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
RE: pythonOCC examples doesn't work?
Dwight Hutto wrote: > Chris Angelico wrote: > > honest. How do you feel? Interesting... > > > Um, I guess like an inconsiderate bandwidth hog, but from now on I'll > trim more text. > > First it was too little, and now it's too much. It is a fine line to walk and nobody does it perfectly all the time. We just attempt our best. > I just tend to cut out some or all depending on the scope of the conversation. > > If I just hit reply all, and send it out, it's not intentionally to > use all of the text, and utilize the extra space, it's just a > response. > > If the conversation is kind of just a few people, then I trim pretty > much everything, which apparently set a guy name mark off, who I was > polite to, but I'm not going to get slammed for a few simple posting > mistakes, and more than likely a few of his aliases, or the group he > tends to cheer up with. Sorry, I did not mean to "slam" you by any means. I was just notifying you of the list's commonly agreed upon etiquette and requesting future posts to attempt to adhere to that. > > It's just a mailing list, lighten up because mistakes in posting will > happen, even by accident. > It's just a mailing list, lighten up because a few people trying to help improve your communication to the rest of the group may come off unintentionally as being "slammed" by the community. :) This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
RE: Comparing strings from the back?
Dwight Hutto wrote: > On Fri, Sep 14, 2012 at 4:20 AM, alex23 wrote: > > On Sep 14, 6:04 pm, Dwight Hutto wrote: > >> > Using foreign names derogatively is a common tactic of the racist. > >> > >> Not really. But nice spin on my pun to make me look bad. > > > > It actually *is* common behaviour of racists. > > > > Not if there name is ramit. What if your name was john? I'd say I'll > be right back, I have to go take a crap on the john. It's a joke about > a name, not where it originates. Okay, so maybe not racist but instead offensive juvenile humor? I suppose that is better... > > >> It's similar to if I said, this is real 'queer' of you to do ya big > >> pansy, and next you'll be calling me a homophobe. Um, yes! You are using 'queer' and 'pansy' as a derogatory comparison which falls under the definition for homophobia. "Homophobia is a range of negative attitudes and feelings toward homosexuality or people who are identified or perceived as being lesbian, gay, bisexual or transgender (LGBT). Definitions refer variably to antipathy, contempt, prejudice, aversion, irrational fear, and hatred." ~ First two sentences on Wikipedia > > > > Well, *yes*. Because your choice of that terminology as derogatory > > shows you view it as derogatory. > > No it was a loose analogy to show that he's just trying to use > anything he can say to slam me, and everyone can know it wasn't meant > as racist. Since I was unsure myself if you were trying to be offensive or racist, I would disagree with "everyone can know it wasn't meant as racist". > > >> Try harder, because no one would ever believe I was a racist, and if > >> they did, it's an uninformed decision based off of cherry picken > >> phrases out of context. > > > > Oh, so *now* context is important. > > Never said it wasn't. The whole conversation to me is the context, and > the OP usually follows it, and that's who it is usually intended for. > [ snip ] This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
RE: Decorators not worth the effort
Jean-Michel Pichavant wrote: [snip] > Ultimately, the goal is to have something like > > @timeout(2) > def doAction1 > > @timeout(4) > def doAction2 [snip] > Here's Steven example: > > # Untested! > def timeout(t=15): > # Decorator factory. Return a decorator to actually do the work. > if FPGA: > t *= 3 > def decorator(func): > @functools.wraps(func) > def inner(self, timeout): > self.sendCmd("bootMe", timeout=t) > return inner > return decorator > > I can assure you, that for some python users, it's is not easy to understand > what it does, this function returning a function which returns another > (wrapped) function. It requires some effort. > I think it would help if it was renamed to set_timeout. And I would not expect the Python user to need to understand how it *works*, just to recognize what it *does* when it is used. I may not understand list's sort method internals (beyond the use of timsort), but I know how to use it to sort a list as I want. That is usually all I need. For example, your colleagues just need to understand that the below decorator is setting a timeout for the function. @set_timeout(min=15) def some_function(): '''blah''' One minor note, the style of decorator you are using loses the docstring (at least) of the original function. I would add the @functools.wraps(func) decorator inside your decorator. This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Fri, 14 Sep 2012 15:16:47 -0600, Ian Kelly wrote: > If only there were a conceptually simpler way to do this. Actually, > there is. I give you: metadecorators! [code snipped but shown below] > Which I think is certainly easier to understand than the nested > functions approach. Maybe for you, but to me it is a big ball of mud. I have no idea how this is supposed to work! At a quick glance, I would have sworn that it *can't* work, since simple_decorator needs to see multiple arguments but only receives one, the function to be decorated. And yet it does work: py> from functools import partial py> def make_wrapper(wrapper): ... return lambda wrapped: partial(wrapper, wrapped) ... py> @make_wrapper ... def simple_decorator(func, *args, **kwargs): ... print "Entering decorated function" ... result = func(*args, **kwargs) ... print "Exiting decorated function" ... return result ... py> @simple_decorator ... def my_function(a, b, c): ... """Doc string""" ... return a+b+c ... py> my_function(1, 2, 3) Entering decorated function Exiting decorated function 6 So to me, this is far more magical than nested functions. If I saw this in t requires me to hunt through your library for the "simple function buried in a utility module somewhere" (your words), instead of seeing everything needed in a single decorator factory function. It requires that I understand how partial works, which in my opinion is quite tricky. (I never remember how it works or which arguments get curried.) And the end result is that the decorated function is less debugging- friendly than I demand: it is an anonymous partial object instead of a named function, and the doc string is lost. And it is far from clear to me how to modify your recipe to use functools.wraps in order to keep the name and docstring, or even whether I *can* use functools.wraps. I dare say I could answer all those questions with some experimentation and research. But I don't think that your "metadecorator" using partial is *inherently* more understandable than the standard decorator approach: def simple_decorator2(func): @functools.wraps(func) def inner(*args, **kwargs): print "Entering decorated function" result = func(*args, **kwargs) print "Exiting decorated function" return result return inner This is no more complex than yours, and it keeps the function name and docstring. > Parameterized decorators are not much more > difficult this way. This function: [snip code] > And now we have a fancy parameterized decorator that again requires no > thinking about nested functions at all. Again, at the cost of throwing away the function name and docstring. I realise that a lot of this boils down to personal preference, but I just don't think that nested functions are necessarily that hard to grasp, so I prefer to see as much of the decorator logic to be in one place (a nested decorator function) rather than scattered across two separate decorators plus partial. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Sep 6, 4:04 am, Oscar Benjamin wrote: > On Thu, 06 Sep 2012 06:07:38 -0400, Dave Angel wrote: > > For random strings (as defined below), the average compare time is > > effectively unrelated to the size of the string, once the size > passes > > some point. > > Define random string as being a selection from a set of characters, > with > > replacement. So if we pick some set of characters, say 10 (or 256, > it > > doesn't really matter), the number of possible strings is 10**N. > > The likelihood of not finding a mismatch within k characters is > > (1/10)**k The likelihood of actually reaching the end of the > random > > string is (1/10)**N. (which is the reciprocal of the number of > strings, > > naturally) > > If we wanted an average number of comparisons, we'd have to > calculate a > > series, where each term is a probability times a value for k. > > sum((k * 9*10**-k) for k in range(1, 10)) > > Those terms very rapidly approach 0, so it's safe to stop after a > few. > > Looking at the first 9 items, I see a value of 1.111 > > This may not be quite right, but the value is certainly well under > 2 for > > a population of 10 characters, chosen randomly. And notice that N > > doesn't really come into it. > > It's exactly right. You can obtain this result analytically from > Johannes' formula above. Just replace 256 with 10 to get that the > expected number of comparisons is > > (10/9)*(1 - 10**(-N)) The math here is simple, but of course the average running time is also driven by usage patterns. Let's say you have two independently produced strings with N number of random bits. The average amount of bit comparisons that it takes to determine that the strings are different is between 1 and 2 checks for any value of N, for the same reason that the average number of times you need to flip a coin before either coming up heads or exhausting your N tries is always less than 2, and pretty darn close to 2 for even relatively small values of N. def compute_checks_for_different_strings(n): x = 1 p = 0.5 for i in range(0, n): x += p * i p = p * 0.5 print n, x for n in [10, 100, 1000, 1]: compute_checks_for_different_strings(n) 10 1.9892578125 100 2.0 1000 2.0 1 2.0 Now let's say your string comparison function is used to verify 100- bit passwords, and 99% of the time the password is from a legit user who types it correctly. Except for the 1% of a time when somebody fat fingers the copy/paste of their password, every strcmp call is gonna have to compare 100 pairs of characters, or N pairs. If the usage pattern says that 99% of the time you're simply verifying that two strings are equal, then the number of bits is the main driving factor for running time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Sep 14, 6:05 am, Tim Chase wrote: > On 09/14/12 07:01, Steven D'Aprano wrote:> [snip timeout class] > > > Holy over-engineering Batman!!! > > > No wonder you don't think much of decorators, > > [snip] > > > Most of my decorator functions are under a dozen lines. And that's the > > complicated ones! > > As are mine, and a sizable chunk of those under-a-dozen-lines are > somewhat boilerplate like using @functools.wraps inside, actual def > of the function, and returning that function. :-) > > -tkc For parameterized decorators, I've usually seen the pattern below. Basically, you have 6 lines of boilerplate, and 2 lines of signal. The amount of boilerplate is fairly daunting, but I like the explicitness, and the nature of decorators is that they tend to get a lot of reuse, so you can amortize the pain of all the boilerplate. import functools def hello_world(name): # non-boilerplate signature def decorator(f): @functools.wraps(f) def wrapped(*args, **kw): print 'hello', name # non-boilerplate value-add f(*args, **kw) return wrapped return decorator @hello_world('earth') def add(x, y): print x + y add(2, 2) -- http://mail.python.org/mailman/listinfo/python-list
unit test strategy
Hello, I've developing a test script. There's a lot of repetition. I want to introduce a strategy for approaching it, but I don't want the program to be discredited because of the test script. Therefore, I'd like to know what people's reactions to and thoughts about it are. The first strategy I used created an iterator and advanced it between each step: self.op_chain(range(5), ('add', 5)) self.op_chain(range(5), ('add', -2), ('add', -1)) self.op_chain(range(5), ('discard', -1), ('add', 5)) self.op_chain_ok(range(5), ('update', [0, 1])) Etc. I'm considering something more complicated. 'iN' creates iterator N, 'nN' advances iterator N, an exception calls 'assertRaises', and the rest are function calls. dsi= dict.__setitem__ ddi= dict.__delitem__ dsd= dict.setdefault KE= KeyError IE= IterationError self.chain(range(10), 'i0', (dsi, 0, 1), 'n0', (dsi, 10, 1), (IE, 'n0')) self.chain(range(10), 'i0', 'n0', (dsd, 0, 0), 'n0', (dsd, 10, 1), (IE, 'n0')) self.chain(range(10), 'i0', (KE, ddi, 10), 'n0', (ddi, 9), (IE, 'n0')) Do you think the 2nd version is legible? Could it interfere with the accuracy of the test? -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing strings from the back?
On Fri, Sep 14, 2012 at 6:43 PM, Prasad, Ramit wrote: > Dwight Hutto wrote: >> On Fri, Sep 14, 2012 at 4:20 AM, alex2find-work-home/3 >> wrote: >> > On Sep 14, 6:04 pm, Dwight Hutto wrote: >> >> > Using foreign names derogatively is a common tactic of the racist. >> >> >> >> Not really. But nice spin on my pun to make me look bad. >> > >> > It actually *is* common behaviour of racists. >> > >> >> Not if there name is ramit. What if your name was john? I'd say I'll >> be right back, I have to go take a crap on the john. It's a joke about >> a name, not where it originates. > > Okay, so maybe not racist but instead offensive juvenile humor? > I suppose that is better... No, just shop talk. You hit me and hit I logarithmically hit back ..."butterfly effect". > >> >> >> It's similar to if I said, this is real 'queer' of you to do ya big >> >> pansy, and next you'll be calling me a homophobe. > > Um, yes! You are using 'queer' and 'pansy' as a derogatory comparison > which falls under the definition for homophobia. > > "Homophobia is a range of negative attitudes and feelings toward > homosexuality or people who are identified or perceived as being lesbian, > gay, bisexual or transgender (LGBT). Definitions refer variably to antipathy, > contempt, prejudice, aversion, irrational fear, and hatred." > ~ First two sentences on Wikipedia No, analogy, and a continued attack on a subject we know is propaganda. > >> > >> > Well, *yes*. Because your choice of that terminology as derogatory >> > shows you view it as derogatory. > >> >> No it was a loose analogy to show that he's just trying to use >> anything he can say to slam me, and everyone can know it wasn't meant >> as racist. > > Since I was unsure myself if you were trying to be offensive or racist, > I would disagree with "everyone can know it wasn't meant as racist". > If you're unsure if it was racist, you should err on the side of caution. There are many nicknames on the net. That could be an ethnic name, or an A.K.A.. Non-logical, pure speculation, that is biased that your minority needs more anit-you. Don't engage in conversations you're sure to lose. >> >> >> Try harder, because no one would ever believe I was a racist, and if >> >> they did, it's an uninformed decision based off of cherry picken >> >> phrases out of context. >> > >> > Oh, so *now* context is important. >> >> Never said it wasn't. The whole conversation to me is the context, and >> the OP usually follows it, and that's who it is usually intended for. >> -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: unit test strategy
On Fri, Sep 14, 2012 at 10:59 PM, Aaron Brady wrote: > Hello, > > I've developing a test script. There's a lot of repetition. I want to > introduce a strategy for approaching it, but I don't want the program to be > discredited because of the test script. Therefore, I'd like to know what > people's reactions to and thoughts about it are. > > The first strategy I used created an iterator and advanced it between each > step: That isn't a refined iterator below: > self.op_chain(range(5), ('add', 5)) > self.op_chain(range(5), ('add', -2), ('add', -1)) > self.op_chain(range(5), ('discard', -1), ('add', 5)) > self.op_chain_ok(range(5), ('update', [0, 1])) > Etc. > > I'm considering something more complicated. 'iN' creates iterator N, 'nN' > advances iterator N, an exception calls 'assertRaises', and the rest are > function calls. > dsi= dict.__setitem__ > ddi= dict.__delitem__ > dsd= dict.setdefault > KE= KeyError > IE= IterationError > self.chain(range(10), 'i0', (dsi, 0, 1), 'n0', (dsi, 10, 1), (IE, > 'n0')) > self.chain(range(10), 'i0', 'n0', (dsd, 0, 0), 'n0', (dsd, 10, 1), > (IE, 'n0')) > self.chain(range(10), 'i0', (KE, ddi, 10), 'n0', (ddi, 9), (IE, 'n0')) > > Do you think the 2nd version is legible? Could it interfere with the > accuracy of the test? Show the test, which should show instances of wehat you want called. I could rewrite the above, but it seems you're moe in need of refining your iterations, and the values given within them. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: unit test strategy
On Fri, Sep 14, 2012 at 11:26 PM, Dwight Hutto wrote: > On Fri, Sep 14, 2012 at 10:59 PM, Aaron Brady wrote: >> Hello, >> >> I've developing a test script. There's a lot of repetition. I want to >> introduce a strategy for approaching it, but I don't want the program to be >> discredited because of the test script. Therefore, I'd like to know what >> people's reactions to and thoughts about it are. >> >> The first strategy I used created an iterator and advanced it between each >> step: > > That isn't a refined iterator below: What I mean is look at the similarities, and the differences, then replace the differences with interpolation, in eval even. > >> self.op_chain(range(5), ('add', 5)) >> self.op_chain(range(5), ('add', -2), ('add', -1)) >> self.op_chain(range(5), ('discard', -1), ('add', 5)) >> self.op_chain_ok(range(5), ('update', [0, 1])) >> Etc. >> >> I'm considering something more complicated. 'iN' creates iterator N, 'nN' >> advances iterator N, an exception calls 'assertRaises', and the rest are >> function calls. iN = [N for N in range(0,5)] >> dsi= dict.__setitem__ >> ddi= dict.__delitem__ >> dsd= dict.setdefault >> KE= KeyError >> IE= IterationError >> self.chain(range(10), 'i0', (dsi, 0, 1), 'n0', (dsi, 10, 1), (IE, >> 'n0')) >> self.chain(range(10), 'i0', 'n0', (dsd, 0, 0), 'n0', (dsd, 10, 1), >> (IE, 'n0')) >> self.chain(range(10), 'i0', (KE, ddi, 10), 'n0', (ddi, 9), (IE, >> 'n0')) >> >> Do you think the 2nd version is legible? Could it interfere with the >> accuracy of the test? Define the 2nd version > > Show the test, which should show instances of what you want called. > > I could rewrite the above, but it seems you're more in need of refining > your iterations, and the values given within them. > -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators not worth the effort
On Fri, Sep 14, 2012 at 2:40 AM, Dieter Maurer wrote: >> On Sep 14, 3:54 am, Jean-Michel Pichavant >> wrote: >>> I don't like decorators, I think they're not worth the mental effort. > > Fine. > > I like them because they can vastly improve reusability and drastically > reduce redundancies (which I hate). Improved reusability and > reduced redundancies can make applications more readable, easier > to maintain and faster to develop. Reduce redundancy, is argumentative. To me, a decorator, is no more than a logging function. Correct me if I'm wrong. It throws things at a functyion designed to watch other functions. The necessity for more than one decorator with if /else statements seems redundant, but I haven't had to use them that much recently. > > -- > http://mail.python.org/mailman/listinfo/python-list -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
On Fri, Sep 14, 2012 at 6:51 PM, Prasad, Ramit wrote: > Dwight Hutto wrote: >> Chris Angelico wrote: >> > honest. How do you feel? Interesting... >> > >> Um, I guess like an inconsiderate bandwidth hog, but from now on I'll >> trim more text. >> >> First it was too little, and now it's too much. > > It is a fine line to walk and nobody does it perfectly all the time. > We just attempt our best. >python docs interpolation >> I just tend to cut out some or all depending on the scope of the >> conversation. >> >> If I just hit reply all, and send it out, it's not intentionally topython >> docs interpolation >> use all of the text, and utilize the extra space, it's just a >> response. >> >> If the conversation is kind of just a few people, then I trim pretty >> much everything, which apppython docs interpolationarently set a guy name >> mark off, who I was >> polite to, but I'm not going to get slammed for a few simple posting >> mistakes, and more than likely a few of his aliases, or the group he >> tends to cheer up with. > > Sorry, I did not mean to "slam" you by any means. I was just > notifying you of the list's commonly agreed upon etiquette and > requesting future posts to attempt to adhere to that. > >> >> It's just a mailing list, lighten up because mistakes in posting will >> happen, even by accident. >> > > It's just a mailing list, lighten up because a few people trying > to help improve your communication to the rest of the group > may come off unintentionally as being "slammed" by the community. :) > That's no problem, But some suported ad some opposed, it's a democracy, but a dictatorship by the moderators. How much did I err in their opinion of stating my opinion, in relation to the statistical whole? -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
On Sat, Sep 15, 2012 at 1:47 PM, Dwight Hutto wrote: > That's no problem, But some suported ad some opposed, it's a > democracy, but a dictatorship by the moderators. How much did I err in > their opinion of stating my opinion, in relation to the statistical > whole? Actually, I've not seen any moderatorial action on this list. Savoynet is as you describe, a monarchy whose head but seldom exercises power; python-list/c.l.p is an anarchy - or, if you like, a true democracy. Not a representative democracy where we all get to vote, but we all individually have the power to kick someone out - it's called a killfile. The more people you annoy, the more people won't hear you any more. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call is not waiting.
On Fri, Sep 14, 2012 at 5:22 AM, wrote: > os.system worked fine, and I found something in another section of code that > was causing the "Too many open errors." (I was fooled, because output from > subprocess call didn't seem to be coming out until the open files error. > > I'll go back and play with subprocess.call more, since os.system works. > That's interesting about using shlex at run time. Is that just for the sake > of computational cost? No, like I said, you'll also get incorrect results. shlex isn't magic. If the exact command line it's given wouldn't work in the shell, then it won't magically fix things. Many (most?) dynamic invocations of shlex.split() are naive and flawed: >>> import shlex >>> filename = "my summer vacation.txt" >>> # the following error is less obvious when the command is more complex >>> # (and when the filename isn't hardcoded) >>> cmd = "cat " + filename >>> shlex.split(cmd) ['cat', 'my', 'summer', 'vacation.txt'] >>> # that's wrong; the entire filename should be a single list element Equivalent bash error: chris@mbp ~ $ cat my summer vacation.txt cat: my: No such file or directory cat: summer: No such file or directory cat: vacation.txt: No such file or directory The right way, in bash: chris@mbp ~ $ cat my\ summer\ vacation.txt Last summer, I interned at a tech company and... chris@mbp ~ $ cat 'my summer vacation.txt' Last summer, I interned at a tech company and… And indeed, shlex will get that right too: >>> shlex.split("cat my\ summer\ vacation.txt") ['cat', 'my summer vacation.txt'] >>> shlex.split("cat 'my summer vacation.txt'") ['cat', 'my summer vacation.txt'] BUT that presumes that your filenames are already pre-quoted or have had backslashes added, which very seldom is the case in reality. So, you can either find an escaping function and hope you never forget to invoke it (cf. SQL injection), or you can figure out the general tokenization and let `subprocess` handle the rest (cf. prepared statements): >>> split('cat examplesimplefilename') ['cat', 'examplesimplefilename'] >>> # Therefore… >>> def do_cat(filename): ... cmd = ['cat', filename] # less trivial cases would be more interesting ... call(cmd) ... >>> filename = "my summer vacation.txt" >>> # remember that those quotes are Python literal syntax and aren't in the >>> string itself >>> print filename my summer vacation.txt >>> do_cat(filename) Last summer, I interned at a tech company and… >>> Generally, use (a) deliberately simple test filename(s) with shlex, then take the resulting list and replace the filename(s) with (a) variable(s). Or, just figure out the tokenization without recourse to shlex; it's not difficult in most cases! The Note in the Popen docs covers some common tokenization mistakes people make: http://docs.python.org/library/subprocess.html#subprocess.Popen Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Moving folders with content
Hello, I am working in both OS X Snow Leopard and Lion (10.6.8 and 10.7.4). I'm simply wanting to move folders (with their content) from various servers to the hard drive and then back to different directories on the servers. I want to be careful not to remove any metadata or resource forks from the files in the directories. I did a bit of researching on shutil, and looks like it is similar to using "cp -p" and copystat(), which I believe will keep the resource fork, etc. Here's the code I came up with. I'm curious if anyone finds fault with this, or if there's a better way to do this? Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> import os >>> import shutil >>> >>> p1 = os.path.expanduser('~/Desktop/IN/Test/') >>> p2 = os.path.expanduser('~/Desktop/OUT/Test/') >>> >>> if os.path.exists(p2): shutil.rmtree(p2) ... >>> shutil.copytree(p1, p2) >>> shutil.rmtree(p1) >>> Thanks! Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonOCC examples doesn't work?
On Fri, Sep 14, 2012 at 11:53 PM, Chris Angelico wrote: > On Sat, Sep 15, 2012 at 1:47 PM, Dwight Hutto wrote: >> That's no problem, But some suported ad some opposed, it's a >> democracy, but a dictatorship by the moderators. How much did I err in >> their opinion of stating my opinion, in relation to the statistical >> whole? > > Actually, I've not seen any moderatorial action on this list. Savoynet Alan Gauld quotes, "Putting on my moderator's hat", sometimes. > is as you describe, a monarchy whose head but seldom exercises power; I think it's Rossenbom(or whoever the creator of the interpreter written in C is), "who says benevolent dictator for life" > python-list/c.l.p is an anarchy - or, if you like, a true democracy. Both, depending on whether you're a freestylist, or a pythonista who follows versions. > Not a representative democracy where we all get to vote, but we all > individually have the power to kick someone out - it's called a > killfile. No, only the individual can killfile, then they miss the point of someone they should be listening to, because they kill filed for propaganda, and not an actual cause(to join a group). The more people you annoy, the more people won't hear you > any more. Annoy, how, with truth and honesty, then go away, and kill file me with the few who are ignorant of the fact I speak the truth. > -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement a combo Web and Desktop app in python.
Shawn McElroy writes: > ... > Although you are correct in the aspect of having 'real' OS level integration. > Being able to communicate with other apps as well as contextual menus. > Although, could I not still implement those features from python, into the > host system from python? There are also tools like 'kivi' which allow you to > get system level access to do things. Though im not too sure on how far that > extends, or how useful it would be. In my szenario you have a standard browser as (thin) client and Python only on the server side. In my szenario, the server could run on the clients desktop -- however, it ran there as a "service", i.e. not in "user space". My knowledge about Windows is limited. I do not really know whether a Windows "service" can fully interact with applications running in the "user space" and what limitations may apply. -- http://mail.python.org/mailman/listinfo/python-list