Re: Python memory handling
On May 31, 8:06 am, [EMAIL PROTECTED] wrote: > Hello, > > I will try later with python 2.5 under linux, but as far as I can see, > it's the same problem under my windows python 2.5 > After reading this document > :http://evanjones.ca/memoryallocator/python-memory.pdf > > I think it's because list or dictionnaries are used by the parser, and > python use an internal memory pool (not pymalloc) for them... > If I understand the document correctly you should be able to free list and dict caches if you create more than 80 new lists and dicts: [list(), dict() for i in range(88)] If it doesn't help that means 1) list&dict caches don't really work like I think or 2) pymalloc cannot return memory because of fragmentation and that is not simple to "fix". -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: pack() and the division of vertical space
On Thu, 31 May 2007 19:45:04 +0200, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I am trying to figure out how to stack two widgets in a frame > vertically so that they both expand horizontally and during vertical > expansion, the top one sticks to the top of the frame and the bottom > one consumes the remaining vertical space. I thought this would do it > but it doesn't. What am I missing? [snip code] For this kind of stuff, don't use pack; use grid. It will be far easier to get it working, to read afterwards and to maintain, even if it's slightly more verbose. IMHO, pack should only be used to create rows or columns of widgets, without any resizing policy, or to put an entire widget into a container. If you do anything more complicated than that, you'll find grid much easier to handle. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" -- http://mail.python.org/mailman/listinfo/python-list
Re: strange PyLint configuration
In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote: > [ripped out of context :-)] > Has this been updated recently? I could've sworn I had read that > stuff like has_key was "old". Yes, `has_key()` is "old", it's spelled ``in`` these days. :-) if mapping.has_key(ham): pass # -> if ham in mapping: pass Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Python in University
Hi all, My name is Tennessee Leeuwenburg. I am the Editor-In-Chief of The Python Papers (archive.pythonpapers.org). We're currently looking for contributions to our next issue. We'd love to hear from anyone who is interested in being involved. I'm also trying to track down anyone who may be using Python in a research or teaching capacity in a university environment. I'd like to talk to anyone who has an academic interest in Python. We are trying to lift the academic profile of The Python Papers, and to this end we are hoping to encourage teachers and students who are interested to publish in our journal, and also to contact their libraries regarding having TPP included as an academic journal in their library databases. We believe that The Python Papers meets all the conditions of an academic journal, including a full academic peer-review process for articles published in the "peer reviewed" section of our journal. It would be a real boost for everyone involved if we could get this recognised. It would give researchers into and using Python a place they could publish with an interested readership. It would lift the profile of Python within the academic community. It would increase our readership, and lift the profile of the journal, which would add value for contributing authors. This in no way detracts from the editorially-reviewed contributions to the magazine, which are part of what makes The Python Papers special. We see no reason why the academic community should be segregated, and indeed isolated, from the wider community. I think it would be a real achievement for all concerned to bring the two together. Thanks for your help, -Tennessee -- http://mail.python.org/mailman/listinfo/python-list
[OT] HTML Form/Page and Navigation with multiple buttons
mosscliffe a écrit : > Excellent - thanks for all your help. I now have a form created by a > python script executing an HTML page, s/executing/generating/, I think... > doing everything I need, except > for Session Data (probably use hidden fields ?? future research) HTTP is a stateless protocol, so you either have to pass *all* the relevant context from request to request or use server-side 'sessions' - which usually means using a cookie to store the session identifier on the client-side, and use some kind of persistant storage (flat files, shelves, dbm, sql dbms, whatever) on the server side. > and > the actual paging logic !!! > > If I use a link. I have to add all my hidden fields to the query > string, If you use a link, you don't use "hidden fields" at all. And yes, you have to add all the relevent context to the query string - which is *exactly* what happens if you use a form with hidden fields and submit the form with the GET method (which is the appropriate one here, since you don't want to submit data, but get data). > otherwise cgi.FieldStorage(), does not return the hidden > fields. This would also mean users see all the hidden field data. They see exactly the same thing. "hidden" fields are not a mean to store sensible informations. > Is there another way, other than a cookie ? If you want server-side sessions, you need to pass the session id from request to request. The two possible solutions are to pass this id as part of the request (either in the query string for GET requests or in the request body for POST requests) or to use cookies. > Why is a link better than a button ? Because links are the normal way to navigate from page to page. > I have been using 'post' for my form, "POST" requests are for submitting data to the server (sending comment, ordering some products, etc). Please read the HTTP specs. > to eliminate the displaying of > field values. Which "displaying" ? In the url ? Most users just don't care, and those who care are able to read the HTML source code and read these values. Don't waste your time with this. Did you bother having a look at what google urls looks like ? > I accept I am quite niave about FORM/HTML logic. This is more about the HTTP protocol than about html forms. And FWIW, none of this has anything to do with Python, so it may be good idea to post other http/ html related questions to a more appropriate newsgroup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Embed text document in excel application using python
[EMAIL PROTECTED] wrote: > Hi, > > How to embed object in excel using python? Is it me, or is this a popular question at the moment? Have a look at this post from yesterday: http://tinyurl.com/37egtt (Doesn't exactly answer, but at least points the way) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
"Tim Roberts" <[EMAIL PROTECTED]> wrote: > Carl Banks <[EMAIL PROTECTED]> wrote: > > > >Identifiers should just allow spaces. > > > >first element.get item(selected value) > > > >This is not a joke. I don't mean Python should necessarily do this > >(though it could be done without any ambiguity or backward > >incompatibility: there is currently nowhere in Python where two > >identifiers can be separated by only a space), but new languages > >should be designed to allow it. > > That's an interesting idea. It would, perhaps, allow you to write programs > that read more like prose. > > However, it would certainly make the parser more complicated, because it > could no longer be context-insensitive. For example, if I had identifiers > called "mine" and "not mine", how would it parse this: > > if not mine: The rules would have to change - currently you cannot use a reserved word (or keyword) as an identifier. It would have to be legislated that you cannot use a keyword as part of a space linked identifier - this should not be a train smash to implement, and if it makes it easier for people with disabilities, its probably not too much to ask. Hey, it could lead to self documenting code such as: That which will be returned = [] for The current element from the iterator in My iterable thingy: My temporary variable called x = The current element from the iterator if My temporary variable called x == None: break else: Temporary variable = Complicated function(My temporary variable called x) That which will be returned.append(Temporary variable) and so forth - kind of verbose, but clear... Note that I have also just invented a rule - I shall call it The German Noun Copycat Readability Style and Parser Simplification Capitalisation Rule for short. It reads: Space linked identifiers must start with a capital letter. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: speeding things up with C++
> Are you sure you want an STL container? Since the primary operator > here is Python, the extra benefits from the STL container over plain C > arrays isn't as evident. > > Pyrex is a good way to write the interface between your C++ code and > the Python code - it handles the refcounting and boilerplate for you - > and perhaps for writing the algorithms as well, depending on how > complicated and performance sensitive they are. good point. while i bow to the genius of the folks who invented template metaprogramming, the compiler error messages tend to be profoundly depressing :). one way or the other, pyrex is something i need to learn since i'm now completely enamoured with python and had better develop an arsenal of tricks for the rare times when it's just not fast enough. > Also, using numeric/Numarray can be a very big win. It can potentially > save you a fair amount of marshalling overhead. as i understand it, this is so for applying the likes of matrix operations, autocorrelations, FFTs, etc...where python essentially provides scripting glue to some highly optimised C functions. i'm assuming that the kind of algorithm i am looking at which involves some set operations on list elements + copying between lists isn't going to be helped so much by using numpy or similar. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
--- stef <[EMAIL PROTECTED]> wrote: > doing a simulation of another language (JAL), > I translate the other language into Python code, > then I execute this converted Python code. > [...] > (btw the whole program is running as an graphical > (wxPython) application) I worked on an open source project that uses Python to intrepret another language (an educational language called Guido van Robot), and it also uses wxPython to allow the user to step through the program one line at a time, and the user gets quite visual feedback. Check out these screen shots, which hopefully illustrate something along the lines of what you're trying to achieve. http://gvr.sourceforge.net/screen_shots/ During the project, we definitely had some lessons learned. The Python-based interpreter originally translated the GvR source into a Python program, and this worked great when the interface was curses. When we went to wxPython, it eventually became clear that it would be very difficult to make this approach work inside of wxPython. I'm not saying it's impossible, but in wxPython, or really any GUI app, it's hard to have your interpreted program drive things, without turing the event loop inside out. It might become easier to turn your own program inside out. I think you know where this is going... You need to build a virtual machine. It might not be quite as hard as it sounds, although it certainly depends on the complexity of the interpreted language. We ended up making the translater create an AST tree, which was essentially a tree of tiny little Python objects. We didn't create bytecode per se; the virtual machine acted directly on the AST. Then we had a stepper class step through the code. Here's the code for the stepper: http://gvr.cvs.sourceforge.net/gvr/GvR/TESTstepper.py?revision=1.28&view=markup http://gvr.cvs.sourceforge.net/gvr/GvR/stepper.py?revision=1.36&view=markup Here's the code for the translator: http://gvr.cvs.sourceforge.net/gvr/GvR/TESTgvrparser.py?revision=1.23&view=markup http://gvr.cvs.sourceforge.net/gvr/GvR/gvrparser.py?revision=1.53&view=markup When you call into the stepper, it has no notion of the GUI around it; it just has a world object that it can call simple methods on. http://gvr.cvs.sourceforge.net/gvr/GvR/guiWorld.py?revision=1.5&view=markup There's a little more code here, but hopefully the above provides a sketch. http://gvr.cvs.sourceforge.net/gvr/GvR/ It's a pretty small project, so you may just want to download all the source and check it out in action. It should run on Linux and Windows, and I know we had it running on the Macs at one point. TV dinner still cooling? Check out "Tonight's Picks" on Yahoo! TV. http://tv.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safety of dict
"Adam Olsen" <[EMAIL PROTECTED]> wrote: > So there you have it: if you're using a dict with custom classes (or > anything other than str) across multiple threads, and without locking > it, it's possible (though presumably extremely rare) for a lookup to > fail even through the key was there the entire time. Nice work. It would be an interesting exercise to demonstrate this in practice, and I think it should be possible without resorting to threads (by putting something to simulate what the other thread would do into the __cmp__ method). I don't understand your reasoning which says it cannot stay in ma_smalltable: PyDict_SetItem only calls dictresize when at least 2/3 of the slots are filled. You can have 5 items in the small (8 slot) table and the dictionary will resize to 32 slots on adding the 6th,the next resize comes when you add the 22nd item. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
[EMAIL PROTECTED] wrote: > Using the same file with cElementTree took me 217 Mb, with no > unreachable object. > For me it's not a good behavior, it's not a good way to let the system > swap this unused memory instead of freeing it. > I think it's a really good idea to have a memory pool for performance > reason, but why is there no 'free block' limit ? > Python is a really really good language that can do many things in a > clear, easier and performance way I think. It has always feet all my > needs. But I can't imagine there is no good solution for that problem, > by limiting the free block pool size or best, letting the user specify > this limit and even better, letting the user completely freeing it > (with also the limit manual specification) > > Like: > import pool > pool.free() > pool.limit(size in megabytes) > > Why not letting the user choosing that, why not giving the user more > flexibility ? Because its not easy, and its an unusual edge case that hasn't attracted developer effort (the PyMalloc change for 2.5 was contributed by someone who desperately needed it, not a core Python developer; it was also a non-trivial effort to get right). You should also appreciate something about PyMalloc: it only handles allocation requests of 256 bytes or smaller, and this limitation is part of PyMalloc's design. If most of your allocations are >256 bytes, you're at the mercy of the platform malloc and heap fragmentation can be a killer. This is probably why the getlines() approach mentioned would appear to relinquish (most of) the memory: the list was probably comprised mostly of PyMalloc allocations. I haven't checked, but cElementTree may internally not be using PyMalloc anyway, as the package is stated to be usable back to Python 1.5 - long before the current allocation management came into effect. In which case, you're at the mercy of the platform malloc... The pure Python ElementTree might play more your way, at a performance cost. -- - Andrew I MacIntyre "These thoughts are mine alone..." E-mail: [EMAIL PROTECTED] (pref) | Snail: PO Box 370 [EMAIL PROTECTED] (alt) |Belconnen ACT 2616 Web:http://www.andymac.org/ |Australia -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
> Warren Stringer wrote: > > > `c[:]()` is unambiguous because: > > > > def c(): print 'yo' > > > > c() # works, but > > c[:]() # causes: > > > > Traceback (most recent call last)... > > c[:]() # causes: > > TypeError: unsubscriptable object > > > > There are many `c()` to be found in the wild and no `c[:]()`, thus > > unambiguous. To be honest, I wasn't sure, until testing this, just now. > > >>> c = 'not quite' > >>> c[:] > 'not quite' > >>> c[:]() > Traceback (most recent call last): >File "", line 1, in ? > TypeError: 'str' object is not callable Interesting example. By extension #- >>> def c(): print 'yo' ... >>> c >>> c(bad) Traceback (most recent call last): File "", line 1, in ? NameError: name 'bad' is not defined #- Both your example and mine show well formed and ill formed statements at the command line. > You also seem to be under the impression that `x[:]()` is somehow > special syntax that is treated differently than `y = x[:]; y()`. It is > not. No; I was under the impression that `x[:]()` didn't work and the reason why it didn't work wasn't obvious. I like your use case. Am I correct in assuming that `y = x[:]; y()` is NOT to be found in working code? If that is the case, then nothing gets broken. It would be instructive to have a use case where enabling c[:]() would break existing code. > Besides, _ambiguity_ was never the problem. _Functionality_ is the > problem. Ambiguity is one of many parameters. It was a problem with another poster. I wish I had McConnel's Code Complete book handy. Let's see ... a search yields: debugging, testing, performance, portability, design, interfaces, style, and notation. My use case is this: do(orchestra(score)).pickle() do(orchestra(conductor)).sequence() And so now, that I can, I am happy. Life is good. Time to sleep. -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Sergey Dorofeev wrote: > "Peter Otten" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> Sergey Dorofeev wrote: >> >>> Please help, is there way to use sub-expressions in lambda? >>> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >>> lambda x: sin(x*x)+cos(x*x) >>> How to make x*x to be evaluated once? >> > (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + >> cos(.5*.5) >> True >> >> The real answer is of course: Use a function. > > But what about something like > > lambda x: sin(y)+cos(y) where y=x*x > > ? > May be this could be a PEP? If there is no straight way to do this. def f(x): y = x*x return sin(y) + cos(y) What is not straightforward about that? Peter -- http://mail.python.org/mailman/listinfo/python-list
Delete a file from a CGI
HI! I want to delete a file from a CGI, but I always get a Permission denied error. I've tryed this after creating the file (from a normal script): os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) but the CGI still can't delete the file. I will appreciate very much your help. Thanks a lot. -- http://mail.python.org/mailman/listinfo/python-list
subexpressions
Hello all! Please help, is there way to use sub-expressions in lambda? For example, if I want to calculate sin(x^2)+cos(x^2) I must code: lambda x: sin(x*x)+cos(x*x) How to make x*x to be evaluated once? -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safety of dict
> So there you have it: if you're using a dict with custom classes (or > anything other than str) across multiple threads, and without locking > it, it's possible (though presumably extremely rare) for a lookup to > fail even through the key was there the entire time. That could be fixed by adding a generation counter to the dictionary, right? Then an adversary would have to arrange for the generation counter to roll over for lookdict to not notice that the dictionary was modified. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
Steve Holden a écrit : > mosscliffe wrote: (snip) >> Why is a link better than a button ? >> > Beats me why you got that advice. Buttons are perfectly adequate for > that purpose. Call me a purist if you want, but I don't think forms and buttons are "perfectly adequate" for normal navigation, which should be handled by links. And FWIW, except for one of the worsts PHP portal in the world, everybody uses links for navigation. > However, you can if you want use links with "javascript: ..." href > values to accomplish local scripting which can do funky stuff like > setting form field values and submitting the form. Yuck. Anyone doing such a thing should be fired immediatly. Steve, I'm not sure you quite got what it's all about : the OP wants to *paginate* search results. Not to submit data to the server. It's just normal navigation, and there is absolutely *no* reason to use anything else than plain old links here. My 2 cents. -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting take on python OO
7stud a écrit : > http://www.evolt.org/article/OO_programming_the_Python_way/18/449/ > > - > The last article gives you the absolute basics of using Python. This > time, we'll do the OO side of Python. Yes, Python: a true object- > oriented language with classes, inheritance and all. > > Ok, my OO background comes from the usual suspects of OO language, C+ > +, Java and Object Pascal (Delphi). So I have this preconceived idea > about what Python OO should be. When I discover how OO is implemented > in Python, my first reaction was: "What the is this > s#~! ?" My idealism about OO is offended by what Python does with > object and classes. It offers a new perspective on what can be done > with classes and object. Over time Python has grown on me, and now I > can really appreciate what it can do. So if you have the same reaction > as mine, keep reading. It will grow on you as well. > > > lol > FWIW, I still don't get why people insist on believing that C++ and Java have anything to do with OO !-) (and yes, it's friday...) -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Please help, is there way to use sub-expressions in lambda? For example, if I want to calculate sin(x^2)+cos(x^2) I must code: lambda x: sin(x*x)+cos(x*x) How to make x*x to be evaluated once? >>> >> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) >> + >>> cos(.5*.5) >>> True >>> >>> The real answer is of course: Use a function. >> >> But what about something like >> >> lambda x: sin(y)+cos(y) where y=x*x >> >> ? >> May be this could be a PEP? If there is no straight way to do this. > > def f(x): >y = x*x >return sin(y) + cos(y) > > What is not straightforward about that? This code is needed once in a map, so I don't want 3+ extra lines. Solution seemed so simple... I always considered python as languague, where simple things do not require extensive coding. Moreover, this construction is common thing in functional programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: generating a tree-like structure
On 2007-05-31, Thorsten Kampe <[EMAIL PROTECTED]> wrote: > * (31 May 2007 12:15:48 -0700) >> On May 31, 12:44 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote: >> > This is a fairly general question: is there some kind of module or >> > framework that allows building a tree like structure from certain kind >> > of data? >> > >> > To be specific: I have a program that dumps the content of a LDAP >> > directory including all properties and values and groups the result >> > from the LDAP search by objClass. >> > >> > Now I was thinking: would it be possible to generate from the totally >> > unordered output that the LDAP server gives me, a tree like >> > representation that displays the hierarchy (omitting the values or >> > even properties if necessary)? >> > >> > It should be a textual representation of what you see in GUI programs >> > like "LDAP Administrator" but the output should be represented like >> > the "tree" program in Linux or Windows "tree.com". >> >> I think you might be able to use ElementTree. The website for the >> module claims it can be used for hierarchical data structures: >> http://effbot.org/zone/element-index.htm >> >> Did you look at any of the Python LDAP tools? They might be useful >> too. See some of the links below: >> http://linuxjournal.com/article/6988 >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303336 >> >> Hopefully they'll give some guidance. I've not used LDAP myself as of >> yet. > > I already have the LDAP output part working - with python-ldap under > Cygwin - and I generate HMTL output with markup.py. Pretty simple. But > a tree structure output would be even prettier... I would probably generate a DOT file to get a 2D visualization. DOT is part of Graphviz (graphviz.org), and there are quite a few graphviz front-ends available in Python to make DOT generation easier (pydot, yapgvb, and probably a few others). Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting take on python OO
On 2007-06-01, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > > FWIW, I still don't get why people insist on believing that C++ and Java > have anything to do with OO !-) > > (and yes, it's friday...) Good marketing. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
--- "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > Are there any other (simple) ways of achieving > this ? > > (btw the whole program is running as an graphical > (wxPython) application) > > use the python trace facilities. > > http://docs.python.org/lib/module-trace.html > I'm not sure how much that will help in a GUI event-driven environment like wxPython. Since the OP is generating his own Python code, he can insert his own tracing statements. I think the essential problem is how do you run the intrepreted Python program in a mode that you can have the GUI get an event, let the intrepreted program run the next instruction, have the GUI get another event, have the intrepreted program run to the next instruction, etc. There are probably ways to achieve this, such as running the intrepreted Python program in a thread, but my own experience in this in wxPython, with Guido van Robot, led me to believe that it's ultimately easier to create a virtual machine for your intepreted language. But I may be missing your point. Don't get soaked. Take a quick peak at the forecast with the Yahoo! Search weather shortcut. http://tools.search.yahoo.com/shortcuts/#loc_weather -- http://mail.python.org/mailman/listinfo/python-list
Re: How to clean a module?
ai wrote: > Yes, you are right. > But from this problem, could I infer that the statement "del xxx" > doesn't release the memory which xxx used? It just removes the name xxx from the current scope - which will result in a reference counter decrease. If that was the last reference, the object will be destroyed. Most times. There are some special cases involving the usage of __del__-methods on objects. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
On 2007-06-01, Sergey Dorofeev <[EMAIL PROTECTED]> wrote: > Hello all! > > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? lambda x: (lambda y: sin(y) + cos(y))(x*x) Albert -- http://mail.python.org/mailman/listinfo/python-list
execute a function after each source code line ?
hello, doing a simulation of another language (JAL), I translate the other language into Python code, then I execute this converted Python code. Now I need todo some checks and give visual feedback to the user, each time a line of code is executed. One way of realizing this, is to add a function call at each source code line under investigation. Are there any other (simple) ways of achieving this ? (btw the whole program is running as an graphical (wxPython) application) thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
Steve Howell wrote: > --- stef <[EMAIL PROTECTED]> wrote: > >> doing a simulation of another language (JAL), >> I translate the other language into Python code, >> then I execute this converted Python code. >> [...] >> (btw the whole program is running as an graphical >> (wxPython) application) >> > > I worked on an open source project that uses Python to > intrepret another language (an educational language > called Guido van Robot), and it also uses wxPython to > allow the user to step through the program one line at > a time, and the user gets quite visual feedback. > Check out these screen shots, which hopefully > illustrate something along the lines of what you're > trying to achieve. > > http://gvr.sourceforge.net/screen_shots/ > > Steve, that's exactly what I've in mind. The screen shots, looks really good, and I'll definitely will take a deeper look into your code. I've one advantage over you, the language I want to simulate (JAL), is very Pascal like, and therefor can be easily converted into equivalent Python code. cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Sergey Dorofeev wrote: > >> Please help, is there way to use sub-expressions in lambda? >> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >> lambda x: sin(x*x)+cos(x*x) >> How to make x*x to be evaluated once? > (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + > cos(.5*.5) > True > > The real answer is of course: Use a function. But what about something like lambda x: sin(y)+cos(y) where y=x*x ? May be this could be a PEP? If there is no straight way to do this. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
Diez B. Roggisch wrote: > stef wrote: > > >> hello, >> >> doing a simulation of another language (JAL), >> I translate the other language into Python code, >> then I execute this converted Python code. >> >> Now I need todo some checks and give visual feedback to the user, >> each time a line of code is executed. >> >> One way of realizing this, is to add a function call at each source code >> line under investigation. >> >> Are there any other (simple) ways of achieving this ? >> (btw the whole program is running as an graphical (wxPython) application) >> > > use the python trace facilities. > > http://docs.python.org/lib/module-trace.html > thanks Diez, that looks exactly what I need. cheers, Stef > Diez > -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Sergey Dorofeev wrote: > > "Peter Otten" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? >>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) >>> + cos(.5*.5) True The real answer is of course: Use a function. >>> >>> But what about something like >>> >>> lambda x: sin(y)+cos(y) where y=x*x >>> >>> ? >>> May be this could be a PEP? If there is no straight way to do this. >> >> def f(x): >>y = x*x >>return sin(y) + cos(y) >> >> What is not straightforward about that? > > This code is needed once in a map, Perhaps you like [sin(y)+cos(y) for y in (x*x for x in items)] then. > so I don't want 3+ extra lines. What syntax would you suggest for a lambda enhanced to cover your use case? I suppose you will end up with roughly the same number of characters, all crammed in one line -- or broken into lines at a random position as it happens with overambitious list comprehensions. > Solution seemed so simple... It /is/ simple. > I always considered python as languague, where simple things do not > require extensive coding. In Python, when conciseness and readability compete, readability tends to win (with the inline if...else as a notable exception). > Moreover, this construction is common thing in functional programming. I can write Haskell in any language :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
Steve Howell wrote: > > > I think itertools.groupby() is usually the key > batteries-included component in elegant solutions to > this problem, but I wonder if the Python community > couldn't help a lot of newbies (or insufficiently > caffeinated non-newbies) by any of the following: > Well, I'm not a newbie, and I always make sure to be thoroughly caffeinated before sitting down for coding. But I think the itertools example in the parent post shows a problem with that package: unless you have intimate knowledge of the package, it is not clear what the code does when reading it. In other words, it is not intuitive. Perhaps a dedicated "block-read" module that wraps any read()-able object would be better. At least it would immediately be clear what the code means. from blockread import BlockReader b = BlockReader(f, boundary='>') for block in b: # whatever -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy make money!
On Apr 22, 1:06 am, John Nagle <[EMAIL PROTECTED]> wrote: > Dustan wrote: > > On Apr 21, 3:45 pm,GPcapital<[EMAIL PROTECTED]> wrote: > > >>Lately I've been surfing trought some web pages and got this one > >>www.gpcapitalgroup.com. It looks quite interesting, it may be a great > >>chance to invest. > > advertisement.delete() > > I couldn't resist. I ran that through SiteTruth, our automatic > website legitimacy checker (written in Python, of course). > > http://www.sitetruth.com/cgi-bin/ratingdetails.cgi?url=www.gpcapitalg... > > Not found in Open Directory. > Not found in US business database. > No address found on site. > No usable SSL certificate. > Rating: "Site ownership unknown or questionable." > > Any questions? > > John Nagle I update the site look up -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
In <[EMAIL PROTECTED]>, Warren Stringer wrote: > I like your use case. Am I correct in assuming that `y = x[:]; y()` is NOT > to be found in working code? If that is the case, then nothing gets broken. > It would be instructive to have a use case where enabling c[:]() would break > existing code. What does "enabling c[:]()" mean? Do you expect after "enabling it" ``c()`` and ``c[:]()`` to be different for the same list or tuple `c`? > My use case is this: > > do(orchestra(score)).pickle() > do(orchestra(conductor)).sequence() This isn't a use case unless you also say what the involved objects are and what semantic you expect from this source snippet. Just guessing, but might the following do what you want without the need to make lists and tuples callable? def do(iterable, func): for item in iterable: func(item) do(orchestra(score), pickle) do(orchestra(conductor), sequence) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: calling Postgresql stored procedure (written in plpython)
Thanks for your help. My stored procedure is written in pythonpl. I noticed that SELECT queries are executed correctly (results are returned to my script) whereas UPDATE queries are not being performed as the data is not updated. I am using a database user with read/write access to the database. Is there a commit statement in plpython? (e.g. plpy.commit()) Why are UPDATEs failing? -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
--- Tijs <[EMAIL PROTECTED]> wrote: > > Yes, or a single one that takes a wide range of > construction possibilities, > like strings, lambdas or regexes in various keyword > parameters. > > BlockReader(f, start='>') > BlockReader(f, start=re.compile('>|<'), end='---') > BlockReader(f, start=lambda x: x.startswith('>')) > Definitely. I like your idea for regexes that you just pass the method in, rather than the regex. It means fewer variations, and it also leads to slightly more explicit code from the user, without being too cumbersome. Do you have any free time on your hands? It seems like it would be fairly straightforward to do a quick prototype implementation of this. I'm off to work soon, so I can't do it today, but maybe Sunday. Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Sergey Dorofeev wrote: > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? >>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + cos(.5*.5) True The real answer is of course: Use a function. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
--- Tijs <[EMAIL PROTECTED]> wrote: > Steve Howell wrote: > > [...] but I wonder if the Python community > > couldn't help a lot of newbies (or insufficiently > > caffeinated non-newbies) by any of the following: > > > Well, I'm not a newbie, and I always make sure to be > thoroughly caffeinated > before sitting down for coding. :) > But I think the > itertools example in the > parent post shows a problem with that package: > unless you have intimate > knowledge of the package, it is not clear what the > code does when reading > it. In other words, it is not intuitive. > Agreed. > Perhaps a dedicated "block-read" module that wraps > any read()-able object > would be better. At least it would immediately be > clear what the code > means. > > from blockread import BlockReader > > b = BlockReader(f, boundary='>') > for block in b: > # whatever > Yep, I like this idea. You might have a few variations: def simple_block_reader(f, start_char='>'): # returns list or iterator where each item # is a list of lines all belonging to the same # block def regex_block_reader(f, start_regex, end_regex=None): # start_regex is regular expression to match on # if end_regex is none, then end of block is # signified by start of next block or end of file def block_reader3(f, start_method, end_method=None): # start_method, end_method should be functions # that evaluate line, return True/False # # if end_method is None, then end of block is # signified by start of next block or end of # input stream Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
--- "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote: > > lambda x: (lambda y: sin(y) + cos(y))(x*x) > Elegant. I find the use of y confusing there (thinking about the unit circle), so I'd amend it to this: lambda x: (lambda x2: sin(x2) + cos(x2))(x*x) But I like the overall idea. No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > What syntax would you suggest for a lambda enhanced to cover your use > case? > I suppose you will end up with roughly the same number of characters, all > crammed in one line -- or broken into lines at a random position as it > happens with overambitious list comprehensions. Agree, this argument is strong. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
stef wrote: > hello, > > doing a simulation of another language (JAL), > I translate the other language into Python code, > then I execute this converted Python code. > > Now I need todo some checks and give visual feedback to the user, > each time a line of code is executed. > > One way of realizing this, is to add a function call at each source code > line under investigation. > > Are there any other (simple) ways of achieving this ? > (btw the whole program is running as an graphical (wxPython) application) use the python trace facilities. http://docs.python.org/lib/module-trace.html Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On Thu, 31 May 2007 18:42:05, Warren Stringer <[EMAIL PROTECTED]> wrote >They were copied from working code. Copied *badly*? Yes. Running python via: > Windows -> start -> run -> python >doesn't allow cut and paste Hi Warren, Actually you can copy and paste from a Windows cmd/command shell: right-click the title-bar of the window, select "Edit" from the pop-up menu, then "Mark" from the sub-menu to copy whatever you want to select into the Windows clipboard. HTH, -- Doug Woodrow -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Sergey Dorofeev wrote: > "Peter Otten" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? >>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) >>> + cos(.5*.5) True The real answer is of course: Use a function. >>> But what about something like >>> >>> lambda x: sin(y)+cos(y) where y=x*x >>> >>> ? >>> May be this could be a PEP? If there is no straight way to do this. >> def f(x): >>y = x*x >>return sin(y) + cos(y) >> >> What is not straightforward about that? > > This code is needed once in a map, so I don't want 3+ extra lines. > Solution seemed so simple... > I always considered python as languague, where simple things do not require > extensive coding. > Moreover, this construction is common thing in functional programming. > > Stop thinking of three lines as "extensive coding" and your problem disappears immediately. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundup, smtplib, TLS and MS Exchange
carlistixx wrote: > [EMAIL PROTECTED] tracker]$ roundup-server -p 8081 > roundup=/home/foobar/roundup/tracker > Roundup server started on :8081 > send: 'STARTTLS\r\n' > reply: '503 5.5.2 Send hello first\r\n' > reply: retcode (503); Msg: 5.5.2 Send hello first I think this must be an issue with roundup, issuing commands in the wrong order. The correct order should (according to the rfc and the python docs) be: * ehlo() * starttls() * ehlo() * login() ... -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: speeding things up with C++
bullockbefriending bard skrev: > good point. while i bow to the genius of the folks who invented > template metaprogramming, the compiler error messages tend to be > profoundly depressing :). one way or the other, pyrex is something i > need to learn since i'm now completely enamoured with python and had > better develop an arsenal of tricks for the rare times when it's just > not fast enough. A dash of c combined integrated via ctypes is probably the easiest solution? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Steve Howell wrote: > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. No, x may be an object that has the __mul__ special method, and it may have side effects. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding tuples to a dictionary
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Let me comment on what happens in you're code: > The place where you create new objects is > keys = [str(x) for x in range(20)] # here you create 20 > strings which will be reused ( by reference ) >and > my_dict[key] = (key, key) # here you create a new tuple with 2 > elements > ( both are key, so you're taking a > reference of existing key object twice ) > The tricky part is where you wrote: > for key in keys: > my_dict[key] = (key, key) > list_of_dicts.append(my_dict) # note that > list_of_dicts.append is in the loop! check upstairs! > This means that my_dict reference will be stored 20 times, and it > won't be released. > statement > my_dict = {} > will always create new my_dict ( 20 times means 20 new dictionaries ) > and start over. > Since python caches free dictionaries ( after delete - they're used > everywhere ), > reuse won't happen, and memory will have to be allocated again. [snip] > The reason why you have a growing time comes from the fact that memory > allocation takes place instead of object > being used by reference. Check the memory usage, and you'll see that > test time is pretty much proportional to overall memory usage. That agrees with my analysis also - it is all about memory usage due to the duplicated (key, key) tuples. In fact it puts my machine into swap at the larger iteration numbers! Here is storing them in a cache which runs nice and fast! import time list_of_dicts = [] keys = [str(x) for x in range(20)] tuple_cache = {} prev_clk = time.clock() for i in range(20): my_dict = {} for key in keys: value = tuple_cache.setdefault((key, key), (key, key)) my_dict[key] = value list_of_dicts.append(my_dict) new_clk = time.clock() print i, new_clk - prev_clk prev_clk = new_clk 0 1.0 1 0.39 2 0.41 3 0.39 4 0.39 5 0.4 6 0.41 7 0.39 8 0.4 9 0.4 10 0.39 11 0.4 12 0.4 13 0.39 14 0.4 15 0.4 16 0.39 17 0.4 18 0.39 19 0.41 Note the first iteration is slower as it builds the tuple cache -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
Andrew MacIntyre <[EMAIL PROTECTED]> wrote: > You should also appreciate something about PyMalloc: it only handles > allocation requests of 256 bytes or smaller, and this limitation is part > of PyMalloc's design. > > If most of your allocations are >256 bytes, you're at the mercy of the > platform malloc You can tweak this if you are using libc (eg under linux) at least :- http://www.gnu.org/software/libc/manual/html_node/Malloc-Tunable-Parameters.html Setting M_MMAP_THRESHOLD should result in blocks that are perfectly free()able back to the OS if allocated with malloc(). By default this is 128k I think so you can set it to 4k and it should help a lot. Note that a mmap block is a minimum of 4k (under x86 - one OS page anyway) so set this too small and you program will use a *lot* of memory, but only temporarily ;-) If PyMalloc stretched up to 4k and M_MMAP_THRESHOLD was set to 4k then you'd have the perfect memory allocator... -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
cStringIO change in 2.4 vs 2.5. Regression?
Hello, I just stumbled accross a difference between cStringIO in Python 2.4 and 2.5. You can no longer feed arrays to cStringIO. Python 2.4: ---%<--- ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from array import array >>> a = array('B', (0, 1, 2)) >>> a array('B', [0, 1, 2]) >>> from StringIO import StringIO >>> StringIO(a) >>> from cStringIO import StringIO >>> StringIO(a) --->%--- Python 2.5: ---%<--- Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from array import array >>> a = array('B', (0, 1, 2)) >>> a array('B', [0, 1, 2]) >>> from StringIO import StringIO >>> StringIO(a) >>> from cStringIO import StringIO >>> StringIO(a) Traceback (most recent call last): File "", line 1, in TypeError: expected a character buffer object --->%--- Has this change been done on purpose or is it a regression? If it's not a regression, is there another way to feed an array to cStringIO without expensive conversion? TIA, Markus -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
--- stef <[EMAIL PROTECTED]> wrote: > the language I want to simulate (JAL), > is very Pascal like, > and therefor can be easily converted into equivalent > Python code. > One more idea. If you haven't already, maybe you can post something to the PyPy community to effect of this: ''' I have a Python-like language that I translate to Python code, and I want to write another Python program in wxPython that executes the former Python program in a step-by-step fashion. ''' I'm sure there are some folks there that eventually want to tackle the same problem, and if nothing else, they might help you out with some terminology for describing your problem. Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -- http://mail.python.org/mailman/listinfo/python-list
Re: generating a tree-like structure
--- "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote: > > I would probably generate a DOT file to get a 2D > visualization. DOT is part of > Graphviz (graphviz.org), and there are quite a few > graphviz front-ends > available in Python to make DOT generation easier > (pydot, yapgvb, and probably > a few others). > +1 on Graphviz/DOT I've used them before (e.g. to display relationships between Python modules). They are very cool tools. ___ You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On Fri, 1 Jun 2007 07:23:16, Steve Holden <[EMAIL PROTECTED]> wrote >> Actually you can copy and paste from a Windows cmd/command shell: >>right-click the title-bar of the window, select "Edit" from the pop-up >>menu, then "Mark" from the sub-menu to copy whatever you want to >>select into the Windows clipboard. > >Better still, modify your shortcut by bring up the command window's >Properties page and setting "Quick Edit Mode". Then you can select with >the mouse and hit Enter to copy. Cool, thanks Steve! Newsgroups really are a good way of learning new things quickly. -- Doug Woodrow -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5.1 broken os.stat module
""Martin v. Löwis"" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >> I created a file and specifically set the created date, last accessed >> date >> and last write date to >> >> 01/02/2003 12:34:56 > > How did you do that? I used a "touch" utility to set the dates but let's try it a different way. Let's use Python 2.5.1 to set the timestamps >> set file timestamp import pywintypes import win32file import sys file_name = sys.argv[1] new_timestamp = pywintypes.Time([2003, 1, 2, 12, 34, 56]) f = win32file.CreateFile(file_name, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, 0) win32file.SetFileTime(f, new_timestamp, new_timestamp, new_timestamp) f.Close() Next I created an empty file with notepad. Then I used the above code to set the 3 timestamps. Let's confirm that Windows has the timestamps set to what we set them too. Here are the timestamps as reported by Windows: dir /tc joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /ta joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /tw joe.txt 01/02/2003 12:34 PM 0 joe.txt Looks like the python code worked to correctly set the timestamps (Note you can also verify them using properties on the file in Windows Explorer) Here is some python code to print out the timestamps: import os import stat import sys import time file_name = sys.argv[1] file_stats = os.stat(file_name) print 'CreationTime: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_CTIME])) print 'Last Access Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_ATIME])) print 'Last Write Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_MTIME])) Now let's see what Python 2.4.2 says about the file CreationTime: 01/02/2003 12:34:56 Last Access Time: 01/02/2003 12:34:56 Last Write Time: 01/02/2003 12:34:56 Looks like Python 2.4.2 is reporting the timestamps correctly Now let's see what Python 2.5.1 says CreationTime: 01/02/2003 11:34:56 Last Access Time: 01/02/2003 11:34:56 Last Write Time: 01/02/2003 11:34:56 All times are off by 1 hour! Let's re-verify that Windows still says the timestamps are 01/02/2003 12:34:56. dir /tc joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /ta joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /tw joe.txt 01/02/2003 12:34 PM 0 joe.txt Windows still says the times are what we set them too. Opening up Windows Explorer also confirms that the times are still 01/02/2003 12:34:56. My text editor has a was to display the file names and timestamp info just like a dir command Let's see what it says: h: joe.txt0 1/02/03 12:34 \ The text editor is reporting the correct timestamps too. So far everything else I try seems to report the timestamps correctly except for Python 2.5.1. It is difficult for me to believe that EVERYTHING else is wrong and Python 2.5.1 is correct, especially when you consider the fact that the code in Python 2.5.1 that performs this functionality is not the same code that was used in previous Python versions. Normally if something is not working, the biggest suspect is the last thing changed. In my other msg I posted a program that compares the timestamps of a dir /tc, dir /ta, and dir /tw for all files against what Python is reporting. This allows us to easily verify what Windows says the timestamps are versus what Python says they are. Python 2.4.2 ALWAYS got it correct. Python 2.5.1 gets it wrong as much as 50% of the time. So unless you are saying that Windows is wrong, Python 2.5.1 has to be wrong since it does not compare to what Windows reports. Since everything else I have tried matches what Windows reports that leads me to believe that Python 2.5.1 has to be wrong. >> I even found situations where the python timestamp was 1 minute later. >> (I >> know about the 2 second timestamps on FAT, all my filesystems are NTFS). >> I >> just found a situation where the python timestamp was 02:51 PM and the >> windows timestamp was 02:12 PM. DST or timezone changes are not going >> to >> make the results be off by 39 minutes? (My timezone is GMT - 5:00). > > Right. If that is reproducable, it is a bug. Please create a zip file > containing this file, and submit a bug report to sf.net/projects/python. Please see my other msg, I ran the program in that msg against the Python\lib directory: I tried it on multiple machines and found the same problems occurring. I already submitted a bug report with the sample code that demonstrates the problem. All Python 2.4.2 timestamps match what Windows reports The Python 2.5.1 timestamps vary Sometimes python is +1 minute Sometimes python is -1 hour Sometimes python is +59 minutes Sometimes python is +42 minutes Sometimes python is +37 minutes Sometimes python +2
RE: c[:]()
> Warren Stringer wrote: > > > As mentioned a while back, I'm now predisposed towards using `do(c)()` > > because square brackets are hard with cell phones. The one mitigating > factor > > for more general use, outside of cell phones, is speed. > > The speed at which you can type code is almost _never_ a valid reason to > make something brief. Code gains readability from verbosity. (That can > be taken too far, of course, but that certainly doesn't apply here.) There is code that you type which persists and code that you type from a command line. Two completely different idioms. A credo inside the cell phone game industry is that you lose half your audience with each menu keystroke. That's how precious keystrokes are. What may be confusing is speaking about both idioms at once. > In short, your repeated use of `c[:]()` indicates a fundamental > misunderstanding about Pythonic style _and_ substance. Please define Pythonic. Is this like a certain US senator who defined porn as "I know it when I see it." 28 years ago, I wrote a hierarchical DBMS that used lexical indentation. 15 years ago I wrote a multimedia script language that used lexical indentation and automatic garbage collection - it was deployed on millons of clients. 2 years ago I hand coded every line of the Python 2.2 BNF into another style of language description. Up until last month, I had tokenized a subset of said definition in C++, using templates to manage cardinality. Recently, I decided to forgo the C++ parser and am now rewriting it in Python. This is a risk. So, what hoop does one jump though to earn that oh so coveted "pythonic" merit badge? Your other post responds with working examples. So, I'll jump over to that one. -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
Steve Howell wrote: >> >> from blockread import BlockReader >> >> b = BlockReader(f, boundary='>') >> for block in b: >> # whatever >> > > Yep, I like this idea. You might have a few > variations: > Yes, or a single one that takes a wide range of construction possibilities, like strings, lambdas or regexes in various keyword parameters. BlockReader(f, start='>') BlockReader(f, start=re.compile('>|<'), end='---') BlockReader(f, start=lambda x: x.startswith('>')) Maybe make variations for character-based readers and line-based readers. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Steve Holden a écrit : (snip) > Stop thinking of three lines as "extensive coding" and your problem > disappears immediately. Lol ! +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
On 1 Jun, 12:55, Steve Howell <[EMAIL PROTECTED]> wrote: > > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. On the basis of you believing that x is one of the built-in numeric types, yes, but how does the compiler know that? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Steve Howell wrote: > --- Sergey Dorofeev <[EMAIL PROTECTED]> wrote: >> > What syntax would you suggest for a lambda >> enhanced to cover your use >> > case? >> > I suppose you will end up with roughly the same >> number of characters, all >> > crammed in one line -- or broken into lines at a >> random position as it >> > happens with overambitious list comprehensions. >> >> Agree, this argument is strong. >> > > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. Of course it's not. You can create arbitrarily overloaded __mul__-operators here. Unless you can guarantee that the objects in question are immutable (which you can only for python-builtins), you can't be sure that there are no sideeffects. And the needed guarding statements for this kind of optimization might well eat up the gain from not multiplying two numbers together. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete a file from a CGI
When you execute a cgi, the program runs under the "apache user" (ussualy www or wwwrun or so), so THAT user needs permissions for deleting the file. Other approach could be suid'ing the cgi program. Gerardo >HI! > >I want to delete a file from a CGI, but I always get a Permission denied >error. > >I've tryed this after creating the file (from a normal script): > >os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) >os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) > >but the CGI still can't delete the file. > >I will appreciate very much your help. > >Thanks a lot. > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: getmtime differs between Py2.5 and Py2.4
Joe Salmeri: > I can see that you guys have already spent alot of time investigating this > but surely the results should match what Windows Explorer says or what the > dir command returns??? One problem I have seen is that Windows Explorer and its File Properties sheet sometimes cache time values. Even closing and reopening the properties can show the old value. dir should always read the times though. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
Steve Howell wrote: > Do you have any free time on your hands? Nope. I think Python is a programmer's language, not a whack-something-together script language for text processing (although it is used that way). Any decent programmer has no need of this construct, since the time to lookup how to use it is larger than the time to implement the specialized version for the task at hand. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Steve Holden <[EMAIL PROTECTED]> wrote: >> Actually you can copy and paste from a Windows cmd/command shell: >> right-click the title-bar of the window, select "Edit" from the pop-up >> menu, then "Mark" from the sub-menu to copy whatever you want to select >> into the Windows clipboard. >> >> HTH, > > Better still, modify your shortcut by bring up the command window's > Properties page and setting "Quick Edit Mode". Then you can select with > the mouse and hit Enter to copy. > Even better use regedit to set key HKEY_CURRENT_USER\Console, value QuickEdit to 1. Then you have copy and paste enabled for all console windows by default. -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Grant Edwards <[EMAIL PROTECTED]> wrote: > [Please quit saying "a container" if you mean lists and tuples. > "A container" is way too general. There most probably _are_ > containers for which c() does not fail.] One example of such a container is any folderish content in Zope: subscripting gets you the contained pages, calling renders the default view. -- http://mail.python.org/mailman/listinfo/python-list
logging module: log file with datetime
Hi I have this logging config file; [loggers] keys=cdmto [handlers] keys=cdmtoHandler [formatters] keys=mtoFormatter [logger_cdmto] level=DEBUG handlers=cdmtoHandler qualname=cdmto propagate=0 [handler_cdmtoHandler] class=handlers.TimedRotatingFileHandler level=DEBUG formatter=mtoFormatter args=('./Logs/cdmto.log',) [formatter_mtoFormatter] format=%(asctime)s %(levelname)-8s %(filename)s[%(lineno)d]: % (message)s datefmt= How could I define a log file with datetime in his name?. Now the name for log file is './Logs/cdmto.log' and I'd like it would be './ Logs/cdmto_20070601.log', for example. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function after each source code line ?
--- stef <[EMAIL PROTECTED]> wrote: > Steve, > that's exactly what I've in mind. > The screen shots, looks really good, > and I'll definitely will take a deeper look into > your code. Cool, good luck. Feel free to contact me privately if you have questions about the implementation. There's also a mailing list for GvR, although it's not that active at the moment. It's not that the project is dead, we just don't have much to add to it at this point. :) > I've one advantage over you, > the language I want to simulate (JAL), > is very Pascal like, > and therefor can be easily converted into equivalent > Python code. > FWIW the language I was interpeting is also Pascal-like, and as I mentioned, we initially translated it into Python code as well. Even when we abandoned the idea of using Python to run the program (er, this is like describing PyPy, we were still using Python at the outer level, just not the inner level), we still kept the code around to translate from GvR to Python. The translations from GvR to Python made it easy for us to write unit tests like this: ''' if front_is_blocked: turnleft if front_is_blocked: turnleft if front_is_blocked: turnleft move ''', ''' if self.FRONT_IS_BLOCKED(0): self.TURNLEFT(1) if self.FRONT_IS_BLOCKED(2): self.TURNLEFT(3) if self.FRONT_IS_BLOCKED(4): self.TURNLEFT(5) self.MOVE(6) ''' More here: http://gvr.cvs.sourceforge.net/*checkout*/gvr/GvR/TESTgvrparser.py?revision=1.23&content-type=text%2Fplain Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
Bruno Desthuilliers wrote: > Steve Holden a écrit : >> mosscliffe wrote: > (snip) >>> Why is a link better than a button ? >>> >> Beats me why you got that advice. Buttons are perfectly adequate for >> that purpose. > > Call me a purist if you want, but I don't think forms and buttons are > "perfectly adequate" for normal navigation, which should be handled by > links. And FWIW, except for one of the worsts PHP portal in the world, > everybody uses links for navigation. > >> However, you can if you want use links with "javascript: ..." href >> values to accomplish local scripting which can do funky stuff like >> setting form field values and submitting the form. > > Yuck. Anyone doing such a thing should be fired immediatly. > > Steve, I'm not sure you quite got what it's all about : the OP wants to > *paginate* search results. Not to submit data to the server. It's just > normal navigation, and there is absolutely *no* reason to use anything > else than plain old links here. > > My 2 cents. > You're right, the English was contorted enough for me to miss the point. Buttons do seem a bit unnecessary, even to someone who hasn't drunk the REST Kool-Aid. Yet. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
In <[EMAIL PROTECTED]>, Warren Stringer wrote: >> Warren Stringer wrote: >> >> > As mentioned a while back, I'm now predisposed towards using `do(c)()` >> > because square brackets are hard with cell phones. The one mitigating >> factor >> > for more general use, outside of cell phones, is speed. >> >> The speed at which you can type code is almost _never_ a valid reason to >> make something brief. Code gains readability from verbosity. (That can >> be taken too far, of course, but that certainly doesn't apply here.) > > There is code that you type which persists and code that you type from a > command line. Two completely different idioms. A credo inside the cell phone > game industry is that you lose half your audience with each menu keystroke. > That's how precious keystrokes are. > > What may be confusing is speaking about both idioms at once. > > > >> In short, your repeated use of `c[:]()` indicates a fundamental >> misunderstanding about Pythonic style _and_ substance. > > Please define Pythonic. Is this like a certain US senator who defined porn > as "I know it when I see it." Yes you are right, "pythonic" is not a hard fact. But one indicator is consistency and no surprising behavior if possible. And that your insisting on ``c[:]()`` instead of just ``c()`` seems to indicate you want a change that is quite surprising. It would mean that a slice of a list returns an other type with the __call__ method implemented. > 28 years ago, I wrote a hierarchical DBMS that used lexical indentation. 15 > years ago I wrote a multimedia script language that used lexical indentation > and automatic garbage collection - it was deployed on millons of clients. 2 > years ago I hand coded every line of the Python 2.2 BNF into another style > of language description. Up until last month, I had tokenized a subset of > said definition in C++, using templates to manage cardinality. Recently, I > decided to forgo the C++ parser and am now rewriting it in Python. This is a > risk. So, what hoop does one jump though to earn that oh so coveted > "pythonic" merit badge? Grok The Zen of Python (``import this`` at the interpreter prompt)? Write "pythonic" code? I don't see how writing other languages and Python parsers and translators into other representations tells you much about the spirit and idiomatic *usage* of a language. Your proposal is not about syntax, it's about semantics. ``obj[:]()`` is basically syntactic sugar for: ``obj.__getitem__(slice(None)).__call__()`` and you want a change in the implementation of `list.__getitem__()` and `tuple.__getitem__()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
Sergey Dorofeev wrote: > "Peter Otten" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> Sergey Dorofeev wrote: >> >>> Please help, is there way to use sub-expressions in lambda? >>> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >>> lambda x: sin(x*x)+cos(x*x) >>> How to make x*x to be evaluated once? > (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + >> cos(.5*.5) >> True >> >> The real answer is of course: Use a function. > > But what about something like > > lambda x: sin(y)+cos(y) where y=x*x > > ? > May be this could be a PEP? If there is no straight way to do this. > > Or maybe it could be made a part of some other language. When straightforward mechanisms (in rhis case, function definitins) exist to avoid repeated computations it's very unlikely that such mangled constructions will be made a part of Python. If it *were* considered, you should at least change the "where" to "for", and extend it to unpacking assignment to allow lambda x, y: (sin(xx+yy) + cos(xx+yy) for xx, yy = x*x, y*y regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
--- Sergey Dorofeev <[EMAIL PROTECTED]> wrote: > > What syntax would you suggest for a lambda > enhanced to cover your use > > case? > > I suppose you will end up with roughly the same > number of characters, all > > crammed in one line -- or broken into lines at a > random position as it > > happens with overambitious list comprehensions. > > Agree, this argument is strong. > FWIW there's the possibility that even without a subexpression syntax, some Python implementations would detect the duplication of x*x and optimize that for you. It would have to know that x*x had no side effects, which I think is a safe assumption even in a dynamic language like Python. I know the CPython implementation does do some types of optimizations (peephole, etc.), but I'm not expert enough to know whether this kind of optimization would be detected. Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete a file from a CGI
Matias Surdi wrote: > HI! > > I want to delete a file from a CGI, but I always get a Permission denied > error. > > I've tryed this after creating the file (from a normal script): > > os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) > os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) > > but the CGI still can't delete the file. > > I will appreciate very much your help. > > Thanks a lot. > > How was the file created in the first place? If you don't have permissions to delete it you may well not have permissions to reown it or change its permissions either! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Douglas Woodrow wrote: > On Thu, 31 May 2007 18:42:05, Warren Stringer <[EMAIL PROTECTED]> wrote >> They were copied from working code. Copied *badly*? Yes. Running python via: >> Windows -> start -> run -> python >> doesn't allow cut and paste > > Hi Warren, > > Actually you can copy and paste from a Windows cmd/command shell: > right-click the title-bar of the window, select "Edit" from the pop-up > menu, then "Mark" from the sub-menu to copy whatever you want to select > into the Windows clipboard. > > HTH, Better still, modify your shortcut by bring up the command window's Properties page and setting "Quick Edit Mode". Then you can select with the mouse and hit Enter to copy. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
--- Tijs <[EMAIL PROTECTED]> wrote: > Steve Howell wrote: > > FWIW there's the possibility that even without a > > subexpression syntax, some Python implementations > > would detect the duplication of x*x and optimize > that > > for you. It would have to know that x*x had no > side > > effects, which I think is a safe assumption even > in a > > dynamic language like Python. > > No, x may be an object that has the __mul__ special > method, and it may have > side effects. > Ok, I stand corrected. Duplicate subexpressions are pretty easy to avoid in Python, so though an optimization would not be impossible here (checking for immutability of builtins, etc., which still assumes the idea that multiplication is more expensive than checking for immutability even for the common builtin case), it would not be worthwhile. Shortly after I posted, there was an elegant solution to avoiding having to repeat x*x in the lambda, so the point's kind of moot now. Shape Yahoo! in your own image. Join our Network Research Panel today! http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: > There is code that you type which persists and code that you type from a > command line. Two completely different idioms. A credo inside the cell phone > game industry is that you lose half your audience with each menu keystroke. > That's how precious keystrokes are. Then why do have your users typing code into a cell phone? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
On Fri, 2007-06-01 at 08:39 -0400, Carsten Haese wrote: > On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: > > There is code that you type which persists and code that you type from a > > command line. Two completely different idioms. A credo inside the cell phone > > game industry is that you lose half your audience with each menu keystroke. > > That's how precious keystrokes are. > > Then why do have your users typing code into a cell phone? _.replace("do", "do you") self.drink(coffee) -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
> Ok, I stand corrected. > > Duplicate subexpressions are pretty easy to avoid in > Python, so though an optimization would not be > impossible here (checking for immutability of > builtins, etc., which still assumes the idea that > multiplication is more expensive than checking for > immutability even for the common builtin case), it > would not be worthwhile. > > Shortly after I posted, there was an elegant solution > to avoiding having to repeat x*x in the lambda, so the > point's kind of moot now. The elegance of that solution very much depends on the cost of the duplicate operation vs. the additional function call. And for the usecase at hand, that's exactly the point not to do it: [EMAIL PROTECTED]:/tmp$ python -m timeit '(lambda x: lambda y: y+y)(10 * 10)' 100 loops, best of 3: 1.04 usec per loop [EMAIL PROTECTED]:/tmp$ python -m timeit 'lambda: 10 * 10 + 10 * 10' 100 loops, best of 3: 0.336 usec per loop Diez -- http://mail.python.org/mailman/listinfo/python-list
unknown host
I have a linux machine (ip = 10.10.10.8), which can ping other machines on the same subnet...such as 10.10.10.1 10.10.10.2 10.10.10.5 10.10.10.6 10.10.10.254 If I use socket.gethostbyaddr() I get back results when ip is 10.10.10.1 and 10.10.10.254 but for the other IP addresses (10.10.10.5, .6, etc) I get back "unknown host". In fact I get "unknown host" for the linux machine that I run the gethostbyaddr from. If perform the same operation from a windows machine (ip = 10.10.10.5) it returns data for the other IP addresses as expected. any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageMagick Issue
Sick Monkey escribió: > I ran into another slight problem. And I attempted to fix it, but have > not been able to do so yet. If a filename does not contain a space, > then this method works like a charm. But if there is a space then the > code throws a nasty error. Ok, the issue is that subprocess.Popen needs a list of the arguments. So, for simplicity, I made an string and then splitted it: >>> s = "ls -l /etc" >>> s.split() ['ls', '-l', '/etc'] >>> This does not work if you have spaces, even if you escape them: >>> s = "ls -l '/etc/mi file'" >>> s.split() ['ls', '-l', "'/etc/mi", "file'"] >>> But you can always build the list by hand: >>> subprocess.Popen(["ls", "-l", "'/etc/mi file'"], ... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: unknown host
On Jun 1, 2007, at 8:09 AM, abcd wrote: > I have a linux machine (ip = 10.10.10.8), which can ping other > machines on the same subnet...such as > > 10.10.10.1 > 10.10.10.2 > 10.10.10.5 > 10.10.10.6 > 10.10.10.254 > > If I use socket.gethostbyaddr() I get back results when ip is > 10.10.10.1 and 10.10.10.254 but for the other IP addresses > (10.10.10.5, .6, etc) I get back "unknown host". In fact I get > "unknown host" for the linux machine that I run the gethostbyaddr > from. > > If perform the same operation from a windows machine (ip = 10.10.10.5) > it returns data for the other IP addresses as expected. > > any ideas? socket.gethostbyaddr() is trying to use a name server to look up the address. It may be that you haven't specified a valid name server in /etc/resolv.conf, or maybe /etc/nsswitch.conf is misconfigured, or maybe your name server doesn't want to play. The fact that you were able to ping addresses have nothing to do with resolving their hostnames. hope this helps, Michael --- A clever person solves a problem. A wise person avoids it. --Albert Einstein -- http://mail.python.org/mailman/listinfo/python-list
Re: logging module: log file with datetime
On 1 Jun, 13:00, Álvaro Nieto <[EMAIL PROTECTED]> wrote: > How could I define a log file with datetime in his name?. Now the > name > for log file is './Logs/cdmto.log' and I'd like it would be './ > Logs/cdmto_20070601.log', > for example. > You can't do this just in the configuration - TimedRotatingFileHandler automatically works out the filename in a predetermined manner when doing rollover (dependent on whether it's doing rollovers daily, hourly or whatever period). If you need more specific handling, you'll need to write a subclass of TimedRotatingFileHandler which does what you need. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: pack() and the division of vertical space
On Jun 1, 3:13 am, "Eric Brunel" <[EMAIL PROTECTED]> wrote: > On Thu, 31 May 2007 19:45:04 +0200, [EMAIL PROTECTED] > > <[EMAIL PROTECTED]> wrote: > > I am trying to figure out how to stack two widgets in a frame > > vertically so that they both expand horizontally and during vertical > > expansion, the top one sticks to the top of the frame and the bottom > > one consumes the remaining vertical space. I thought this would do it > > but it doesn't. What am I missing? > > [snip code] > > For this kind of stuff, don't use pack; use grid. It will be far easier to > get it working, to read afterwards and to maintain, even if it's slightly > more verbose. IMHO, pack should only be used to create rows or columns of > widgets, without any resizing policy, or to put an entire widget into a > container. If you do anything more complicated than that, you'll find grid > much easier to handle. > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Thanks, I basically came to the same conclusion shortly after writing my post. I got it working with grid like this: from Tkinter import * class AFrame(Frame): def __init__(self,master,**config): Frame.__init__(self,master,config) top= self.winfo_toplevel() top.columnconfigure(0,weight=1) top.rowconfigure(0,weight=1) self.grid(row=0,column=0,sticky="NEWS") self.rowconfigure(0,weight=0) self.rowconfigure(1,weight=1) self.columnconfigure(0,weight=1) self.l1= Label(self,text="abc",relief="groove") self.l1.grid(row=0,column=0,sticky="NEW") self.l2= Label(self,text="abc",relief="groove") self.l2.grid(row=1,column=0,sticky="NEWS") af= AFrame(None) mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete a file from a CGI
Thanks for your reply. This is the code that creates the file: lock_file = open(".lock","w") lock_file.write("test") lock_file.close() #Change permissions so that CGI can write lock file os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) This script was run as root. Now, the code of the CGI that should delete the file: #As you see, I can write to the file lock_file = open(".lock","w") lock_file.write("") lock_file.close() # But the following line raises a "permission denied" OSError os.remove(".lock") I've seen that the script is running as "nobody", but, the file is rwx by everybody. I've also tryed changing the owner of the file to "nobody" also, but no luck anyway. Thanks a lot. Steve Holden wrote: > Matias Surdi wrote: >> HI! >> >> I want to delete a file from a CGI, but I always get a Permission denied >> error. >> >> I've tryed this after creating the file (from a normal script): >> >> os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | >> stat.S_IRWXG)) >> os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) >> >> but the CGI still can't delete the file. >> >> I will appreciate very much your help. >> >> Thanks a lot. >> >> > How was the file created in the first place? If you don't have > permissions to delete it you may well not have permissions to reown it > or change its permissions either! > > regards > Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Warren Stringer <[EMAIL PROTECTED]> wrote: >#-- >class do(list): >def __call__(self,*args,**kwargs): >return [f(*args,**kwargs) for f in self] > > >def a(): print 'a called' >def b(): print 'b called' >c = do() >c = [a,b] >do(c[:])() >do(c)() >#-- > >I prefer that last line, because [:] is very expensive to type from a cell >phone. And not because it's completely redundant? >Now, if I could only could do this: > > do(orchestra(conductor)).play() Something along the lines of: def __getattr__(self, name): return do(getattr(x, name) for x in self) ? -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: unknown host
abcd <[EMAIL PROTECTED]> wrote: >I have a linux machine (ip = 10.10.10.8), which can ping other >machines on the same subnet...such as > [ ... ] >If I use socket.gethostbyaddr() I get back results when ip is >10.10.10.1 and 10.10.10.254 but for the other IP addresses >(10.10.10.5, .6, etc) I get back "unknown host". In fact I get >"unknown host" for the linux machine that I run the gethostbyaddr >from. > >If perform the same operation from a windows machine (ip = 10.10.10.5) >it returns data for the other IP addresses as expected. > >any ideas? Almost certainly it's a name resolution configuration problem -- check that on the Linux machine 'host 10.10.10.x' gives the same results as Python, then go and look at what you've got in /etc/hosts and /etc/resolv.conf . -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On 2007-06-01, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: >> There is code that you type which persists and code that you type from a >> command line. Two completely different idioms. A credo inside the cell phone >> game industry is that you lose half your audience with each menu keystroke. >> That's how precious keystrokes are. > > Then why do have your users typing code into a cell phone? I've decided the guy is trolling. Most of what he says is just nonsense. -- Grant Edwards grante Yow! Xerox your lunch at and file it under "sex visi.comoffenders"! -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On 2007-06-01, Warren Stringer <[EMAIL PROTECTED]> wrote: > I like your use case. Am I correct in assuming that `y = x[:]; > y()` is NOT to be found in working code? No, you may not assume that. > If that is the case, then nothing gets broken. It would be > instructive to have a use case where enabling c[:]() would > break existing code. I've already explained such a use case. You still seem to be operating under the delusion that c[:] is somehow different than c. -- Grant Edwards grante Yow! I'm imagining a surfer at van filled with soy sauce! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Cookie: Not understanding again
I have the following code, which I thought would create a cookie, if one did not exist and on the html form being sent to the server, it would be availabe for interrogation, when the script is run a second time. It seems to me there is something basic missing in that I should need to tell the server I am sending a cookie, but all the docs I have read imply it is done automatically, if one creates a 'Cookie.SimpleCookie' I know my understanding is poor of web server logic, but if anyone can help, I will be most grateful. This may be more to do with Web Server behaviour than python programming, but surely there is a way of doing this in python. Richard #!/usr/bin/env python import Cookie, os import cgitb;cgitb.enable() def getCookie(): c = Cookie.SimpleCookie() if 'HTTP_COOKIE' in os.environ: c.load(os.environ['HTTP_COOKIE']) print "Found a Cookie", c, "" c['mysession'].value += 1 print "" return c else: c['mysession'] = 45 print "No Cookie Found so setting an initial value for a Cookie", c print "" return c if __name__ == '__main__': print "Content-type: text/html\n\n" myCookie = getCookie() #Print all Environment variables for k, v in os.environ.items(): print k, "=", v, "" print "" print """ """ -- http://mail.python.org/mailman/listinfo/python-list
Re: calling Postgresql stored procedure (written in plpython)
In article <[EMAIL PROTECTED]>, Alchemist <[EMAIL PROTECTED]> wrote: > Thanks for your help. > > My stored procedure is written in pythonpl. I noticed that SELECT > queries are executed correctly (results are returned to my script) > whereas UPDATE queries are not being performed as the data is not > updated. Aha! So the problem is not really with how to call Postgres stored procs, but that you're not getting the results you expect from some calls. > I am using a database user with read/write access to the database. > > Is there a commit statement in plpython? (e.g. plpy.commit()) Did you try that? Did you check the documentation? > Why are UPDATEs failing? I'm not familiar with plpy but if it is compliant with the Python DBAPI (PEP 249) specification then, yes, it has a .commit() method and yes, you must call it after DDL statements. >From the PEP: "Note that if the database supports an auto-commit feature, this must be initially off." http://www.python.org/dev/peps/pep-0249/ In short, either turn on autocommit or start calling .commit(). -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
Re: Cookie: Not understanding again
On 1 Jun, 15:49, mosscliffe <[EMAIL PROTECTED]> wrote: > I have the following code, which I thought would create a cookie, if > one did not exist and on the html form being sent to the server, it > would be availabe for interrogation, when the script is run a second > time. > > It seems to me there is something basic missing in that I should need > to tell the server I am sending a cookie, but all the docs I have read > imply it is done automatically, if one creates a 'Cookie.SimpleCookie' > > I know my understanding is poor of web server logic, but if anyone can > help, I will be most grateful. > > This may be more to do with Web Server behaviour than python > programming, but surely there is a way of doing this in python. > > Richard > > #!/usr/bin/env python > > import Cookie, os > import cgitb;cgitb.enable() > > def getCookie(): > c = Cookie.SimpleCookie() > if 'HTTP_COOKIE' in os.environ: > c.load(os.environ['HTTP_COOKIE']) > print "Found a Cookie", c, "" > c['mysession'].value += 1 > print "" > return c > else: > c['mysession'] = 45 > print "No Cookie Found so setting an initial value for a > Cookie", c > print "" > return c > > if __name__ == '__main__': > > print "Content-type: text/html\n\n" > myCookie = getCookie() > #Print all Environment variables > for k, v in os.environ.items(): > print k, "=", v, "" > print "" > > print """ > > > > """ Forgot to add running python 2.3.4 on a hosted Apache server -- http://mail.python.org/mailman/listinfo/python-list
What is equivalent of *this = that in python?
Dear Experts, How do I reassign self to another object? For example, I want something like class foo: def Update(self,other): # make this object the same as other or make this object a copy of other self = other # This won't work. What I really want is *this = other in C++ terminology. Thanks -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb insert fails on one table
I have this table mysql> describe valid_individuals; +---+--+--+-+-+---+ | Field | Type | Null | Key | Default | Extra | +---+--+--+-+-+---+ | fname | varchar(30) | YES | | NULL| | | lname | varchar(30) | YES | | NULL| | | alias | varchar(30) | YES | | NULL| | | email | varchar(100) | YES | | NULL| | +---+--+--+-+-+---+ I call this function def insertRecords(self, tablename, columnnames, values, clear=True): cursor = self.Connection.cursor() sql = "INSERT INTO %s (%s) VALUES (%s)" % (tablename, ','.join(columnnames), ','.join(['%s' for x in columnnames])) print >>sys.stderr, sql, values[:3] cursor.executemany(sql, values) cursor.close() which prints: INSERT INTO valid_individuals (fname,lname,alias,email) VALUES (%s,%s,%s,%s) [['', '', 'z', 'aa']] this function works fine for several other tables, but on this one I get no errors and there is nothing in the table. If I run the equivalent insert on the command line, it's just fine. I'm lost here; Python 2.4.4 and latest MySQLdb for 2.4.4; anyone got a clue? --- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --- -- http://mail.python.org/mailman/listinfo/python-list
Re: What is equivalent of *this = that in python?
On Fri, 2007-06-01 at 11:30 -0400, Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do I reassign self to another object? For example, I want > something like > > class foo: > def Update(self,other): > # make this object the same as other or make this object a > copy of other > self = other # This won't work. What I really want is *this = > other in C++ terminology. There is no such thing in Python. What's the actual problem you're trying to solve? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
This discussion has gone in more circles than Earth has gone 'round the Sun, but it seems you should consider the following: 1) Sequences and functions serve fundamentally different purposes in Python. One is for containing objects, the other is for executing an action. (And yes, I'm aware that these concepts can differ in other contexts. But we're talking about Python.) 2) It seems--at least to me--a bit dubious to change an entire general purpose programming language to suit a very limited--and frankly strange--use case. 3) You'd probably be better off making a very simple and concise domain specific language. You could do whatever you want with syntax--in the case of a cell phone, I would think the less punctuation you have, the better. Your main goal seems to be speed or ease of input, so perhaps a very abbreviated syntax would be more important than being able to read the code as if it were English, as is the case in Python--the tradeoff here being more time spent reading documentation and more time spent learning syntax. You also might stand to benefit from this move if you ever decide to implement this software in something other than Python. Specifically, not requiring parentheses for function calls would probably be a nice start, and very short built-in names might also be helpful. Again, this is a tradeoff between readability and speed of input. You'd also have to spend more time implementing a parser of some sort. This could very well outweigh any benefits involved, depending on your time frame. But to reiterate the most obvious point: in your context, [:] is just notation for copying a sequence, so c[:]() would have *exactly* the same effect as c(). If it helps, you can think of [:] being just like writing .copy() for dictionaries: it makes a shallow copy, nothing more. Now think about that while remembering that sequences and functions serve different purposes in Python and thus have different semantics. There's a reason this isn't implemented in Python: it would be confusing beyond belief at first sight. And there's already perfectly good syntax for this: "for func in funcs: func()" Being able to write code quickly on a cell phone is not a goal of Python. That's your goal. On 5/30/07, Warren Stringer <[EMAIL PROTECTED]> wrote: > I want to call every object in a tupple, like so: > > #-- > def a: print 'a' > def b: print 'b' > c = (a,b) > > >>>c[:]() # i wanna > TypeError: 'tupple' object is not callable > > >>>c[0]() # expected > a > >>>c[:][0] # huh? > a > >>> [i() for i in c] # too long and ...huh? > a > b > [None,None] > #-- > > Why? Because I want to make Python calls from a cell phone. > Every keystroke is precious; even list comprehension is too much. > > Is there something obvious that I'm missing? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is equivalent of *this = that in python?
I have a distributed application using xmlrpc and I'd like for a local object to sync itself to match a remote version of the object. I realize that I can copy all the attributes from the remote object to the local object, but that seems like an ugly solution. There must be a better way... Thanks, -Emin On 6/1/07, Carsten Haese <[EMAIL PROTECTED]> wrote: On Fri, 2007-06-01 at 11:30 -0400, Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do I reassign self to another object? For example, I want > something like > > class foo: > def Update(self,other): > # make this object the same as other or make this object a > copy of other > self = other # This won't work. What I really want is *this = > other in C++ terminology. There is no such thing in Python. What's the actual problem you're trying to solve? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PIL to find separator pages
Steve Holden wrote: > Larry Bates wrote: >> I have a project that I wanted to solicit some advice >> on from this group. I have millions of pages of scanned >> documents with each page in and individual .JPG file. >> When the documents were scanned the people that did >> the scanning put a colored (hot pink) separator page >> between the individual documents. I was wondering if >> there was any way to utilize PIL to scan through the >> individual files, look at some small section on the >> page, and determine if it is a separator page by >> somehow comparing the color to the separator page >> color? I realize that this would be some sort of >> percentage match where 100% would be a perfect match >> and any number lower would indicate that it was less >> likely that it was a coverpage. >> >> Thanks in advance for any thoughts or advice. >> > I suspect the easiest way would be to select a few small patches of each > image and average the color values of the pixels, then normalize to hue > rather than RGB. > > Close enough to the hue you want (and you could include saturation and > intensity too, if you felt like it) across several areas of the page > would be a hit for a separator. > > regards > Steve Steve, I'm completely lost on how to proceed. I don't know how to average color values, normalize to hue... Any guidance you could give would be greatly appreciated. Thanks in advance, Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb insert fails on one table
On Fri, 2007-06-01 at 11:48 -0400, Sells, Fred wrote: > INSERT INTO valid_individuals (fname,lname,alias,email) VALUES (%s,%s,%s,%s) > [['', '', 'z', 'aa']] > > this function works fine for several other tables, but on this one I get no > errors and there is nothing in the table. If I run the equivalent insert on > the command line, it's just fine. This usually indicates that the table is transaction-aware (e.g. storage mechanism InnoDB versus MyISAM) and you're not committing your transaction, so the transaction gets rolled back when your connection is closed. HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: cStringIO change in 2.4 vs 2.5. Regression?
"Markus Schöpflin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | Hello, | | I just stumbled accross a difference between cStringIO in Python 2.4 | and 2.5. You can no longer feed arrays to cStringIO. [snip] | Has this change been done on purpose or is it a regression? I doubt that an intentional change would have been made for cStringIO and not StringIO. Two ways to investigate: scan the detailed listing of 2.5 changes for mention of array and cStringIO modules; check the source code checkin messages for both for the relevant time period. This might also suggest who to send an inquiry to who might not be reading here. If you do not get a satifactory resolution here, file a bug report on SF. But remember that all bug fixers are volunteers just like you, so any investigation you do and report on to make response easier will likely make it quicker also. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5.1 broken os.stat module
"Joe Salmeri" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | I hope I have provided enough information for you to reproduce the bug so | that a solution can be found. If, when discussion is concluded here, you still think there is a bug, file a report on SF. Make a concise summary in the comments section and attach a file with the output from your experiments. You may have to submit the attachment separately after first submitting the report. Keep in mind that all the 'you's who might fix this are volunteers just like you. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: How to clean a module?
thx On Jun 1, 6:50 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > ai wrote: > > Yes, you are right. > > But from this problem, could I infer that the statement "del xxx" > > doesn't release the memory which xxx used? > > It just removes the name xxx from the current scope - which will result in a > reference counter decrease. If that was the last reference, the object will > be destroyed. Most times. There are some special cases involving the usage > of __del__-methods on objects. > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PIL to find separator pages
Larry Bates wrote: > Steve Holden wrote: >> Larry Bates wrote: >>> I have a project that I wanted to solicit some advice >>> on from this group. I have millions of pages of scanned >>> documents with each page in and individual .JPG file. >>> When the documents were scanned the people that did >>> the scanning put a colored (hot pink) separator page >>> between the individual documents. I was wondering if >>> there was any way to utilize PIL to scan through the >>> individual files, look at some small section on the >>> page, and determine if it is a separator page by >>> somehow comparing the color to the separator page >>> color? I realize that this would be some sort of >>> percentage match where 100% would be a perfect match >>> and any number lower would indicate that it was less >>> likely that it was a coverpage. >>> >>> Thanks in advance for any thoughts or advice. >>> >> I suspect the easiest way would be to select a few small patches of each >> image and average the color values of the pixels, then normalize to hue >> rather than RGB. >> >> Close enough to the hue you want (and you could include saturation and >> intensity too, if you felt like it) across several areas of the page >> would be a hit for a separator. >> >> regards >> Steve > > Steve, > > I'm completely lost on how to proceed. I don't know how to average color > values, normalize to hue... Any guidance you could give would be greatly > appreciated. > > Thanks in advance, > Larry I'd like to help but I don't have any sample code to hand. Maybe someone who does could give you more of a clue. Let's hope so, anyway ... regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Sergey Dorofeev" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | How to make x*x to be evaluated once? Addendum to the answers already posted: In Python, lambda params: expression is an inline abbreviation for def (params): return expression except that there is no external binding of the otherwise illegal .func_name ''. The resulting function objects are otherwise identical. After years of discussion, Guido has decided to leave lambda alone for 3.0. It will not be neither expanded, nor removed, nor renamed. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
On 2007-06-01, Tijs <[EMAIL PROTECTED]> wrote: > Steve Howell wrote: >>> >>> from blockread import BlockReader >>> >>> b = BlockReader(f, boundary='>') >>> for block in b: >>> # whatever >> >> Yep, I like this idea. You might have a few >> variations: > > Yes, or a single one that takes a wide range of construction > possibilities, like strings, lambdas or regexes in various > keyword parameters. > > BlockReader(f, start='>') > BlockReader(f, start=re.compile('>|<'), end='---') > BlockReader(f, start=lambda x: x.startswith('>')) > > Maybe make variations for character-based readers and > line-based readers. I would prefer, "f.readlines(delim='>')" etc., a la C++ str::getline. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: unknown host
abcd wrote: > I have a linux machine (ip = 10.10.10.8), which can ping other > machines on the same subnet...such as > > 10.10.10.1 > 10.10.10.2 > 10.10.10.5 > 10.10.10.6 > 10.10.10.254 > > If I use socket.gethostbyaddr() I get back results when ip is > 10.10.10.1 and 10.10.10.254 but for the other IP addresses > (10.10.10.5, .6, etc) I get back "unknown host". In fact I get > "unknown host" for the linux machine that I run the gethostbyaddr > from. > > If perform the same operation from a windows machine (ip = 10.10.10.5) > it returns data for the other IP addresses as expected. > > any ideas? > Probably the Windows hosts are resolving the addresses to names using WINS, a NetBIOS-over-TCP compatible naming service, while the Unix hosts are trying to use the DNS. If you could arrange for your hosts to register on the DNS automatically that might solve the problem. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list