Removing hidden files and folders with python ...
Hi, I try to delete a whole directory-tree using shutil.rmtree(...) But there are always the hidden files and folders (e.g. from the svn .svn) left. How can I delete -all- files and folders (also the hidden) with python? Many Thanks Konrad -- http://mail.python.org/mailman/listinfo/python-list
Re: starting programs from python script on windows
Benedict Verheyen [EMAIL PROTECTED] (BV) wrote: BV Hi, BV i want to automate starting programs on my windows machine and i want BV to do it with windows. BV This is a sample script: BV from subprocess import Popen, PIPE BV import time BV print Starting app 1 BV time.sleep(1) BV try: BV p1 = Popen([C:\Program Files\Microsoft Office\OFFICE11\OUTLOOK.EXE], Use raw strings or escape the \'s. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Appropriate use of Property()
On Jan 30, 5:03 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: On 29 ene, 23:17, [EMAIL PROTECTED] wrote: Property() can be used to rid ourselves of the extra effort of using two different methods (getAttrib() setAttrib()) for access of an attribute without giving direct access to the attribute, thus making it more elegant. So, the outsider using my module accesses the attribute with the syntax 'Object.attrib', but since this syntax looks as if he is accessing the attribute (rather than through a descrtiptor), should we subscribe to this syntax only when the attribute is both readable and writable? i.e., if I have an attribute which I strongly believe would always be only readable, should I go with the old style 'Object.getAttrib()'? Would like to know different perspectives. The use of accessor methods is generally eschewed in python because it is felt that reading and writing to foo.bar.baz, for instance, results in cleaner (more legible) code than the idiom using foo.getBar().getBaz()/foo.setBar().setBaz(). In the culture of some other 00 languages, directly accessing an object's method is considered a cardinal sin because it breaks encapsulation. The main practical problem cited is something along this scenario: You design an object to be used by others (objects or people), and include an attribute x. Without an accesor method the others would have to look directly at the attribute (ie via y = obj.x), which is all fine and good until you decide to change the implementation of your object, specifically you figure that x is really primary, but should rather be computed from a and b, so you want to remove attribute x and add a and b. Now with an accessor method getX(), all you need do is change it to return a+b (or whatever), whereas if you had relied on direct access, obviously all the other objects using your obj.x will need to change. Therefore it is said that other (objects and programmers) should be isolated from implentation details via accessor methods. Of course in python, should that situation arise, you simply employ property() and from the point of view of those others nothing has changed. In other words property() is a way of hiding implentation details when you need to. So we can happily access object attributes directly even if only apparently and enjoy clean code without guilt. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On 30 ene, 08:09, Paul Rubin http://[EMAIL PROTECTED] wrote: Santiago Romero [EMAIL PROTECTED] writes: li = [1,2,3,4,5] filter(lambda x: x != 3, li) [1, 2, 4, 5] I haven't measured it, but this should be the fast solution in all the thread ... li.remove(3) is probably faster. But that only removes the first ocurrence of item==3. In a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will efectively remove all items with value == 3 while li.remove(3) will only remove the first ocurrence. Bye! -- http://mail.python.org/mailman/listinfo/python-list
Form to mail script
I am looking for a python web form to mail script for a public web site - could you recommend one? -- Joe Demeny -- http://mail.python.org/mailman/listinfo/python-list
help using python on Vista
I have no issues using python on XP. However on Vista I cant get the python gui (IDLE) to open! I did some research and found out that I need to unhide .idlerc but I cannot find any hidden files by that name whatsoever. Please help me. Im fairly new to python but I want to get this going. User friendly instructions would be much appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Unicode literals to latin-1
How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? I have tried variations around Fr\u00f8ya.decode('latin-1') but to no avail. .david -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Interface Recommendations
PurpleServerMonkey a écrit : (snip) Out of the major frameworks is there one that stands out as being particularly well suited for what I'm trying to do? Django and CherryPy are on the short list so I'll give them a detailed look although Pylons does sound rather interesting as well. I guess you'll have to try them out to find the one that best match your needs and personal preferences. Mostly: - CherryPy is more of a web application server than a framework per-se: it's it's own HTTP server - which might or not be a good thing -, and only deals with the controler part of the MVC triad. - Django is by now a mostly mature MVC framework, with more than a couple years of production use on quite a lot of sites and applications, good documentation and a somewhat large and active community. OTHO, it's a very opiniated (and somewhat monolithic) framework, with most parts of the stack (ORM, forms validation, template system etc) built specifically for this framework (which was probably the sensible thing to do by the time), so it's perhaps the less flexible of the three. - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, good default components choice (paste / Routes / SQLAlchemy / Mako / FormEncode) but let you swap what you want in and out, and FWIW I've seen so far a very sound architecture. FWIW, next Turbogears major version will switch from CherryPy to Pylons. OTHO, it's still far from being as mature and documented as Django. My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On Jan 30, 9:50 am, Santiago Romero [EMAIL PROTECTED] wrote: On 30 ene, 08:09, Paul Rubin http://[EMAIL PROTECTED] wrote: Santiago Romero [EMAIL PROTECTED] writes: li = [1,2,3,4,5] filter(lambda x: x != 3, li) [1, 2, 4, 5] I haven't measured it, but this should be the fast solution in all the thread ... li.remove(3) is probably faster. But that only removes the first ocurrence of item==3. In a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will efectively remove all items with value == 3 while li.remove(3) will only remove the first ocurrence. Bye! from itertools import ifilter print [x for x in ifilter(lambda x: x != 99, li)] Will this one be faster or slower than filter? -- http://mail.python.org/mailman/listinfo/python-list
Re: Appropriate use of Property()
[EMAIL PROTECTED] a écrit : Property() can be used to rid ourselves of the extra effort of using two different methods (getAttrib() setAttrib()) for access of an attribute without giving direct access to the attribute, NB : properties are for computed attributes, not to avoid giving direct acces to (an) attribute. If what you need is really a public attribute, then use a plain attribute - knowing you'll be able to switch to a property if and when the need arises. thus making it more elegant. So, the outsider using my module accesses the attribute with the syntax 'Object.attrib', but since this syntax looks as if he is accessing the attribute (rather than through a descrtiptor), should we subscribe to this syntax only when the attribute is both readable and writable? i.e., if I have an attribute which I strongly believe would always be only readable, should I go with the old style 'Object.getAttrib()'? Would like to know different perspectives. I just can second Gabriel on this: as long as it's not computation intensive, I use a read-only attribute (ie: fset and fdel raising AttributeError('attribute XXX is read-only')). -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode literals to latin-1
On Wed, 30 Jan 2008 09:57:55 +0100, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? I have tried variations around Fr\u00f8ya.decode('latin-1') but to no avail. Assuming you use Unicode-strings, the following should work: uFr\u00f8ya.encode('latin-1') That is, for some string s, s.decode('encoding') converts the non-unicode string s with encoding to a unicode string u. Whereas for some unicode string u, u.encode('encoding') converts the unicode string u into a non-unicode string with the specified encoding. You can use s.encode() on a non-unicode string, but it will first try to decode it (which might give an DecodeError if there are non-ASCII characters present) and it will then encode it. Berteun -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode literals to latin-1
[EMAIL PROTECTED] (DR) wrote: DR How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? DR I have tried variations around DR Fr\u00f8ya.decode('latin-1') DR but to no avail. You have to use encode instead of decode, and the input string must be a unicode string. print uFr\u00f8ya.encode('latin-1') Frøya -- Piet van Oostrum [EMAIL PROTECTED] URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
The problem is that we are now back to the identity problem. The class won't actually *BE* org.lib.animal.Monkey. The usage is the same; it works in all cases once you redefine __module__. Who cares what it really is? The cases I listed were just examples. My point was that I wanted it to *be* the right class, to avoid unintended consequences. If I knew what all those possible consequences were, there would not be a problem to begin with. The other follow-up to your E-Mail points out a possible problem for example. I would not have come up with that, but that does not mean the effect does not exist. And committing to a solution that seems to work, only to break massively for some particular use case in the future, is exactly why I don't want a hack for a solution. I don't know Python internals enough to state of believe with any authority wither, let's say, stomping __module__ and hacking sys.modules would be enough to *truly* do it correctly in a proper way such that it is entirely transparent. This is why I care about whether it truly changes the real identity of the class; it's not about satisfying my particular list of examples (because they *were* just examples). Whatever. ISTM you came here looking for a particular means and not a particular end. My particular preferred end is to be able to separate file hierarchy from module hierarchy without causing unforseen consequences. This was the stated goal all along. Python already has the power to meet your stated needs, but you won't use that solution because it's hacky. Apparently all you really wanted was the loosened file structure in the first place. Yes, or failing that an alternative that mitigates the problem. And it *is* hacky, in my opinion, if things break as a result of it (such as the other poster's inspect example). -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]' Key retrieval: Send an E-Mail to [EMAIL PROTECTED] E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
Santiago Romero [EMAIL PROTECTED] writes: In a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will efectively remove all items with value == 3 while li.remove(3) will only remove the first ocurrence. Hmm, interesting, I didn't realize that (shoulda checked the docs). Thanks! -- http://mail.python.org/mailman/listinfo/python-list
SV: Unicode literals to latin-1
On 30. januar 2008 10:21, Berteun Damman wrote: On Wed, 30 Jan 2008 09:57:55 +0100, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? I have tried variations around Fr\u00f8ya.decode('latin-1') but to no avail. Assuming you use Unicode-strings, the following should work: uFr\u00f8ya.encode('latin-1') I'm afraid that the string read from the database is a non-unicode string, thus me not using u... above. But it may contain unicode literals from the (Python-based) system that populated the table, and I'd like to get them back to proper unicode strings again, so that I can display them correctly to the user. That is, for some string s, s.decode('encoding') converts the non-unicode string s with encoding to a unicode string u. Whereas for some unicode string u, u.encode('encoding') converts the unicode string u into a non-unicode string with the specified encoding. You can use s.encode() on a non-unicode string, but it will first try to decode it (which might give an DecodeError if there are non-ASCII characters present) and it will then encode it. Any suggestions on how that would look, given the example above? .david -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode literals to latin-1
On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? I have tried variations around Fr\u00f8ya.decode('latin-1') but to no avail. In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') Frøya Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
SV: Unicode literals to latin-1
On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? I have tried variations around Fr\u00f8ya.decode('latin-1') but to no avail. In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') Frøya 'unicode-escape' did the trick! Thank you! .david -- http://mail.python.org/mailman/listinfo/python-list
Re: help using python on Vista
You need to go into folder options which is in the control panel and there under the view tab click Show hidden files and folders On Jan 30, 2008 9:36 AM, Safe Alattar [EMAIL PROTECTED] wrote: I have no issues using python on XP. However on Vista I cant get the python gui (IDLE) to open! I did some research and found out that I need to unhide .idlerc but I cannot find any hidden files by that name whatsoever. Please help me. Im fairly new to python but I want to get this going. User friendly instructions would be much appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Implementation of IBuyable or Interface?
Hi Gabriel, thanks for the reply. It's hard to tell just with that description. If you have to distinguish between a Product and a Service, specially if you have to do things with one that aren't done with the other (so they have a different set of methods), I'd say they should be different interfaces. Of course you may have several classes implementing the same interface Thanks, that made things clearer for me. If a service will be used by another object that expects different methods then it might as well implement a different interface but still be a buyable so that it can be used where a other buyables are expected (and maybe also using the more specific methods by upcasting it). And yes, Products and Services will probably have different methods and attributes. BTW, what do you use to define the interface? zope.inteface? another package? Yes, I'm using zope.interface. Cheers, Marcelo. On Jan 29, 2008 8:46 PM, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 29 Jan 2008 15:52:58 -0200, Marcelo de Moraes Serpa [EMAIL PROTECTED] escribi�: I've got a IBuyable interface. The app can sell both Products and Services (Both Buyables). I'm not sure if Product and Service should also be represented as interfaces (inherited from IBuyable) or if they are actually directly implementations of IBuyable. It's hard to tell just with that description. If you have to distinguish between a Product and a Service, specially if you have to do things with one that aren't done with the other (so they have a different set of methods), I'd say they should be different interfaces. Of course you may have several classes implementing the same interfaces. BTW, what do you use to define the interface? zope.inteface? another package? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
find nearest time in datetime list
Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt is there a simple way to do this? There isn't necessarily an exact match... Thanks! .john -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15180398.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
HI all
I am shravan tiwari, i want to know that how i'll run any python file(*.py) on command prompt r python GUI. i tried this python test.py but i have got error, syntax error. so can i get the solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: find nearest time in datetime list
washakie wrote: Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt is there a simple way to do this? There isn't necessarily an exact match... code import datetime dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] one_date = datetime.date (2007, 1, 7) print sorted (dates, key=lambda x: abs (x-one_date))[0] /code TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: find nearest time in datetime list
I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt is there a simple way to do this? There isn't necessarily an exact match... import datetime dates = [datetime.datetime(2007,m, 1) for m in range(1,13)] test_date = datetime.datetime(2007,4,15) closest = sorted(dates, key=lambda d: abs(test_date - d))[0] print closest -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand Python web-development
On 29 Jan, 18:11, walterbyrd [EMAIL PROTECTED] wrote: I don't know much php either, but running a php app seems straight forward enough. I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night, regardless of whether the cause is technical (what processes or components are running) or social (that hosting providers install enough of the useful PHP stuff for people not to care about wanting to install more). Python seems to always use some sort of development environment vs production environment scheme. For development, you are supposed to run a local browser and load 127.0.0.1:5000 - or something like that. Then to run the same thing in a development environment, I have to configure some files, or touch all the files, restart the web-server, or something. Why is that? You can deploy Python Web applications using anything as simple as CGI (which only requires a single change to the Web server setup), right up to the full application server configuration. For a long time I've advocated the ability to be able to do this without having to switch frameworks and rewrite your code: that's what my WebStack package [1] is all about, and I guess that given the availability of the right adaptors and framework support, WSGI should let you do this as well. Python also seems to require some sort of long running processes I guess that the python interpretor has to running all of time. Not so: deploying anything as a CGI script/program means that the application code is only run when a request is made to the application. Lots of Python software can use this approach: MoinMoin, ViewVC, Trac... (All these things have, notably, implemented their own mechanisms for abstracting away the deployment technology, since they also work with things like mod_python. Another sad example of the community not coalescing around standards, although I think they're all looking into WSGI now.) I am not really sure about what wsgi is supposed to accomplish. It's supposed to decouple the deployment technologies from the framework technologies, or at least that's what I'd use it for, and if all frameworks supported it, you'd supposedly be able to take, say, your Django application and run it on Zope 3, or your TurboGears application and run it on Twisted. Of course, you'd write your Django code differently from any Zope 3 code in your application, and the TurboGears code wouldn't look a lot like Twisted code, but that's another issue entirely. Paul [1] http://www.python.org/pypi/WebStack -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On Jan 29, 10:59 pm, Paul Hankin [EMAIL PROTECTED] wrote: If I really had to modify it in place (and the condition wasn't really x == 99), how about: bad_indices = [i for i, x in enumerate(a) if x == 99] for bad_index in reversed(bad_indices): del a[bad_index] Or one could use the trick of counting from the right (untested): n = len(a) for i, x in enumerate(a): if x == 99: del a[i-n] -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) Removing pubic hair methods [EMAIL PROTECTED] wrote: Shaving is the most common removing pubic hair method. However, it is not the only one. After you have decided you want to remove your pubic hair, you will have to examine the different methods for removing pubic hair and decide which one is the best for you. The following lines include a brief glance of the existing pubic hair removal methods: 1. Shaving - razor shaving is the most popular removing pubic hair method. One should shave his pubic hair area carefully and gently using a proper razor and shaving cream. Make sure you wash and clean your pubic hair area before and after the shave. 2. Hair removal creams - those can cause lots of pain and allergic reactions. However, they are very effective in removing pubic hair. We suggest you test in on a harmless spot like your back or the inside of your elbow to check for possible allergic reactions. If your skin gets red or itchy for a long period of time (more than 3 hours) do use it. Again, wash you pubic hair area carefully after using this removing pubic hair method. 3. Waxing - We strongly suggest avoiding using wax for removing pubic hair. Most of the women can not stand the pain and the outcome is as good as the other removing pubic hair methods. 4. Electrolysis - A permanent pubic hair removing methods using electric shocks. It can be done in a hair salon or at home after purchasing a personal device. This method is very expensive (It may cost more than a thousand dollars). It also painful in most cases but this method provides a permanent pubic hair removal. 5. Pulling - We got to know in our research quite a few women who prefer pull their pubic hair out. It takes time, Its painful but it involves a satisfaction. Now you can make the proper decision on the best removing pubic hair method for you. Good luck. http://www.dontplayplay.com/html/Bothsexes/20061002/47329.html -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) I think `pubic_hair` is an attribute instead of a method. Oh, and ``del`` is a statement and not a function. So the way you wrote it with parentheses is a bit misleading. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python noob SOS (any [former?] Perlheads out there?)
In [EMAIL PROTECTED] Reedick, Andrew [EMAIL PROTECTED] writes: Be that as it may, the activation barrier to using Python for my scripting remains too high. =20 I'd written a Perl module to facilitate the writing of scripts. It contained all my boilerplate code for parsing and validating command-line options, generating of accessor functions for these options, printing of the help message and of the full documentation, testing, etc. Bleh. Perl and Python have really good libraries. Why waste time rolling your own when you can use Python's getopt or optparse, or Perl's Getopt and Getopt::Long? No, no bleh. My module in fact uses Getopt::Long behind the scenes, but customizes the heck out of it and adds a ton of functionality I wanted not available in Getopt::Long. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter - incremental input ?
Hi, I don't want to reinvent the wheel but I cannot find it so far. Many editors have a so-called incremental search feature. As you type characters, elements of a set of strings which fit so far are displayed or at least, the first one of these is displayed. Now I want to do something similar in Tkinter - an Entry widget which displays possible 'completions' e.g. given the list of names (...,'Hardy','Helmut',..) As soon as enter the character 'H' the string 'Hardy' would be displayed in the Entry widget - but the cursor is still at position 2 (given 'H' is a position 1) Furthermore, as soon as I enter 'e', it would change the text to 'Helmut', and so on. While I can bind 'Key' to a callback, I haven't figured out how to get (and later on set) the cursor within the Entry widget. In other words I need to know at which character position the last character was entered. Currently I can only see the brute force method: keeping track of all cursor positioning means like Backspace, Del, the '-' and '-' keys and mouse clicks. Is there an easier method? Many thanks for a hint or even a pointer to an example, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Python noob SOS (any [former?] Perlheads out there?)
In [EMAIL PROTECTED] Wildemar Wildenburger [EMAIL PROTECTED] writes: kj wrote: Is there any good reading (to ease the transition) for Perl programmers trying to learn Python? www.diveintopython.org Thanks. Not for Perl programmers specifically, but it looks useful all the same. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On Jan 30, 11:57 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: n = len(a) for i, x in enumerate(a): if x == 99: del a[i-n] Oops. That can't work. Don't know what I was thinking here. I probably did had one mental refactoring too many... -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
Neil Cerutti [EMAIL PROTECTED] writes: Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: i = 0 while i len(a): if a[i] == 99: del a[i] else: i += 1 Quadratic time!! Yowch!! Back to the future: def rocket_science(xs): for x in xs: if x != 99: yield x a[:] = list(rocket_science(a)) ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: refcount
Benjamin [EMAIL PROTECTED] wrote: [ help(sys.getrefcount) says: ] [ ... ] The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). Are there any cases when it wouldn't? When the temporary reference which is the argument to getrefcount is the *only* reference, eg: sys.getrefcount (set()) 1 The return value for a weakly referenced object may also be not what you expect: s = set() sys.getrefcount(s) 2 r = weakref.ref(s) r() is s True sys.getrefcount(r()) 2 -- \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: Problem with Tkinter scrollbar callback
HI All-- We've decided that this represents a bug in the tcl/tk library, and there's no workaround. I switched to + and - buttons, which are not as nice aesthetically but work correctly on both Windows Linux. Thanks to everyone for their help. Metta, Ivan On Jan 29, 2008 11:03 AM, Ivan Van Laningham [EMAIL PROTECTED] wrote: No Joy. Waits the 1 second, then clicks the button once per second until the limit's reached. Sigh. Metta, Ivan On Jan 29, 2008 10:20 AM, Russell E Owen [EMAIL PROTECTED] wrote: Nope: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'), And even after I set it, it looks funny: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'), And when I try it with the new repeatdelay (1000), the only thing that has changed is that it waits 1000 milliseconds before exhibiting the same uncontrolled growth as before. You need to change repeatinterval, not repeatdelay. As to looking funny: that is the standard output format for configure(). I think can get a more reasonable value using cget(repeatdelay). -- Russell Metta, Ivan On Jan 25, 2008 5:49 PM, Russell E. Owen [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Ivan Van Laningham [EMAIL PROTECTED] wrote: Hi All-- That helps. Doing a get() on the scrollbar before a set(0.0,0.0) returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) and now the callback gets the correct number of arguments. However, I'm still getting the weird behaviour when clicking the arrowheads--and the heads are all I want. They act like they've been set to a keybounce timeout of about a millisecond. ... The arrow click increments the number of cells in a table row (effectively), and it shoots up from 5 to 26 columns almost instantly (that's the internal max I set). Is the scroll bar's repeatinterval set to a reasonable value? -- Russell -- http://mail.python.org/mailman/listinfo/python-list -- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours -- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours -- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours -- http://mail.python.org/mailman/listinfo/python-list
Re: HI all
On 30 ene, 09:26, [EMAIL PROTECTED] wrote: I am shravan tiwari, i want to know that how i'll run any python file(*.py) on command prompt r python GUI. i tried this python test.py but i have got error, syntax error. so can i get the solution. This is the right way to run it. If you get a syntax error, it means that test.py is not correctly written. Fix the code and try again. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On Jan 30, 2008 6:57 AM, Arnaud Delobelle [EMAIL PROTECTED] wrote: Or one could use the trick of counting from the right (untested): n = len(a) for i, x in enumerate(a): if x == 99: del a[i-n] Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: i = 0 while i len(a): if a[i] == 99: del a[i] else: i += 1 -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
If you don't want to reinvent the wheel all the time you can use this one: def inplacefilter(pred, alist): inplacefilter(pred, alist): filters the given list like filter(), but works inplace, minimizing the used memory. It returns None. pr = lambda x: x 2 l = [] inplacefilter(pr, l) l [] l = [1,2,2] inplacefilter(pr, l) l [] l = [3] inplacefilter(pr, l) l [3] l = [1,2,3,1,5,1,6,0] r = filter(pr, l) # normal filter r [3, 5, 6] inplacefilter(pr, l) r == l True slow = 0 for fast, item in enumerate(alist): if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 del alist[slow:] If you use Psyco you can replace the enumerate() with a manually incremented counter to speed up the code a bit, like this (untested): def inplacefilter(pred, alist): slow = 0 fast = 0 for item in alist: if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 fast += 1 del alist[slow:] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: find nearest time in datetime list
washakie wrote: Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt is there a simple way to do this? There isn't necessarily an exact match... Thanks! .john min(DTlist,key=lambda date : abs(dt-date)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
On 30 Jan 2008 05:20:49 -0800, Paul Rubin http://phr.cx@nospam.invalid wrote: Neil Cerutti [EMAIL PROTECTED] writes: Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: i = 0 while i len(a): if a[i] == 99: del a[i] else: i += 1 Quadratic time!! Yowch!! Back to the future: def rocket_science(xs): for x in xs: if x != 99: yield x a[:] = list(rocket_science(a)) Heh. lamelyIt's probably a fairly peppy quadratic operation though./lamely Besides, wherever will I find plutonium or a bolt of lightning? -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing two lists, ndiff performance
[EMAIL PROTECTED] wrote: Zbigniew Braniecki: Is there a way to speed it up? Any easier way? Faster method? This problem is a bit messy. Maybe it's better to sidestep the problem, and not use a list, and create an object that wraps the list, so it always keeps an updated record of what changes are done... but you have to notify it if you change the objects it contains. That would be sweet... But I rarely will have it on the plate. In most cases I will load the two l10nObjects from the files and then I'll have to compare them in the way described above. So it's something like compare-locales or compare-l10n-directories script in the easiest form. and it'll be launched in the pessimistic case on around 40 locales each of them made of ~800 l10nObjects. I'll probably leave two methods. The faster for automated scripts which just have to catch changes and report that the file needs an update, and a detailed one for presenting it to the user. I was just thinking that there maybe exists a smart, fast, powerful method that would eliminate use of ndiff to compare two lists. Thanks for help! Greetings Zbigniew Braniecki -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
On Tue, 29 Jan 2008 13:44:33 -0600, Robert Kern wrote: Carl Banks wrote: On Jan 29, 7:48 am, Peter Schuller [EMAIL PROTECTED] wrote: You can also put, in animal/__init__.py: from monkey import Monkey and now you can refer to it as org.lib.animal.Monkey, but keep the implementation of Monkey class and all related stuff into .../animal/monkey.py The problem is that we are now back to the identity problem. The class won't actually *BE* org.lib.animal.Monkey. The usage is the same; it works in all cases once you redefine __module__. Who cares what it really is? The inspect module. [snip example] I call that a bug in the inspect module. In fact, looking at the source for the findsource() function, I can see no fewer than two bugs, just in the way it handles classes: (1) it assumes that the only way to create a class is with a class statement, which is wrong; and (2) it assumes that the first occurrence of class name must be the correct definition, which is also wrong. It isn't hard to break the inspect module. Here's an example: import broken import inspect lines, lineno = inspect.findsource(broken.Parrot) lines[lineno] 'class Parrot which will be defined later.\n' lines, lineno = inspect.findsource(broken.Wensleydale) lines[lineno] 'class Wensleydale: # THIS IS GONE\n' Here's the source of broken.py: $ cat broken.py Here is a doc string, where I happen to discuss the class Parrot which will be defined later. class Parrot: pass class Wensleydale: # THIS IS GONE pass del Wensleydale class Wensleydale(object): # but this exists pass It isn't often that I would come right out and say that part of the Python standard library is buggy, but this is one of those cases. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing two lists, ndiff performance
On 29 ene, 22:47, Zbigniew Braniecki [EMAIL PROTECTED] wrote: The new one is of course much better and cleaner (the old one is bloated), but I'm wondering if there is a faster way to compare two lists and find out what was added, what was removed, what was changed. I can simply iterate through two lists because I need to keep an order (so it's important that the removed line is after the 3 line which was not changed etc.) ndiff plays well here, but it seems to be extremely slow (1000 iterations of diffToObject takes 10 sec, 7sec of this is in ndiff). ndiff does a quadratic process: first determines matching lines using a SequenceMatcher, then looks for near-matching lines and for each pair, compares them using another SequenceMatcher. You don't appear to be interested in what changed inside a line, just that it changed, so a simple SequenceMatcher would be enough. Output from SequenceMatcher is quite different than ndiff, but you'd have to reimplement the _compareLists method only. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
On Tue, 29 Jan 2008 06:48:59 -0600, Peter Schuller wrote: You can also put, in animal/__init__.py: from monkey import Monkey and now you can refer to it as org.lib.animal.Monkey, but keep the implementation of Monkey class and all related stuff into .../animal/monkey.py The problem is that we are now back to the identity problem. The class won't actually *BE* org.lib.animal.Monkey. It what sense will it not be? Why do you care so much about where the source code for Monkey is defined? If you actually want to read the source, you might need to follow the chain from animal, see that Monkey is imported from monkey, and go look at that. But the rest of the time, why would you care? There is a very good reason to care *in practice*: if there is code out there that assumes that the source code from Monkey is in the file it was found in. In practice, you might be stuck needing to work around that. But that's not a good reason to care *in principle*. In principle, the actual location of the source code should be an implementation detail of which we care nothing. It's possible that the source for Monkey doesn't exist *anywhere*. It is important to deal with buggy tools. But the correct way to do so is to fix the bugs, not to throw away perfectly good abstractions. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
Sion Arrowsmith wrote: Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) I think `pubic_hair` is an attribute instead of a method. Oh, and ``del`` is a statement and not a function. So the way you wrote it with parentheses is a bit misleading. And who's going to want to call genital().remove() anyway? I will use genital().extend(), thats for shure ^^ -- http://mail.python.org/mailman/listinfo/python-list
Re: optional static typing for Python
Kay Schluehr wrote: On Jan 30, 12:38 am, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Python has a JIT right no You mean in the Java-sense (outputting native machine code)? /W Sure. http://psyco.sourceforge.net/ Oh, switcheroo! :) /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
Anyone else noticed that the OP has not actually replied to any of the suggestions... -- http://mail.python.org/mailman/listinfo/python-list
Re: find nearest time in datetime list
Boris Borcic wrote: min(DTlist,key=lambda date : abs(dt-date)) In Python2.4: Traceback (most recent call last): File stdin, line 1, in ? TypeError: min() takes no keyword arguments Looks like min() only started taking keywords (key) from Python2.5 forward. But the min() solution is good if you're running 2.5 -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
On 30 ene, 12:00, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I call that a bug in the inspect module. In fact, looking at the source for the findsource() function, I can see no fewer than two bugs, just in the way it handles classes: (1) it assumes that the only way to create a class is with a class statement, which is wrong; and (2) it assumes that the first occurrence of class name must be the correct definition, which is also wrong. Yes, it's broken. But I'm afraid that's the only available thing to do. Python stores filename and line number information in code objects (only). If you have a reference to any code object (a method, a function, a traceback...) inspect can use it to retrieve that information. Once a class is defined, there is no code object attached to it. (The class statement is executed when the module is loaded and initialized, but that code object is discarded afterwards because it's not required anymore). If you *know* that a certain method is defined in a class, you can use it to find the real module. But in general, there is nothing to start with. I'm eagerly waiting for someone to come and say I'm wrong... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
Gerardo Herzig wrote: I will use genital().extend(), thats for shure ^^ Well, you never go wrong with apply(genital(), females), do you? /W -- http://mail.python.org/mailman/listinfo/python-list
Re: find nearest time in datetime list
Thanks all! This is terrific, and a quick response... I have to go with the 2.4 version, but thanks to everyone... Tim Golden-4 wrote: washakie wrote: Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt is there a simple way to do this? There isn't necessarily an exact match... code import datetime dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] one_date = datetime.date (2007, 1, 7) print sorted (dates, key=lambda x: abs (x-one_date))[0] /code TJG -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15183205.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removal of element from list while traversing causes the next element to be skipped
Paul Rubin http://[EMAIL PROTECTED] writes: Quadratic time!! Yowch!! Back to the future: def rocket_science(xs): for x in xs: if x != 99: yield x a[:] = list(rocket_science(a)) I call useless use of list! a[:] = rocket_science(a) :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing hidden files and folders with python ...
On 30 ene, 06:21, Konrad Mühler [EMAIL PROTECTED] wrote: I try to delete a whole directory-tree using shutil.rmtree(...) But there are always the hidden files and folders (e.g. from the svn .svn) left. How can I delete -all- files and folders (also the hidden) with python? I assume you use Windows. You have to reset the readonly, system and hidden directory attributes. os.chmod can reset the first one, but for the others you have to use ctypes or the pywin32 package to call the SetFileAttributes function. Of course there is system too: os.system(attrib -r -h -s filename) You could use rmtree once, apply the above on the remaining files and directories -if any- and try rmtree again. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing two lists, ndiff performance
Zbigniew Braniecki: Is there a way to speed it up? Any easier way? Faster method? This problem is a bit messy. Maybe it's better to sidestep the problem, and not use a list, and create an object that wraps the list, so it always keeps an updated record of what changes are done... but you have to notify it if you change the objects it contains. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode literals to latin-1
On 30 ene, 07:54, [EMAIL PROTECTED] wrote: On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' 'unicode-escape' did the trick! Thank you! A unicode-escaped string looks very strange in a database... I'd revise the way things are stored and retrieved. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) I think `pubic_hair` is an attribute instead of a method. Oh, and ``del`` is a statement and not a function. So the way you wrote it with parentheses is a bit misleading. And who's going to want to call genital().remove() anyway? -- \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
Anyone Know Unicode? Help!
Hi; Second post on this. Googling shows many others with same problem, but no answers! Help! New to unicode. Got this error: Traceback (most recent call last): File stdin, line 1, in module File stdin, line 29, in tagWords File /usr/local/lib/python2.5/codecs.py, line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128) I think the problem comes from this code snippet: for line in sentences: print line tup = re.split(' ', line) for word in tup: for key, value in dictionary.items(): if key == word: word = word + '::' + value newLine.append(word) sentences.close() TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
SV: Unicode literals to latin-1
On 30. januar 2008 14:31, Gabriel Genellina wrote: On 30 ene, 07:54, [EMAIL PROTECTED] wrote: On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: How can I convert a string read from a database containing unicode literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya? In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' 'unicode-escape' did the trick! Thank you! A unicode-escaped string looks very strange in a database... I'd revise the way things are stored and retrieved. I agree. I'm currently using the trick above to fix it. .david -- http://mail.python.org/mailman/listinfo/python-list
Sine Wave Curve Fit Question
Python Folks I'm a newbie to Python and am looking for a library / function that can help me fit a 1D data vector to a sine wave. I know the frequency of the wave, so its really only phase and amplitude information I need. I can't find anything in the most widely known libraries (they seem to be strong on polynomial fitting, but not, apparently, on trig functions) and I wondered if any one here had recommendations? Something that implemented IEEE 1057 , or similar, would be perfect. TIA Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - incremental input ?
On Wed, 30 Jan 2008 13:32:00 +0100, Helmut Jarausch [EMAIL PROTECTED] wrote: [snip] While I can bind 'Key' to a callback, I haven't figured out how to get (and later on set) the cursor within the Entry widget. In other words I need to know at which character position the last character was entered. You can get the position of the insertion point with entry.index('insert'), and set it via entry.icursor(index). If you want to do this as the user types, take care to bind to KeyRelease; this way, the character corresponding to the key has already been entered in the entry. BTW, you may also want to automatically select the part that the user hasn't actually typed. This can be done with entry.selection_clear(), then entry.selection_range(start_position, end_position). 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: Removing Pubic Hair Methods
Wildemar Wildenburger wrote: Gerardo Herzig wrote: I will use genital().extend(), thats for shure ^^ Well, you never go wrong with apply(genital(), females), do you? /W That's enough genitalia [ed] -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble loading dll via ctypes
subopt inTheVicinityOf geemail.com wrote: I'm trying to load a dll via ctypes by doing this: cdll.LoadLibrary('/path/to/mylib.so') But i'm getting this: /path/to/mylib.so: cannot open shared object file: No such file or directory What am i doing wrong? The dll in question is in a directory mounted via NSF, but no part of the path/filename is a symlink. When i try code from the docs: cdll.LoadLibrary('libc.so.6') ,then all is fine. I've also tried to set my LD_LIBRARY_PATH before starting Python, checking it via os.environ, then doing the cdll.LoadLibrary(...), but that fails with the same complaint. What am i doing wrong? I vaguely remember you need execute permissions for a dynamic library to load. Permissions on an NFS mounted directory are different, especial for user 'root'. Check if can execute some executable in that NFS path. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Python noob SOS (any [former?] Perlheads out there?)
On Jan 29, 5:39 pm, kj [EMAIL PROTECTED] wrote: [...] It's not the Python syntax that I'm having problems with, but rather with larger scale issues such as the structuring of packages, techniques for code reuse, test suites, the structure of distributions,... Python and Perl seem to come from different galaxies altogether... [...] I'd written a Perl module to facilitate the writing of scripts. It contained all my boilerplate code for parsing and validating command-line options, generating of accessor functions for these options, printing of the help message and of the full documentation, testing, etc. Of course, for Python now I don't have any of this, so I must write it all from scratch, and the thing is *I don't even know where to begin*! And meanwhile works needs to get done, projects finished, etc. So naturally I revert to Perl, yadda-yadda-yadda, and the Python project gets pushed back another week... In a way it's the usual story with learning a new language, but I've taught myself new languages before. (After all, there was a time when I didn't know Perl.) It's harder this time, somehow... The journey of a thousand miles etc. For command line options I get a long way with this: [code python] def _getargs(): allargs = sys.argv[1:] args = [] kwargs = {} key = None while allargs: arg = allargs.pop(0) if arg.startswith('--'): key, arg = arg.split('=', 1) key = key[2:] elif arg.startswith('-'): key = arg[1:] if not allargs or allargs[0].startswith('-'): allargs.insert(0, 'yes') continue if key is None: args.append(arg) else: kwargs[key] = arg key = None return args, kwargs ARGS, KWARGS = _getargs() [/code] though obviously there's no validation. For testing see doctest module. For file and directory manipulation see os and shutil modules. The following is an abuse of docstrings, but shows some OO techniques: [code python] import inspect linesep = '\n' class TemplateBase(object): factory = None template = None verb = 'substitute' @classmethod def render(cls, **kws): if cls.template is None: cls.template = cls.factory(inspect.getdoc(cls)) return getattr(cls.template, cls.verb)(**kws) @classmethod def write(cls, fd, **kws): fd.write(linesep) fd.write(cls.render(**kws)) fd.write(linesep) @classmethod def writeiter(cls, fd, seq): for context in seq: cls.write(fd, **context) class StringTemplate(TemplateBase): import string factory = string.Template class SafeStringTemplate(StringTemplate): verb = 'safe_substitute' try: class TempitaTemplate(TemplateBase): import tempita factory = tempita.Template except ImportError: pass try: class MakoTemplate(TemplateBase): from mako.template import Template factory = Template verb = 'render' except ImportError: pass class StartJythonUnix(SafeStringTemplate): r #!/usr/bin/ksh java \ -Dpython.home=$jythonhome \ -classpath $jythonhome/jython.jar:$CLASSPATH \ org.python.util.jython.class class DefineLocalQueue(StringTemplate): DEFINE QLOCAL($qname) + DEFPSIST(YES) + DESCR('$descr') + STGCLASS('$stgclass') + MAXDEPTH ($maxdepth) class DeleteLocalQueue(TempitaTemplate): DELETE QLOCAL({{qname}}) import sys StartJythonUnix.write(sys.stdout, jythonhome=/home/dev/jython/ jython-2.1) from cStringIO import StringIO s = StringIO() DefineLocalQueue.write(s, name=AAA, descr=AAA, stgclass=AAA, maxdepth=100) DeleteLocalQueue.write(s, name=BBB, descr=BBB, stgclass=BBB, maxdepth=100) print s.getvalue() [/code] HTH Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
On Jan 30, 4:31 am, Peter Schuller [EMAIL PROTECTED] wrote: I don't know Python internals enough to state of believe with any authority wither, let's say, stomping __module__ and hacking sys.modules would be enough to *truly* do it correctly in a proper way such that it is entirely transparent. This is why I care about whether it truly changes the real identity of the class; it's not about satisfying my particular list of examples (because they *were* just examples). Well, all I will say is that many people on this list, myself included, do know Python internals, and we use the method we've been suggesting here, without problems. I think you're slipping to a level of paranoia that's more harmful that helpful now. The ironic thing is, breaking the one-to-one module-to-file relationship is more likely to have unintended consequences, by a very large margin. Python has always been one-to-one module-to-file (excepting modules built into the interpretter), and many codes and tools have come to depend on it. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb and column names
Hello all, I am using MySQLdb 1.2.2 and have a question about the construction of the dictionary keys of a result set. Here is an example query, from which you may intuit some of the structure of the tables: SELECT shots.*, users.*, sequences.*, jobs.* FROM shots LEFT JOIN users ON users.id=shots.user_id INNER JOIN sequences ON sequences.id=shots.sequence_id INNER JOIN jobs AS j ON j.id=sequences.job_id WHERE shots.id=%s 1. The 'users' table has a column named 'id', as do all the other tables. 2. I define my cursor as a 'DictCursor' so that my results are dictionaries 3. The 'shots' id has the key name of 'id', while all the -other- 'id's have key names of the form: TABLE.id I would prefer to have the key names consistent, so that event the shots fields have key names of the form TABLE.id Is this possible? Thanks in advance! -- Wellington -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb and column names
change: I would prefer to have the key names consistent, so that event the to: I would prefer to have the key names consistent, so that *even* the -- http://mail.python.org/mailman/listinfo/python-list
Re: Python plugins for netbeans 6 IDE?
Did you managed to work out NetBeans and Python? Ken McDonald wrote: Do any such exist? And do you find them worthwhile? I couldn't see any browsing the netbeans pages, but that doesn't mean they're not out there... Thanks, Ken -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/Python-plugins-for-netbeans-6-IDE--tp12843005p15186891.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
event handling
Hi , I am working on a stellar spectral analysis pipeline in Python. My OS is Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard event handling. My code communicates with the user through an xterm window and shows graphs in a Gnuplot window. At a certain point i start an infinite loop in order to select multiple spectral regions by mouse-clicks over the Gnuplot graph. I would like to terminate this loop by a single keystroke, but i can not get it done. I use 'thread' to run this process in the background waiting for a keystroke. I don't want to use tkinter, widgets or pygame because those require a popup surface to work in and i already have the gnuplot window. I tried a C like getch() function, but that pauses the code waiting for key press instead of scanning the event queue. Is there any other means for general event handling in Python? Any help would be greatly appreciated. Sincerely, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Sine Wave Curve Fit Question
Iain Mackay napisal(a): Python Folks I'm a newbie to Python and am looking for a library / function that can help me fit a 1D data vector to a sine wave. I know the frequency of the wave, so its really only phase and amplitude information I need. I can't find anything in the most widely known libraries (they seem to be strong on polynomial fitting, but not, apparently, on trig functions) and I wondered if any one here had recommendations? Something that implemented IEEE 1057 , or similar, would be perfect. TIA Iain I'm not aware of any specialized library, but how about using numpy and running FFT on your data? If you already know the frequency, you can easily extract phase and scaled amplitude from the result. Regards, Marek -- http://mail.python.org/mailman/listinfo/python-list
Updating documents in PyLucene
Hi all, The way that Lucene (and by extension, PyLucene) seems to work is that updates to documents are implemented by the user as a document addition (of the new version) and subsequent deletion (of the old version). My problem is that I'd like to update a number of documents which have their Store flag set to NO - they're indexed, but not stored. I don't have the original text content of these documents available anywhere else - is there any way for me to get this un-stored indexed data from the old document into the new? Also posting to comp.lang.java.programmer. Thanks, James -- http://mail.python.org/mailman/listinfo/python-list
Re: Python UML Metamodel
En Tue, 29 Jan 2008 21:25:26 -0200, sccs cscs [EMAIL PROTECTED] escribió: I find an OPEN SOURCE tool (http://bouml.free.fr/) that Recently generates Python code from UML model. Does it keep the model synchronized when you modify the Python code? I like to model the Python language metamodel himself, with it, e.g the model of the language: I need that to better understand the language constraint of the language. for example, i like to model that : -a class class may inherit from 0..* class 1..* classes if you model new-style classes only. Classic classes disappear completely in Python 3.0 -a class class is create from a class that is its metaclass -a class class has 0..n attributes and 0..n method Just attributes. Methods are created on-the-fly when the corresponding function attribute is retrieved from the instance. And remember that instances are not restricted to what their class define. You can add or remove any attribute (even methods!) to any instance of a user-defined class at any time. (This doesn't apply to most builtin types, but *does* apply if you inherit from it) -a class module has 0..n class class Not true. A module instance can contain any number of attributes of any type; classes are just an example. Does anyone know a document that describes it already, because I think it is complicated to find this information in the documentation of Python. See section 2 Data Model and section 3 Execution Model in the Python Language Reference http://docs.python.org/ref/ For example, can i say that: -a class class has 0..n properties ? It seems that the Python metamodel is not perfect, because I do not find attribute which give me the property list with a code like: myPropertyList = myclass.properties dir(obj) retrieves most of the obj attributes. Some are hard to enumerate (if they are simulated in code, using __getattr__ by example), and some internal fields are not shown in dir() yet (the __dir__ method in 2.6 would help in this case). - a class method can contains nested method, but what is the way to get a list of internal methods, without use ? Can i just write: myNestedMethodList = method.nestedMethodList Are you talking about nested functions? You can't enumerate them from outside the container function: Python is a dynamic language, those inner functions are created when the def statement is *executed*. If you have an if statement around the def, the function may not even exist. I think a metamodel Python would be welcome to complement the BNF (http://docs.python.org/ref/grammar.txt), so as to know fully understand the relationships between the various elements of language. Maybe, but I think it's a lot simpler than you imagine. For the builtin types, see section 3.2 on the reference above; more info in the Library Reference. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: event handling
On Jan 30, 11:16 am, Peter Nemeth [EMAIL PROTECTED] wrote: Hi , I am working on a stellar spectral analysis pipeline in Python. My OS is Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard event handling. My code communicates with the user through an xterm window and shows graphs in a Gnuplot window. At a certain point i start an infinite loop in order to select multiple spectral regions by mouse-clicks over the Gnuplot graph. I would like to terminate this loop by a single keystroke, but i can not get it done. I use 'thread' to run this process in the background waiting for a keystroke. I don't want to use tkinter, widgets or pygame because those require a popup surface to work in and i already have the gnuplot window. I tried a C like getch() function, but that pauses the code waiting for key press instead of scanning the event queue. Is there any other means for general event handling in Python? Any help would be greatly appreciated. Sincerely, Peter I would use wxPython, but since you seem against that, here's what I found using Google-fu: http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm It sounds very similar to what you are doing and it shows how to do it in both Windows and Linux. Threads are annoying buggers. You'll probably want to have one thread catching key-presses and storing them in a file or file-like object and have your other thread read from it periodically. I'm not sure that the link above mentions that. Hope that helps! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Q: paramiko/SSH/ how to get a remote host_key
I tried to get what host_key has been aquired after AutoPolicy is set. I added the following code just before client.close() in rosty's final code: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' I still got 'Unable to open host keys file'. Can you tell me how to get the remote host_key under this situation? Thanks! Charles 1/30/2008 by Guilherme Polo Jan 21, 2008; 09:08am : 2008/1/21, DHR [EMAIL PROTECTED]: Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. by rosty Jan 21, 2008; 08:43am : Thank you! Now it works and the code looks like this: import paramiko import base64 from paramiko import AutoAddPolicy, SSHClient client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('hostIP', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sine Wave Curve Fit Question
Iain Mackay wrote: Python Folks I'm a newbie to Python and am looking for a library / function that can help me fit a 1D data vector to a sine wave. I know the frequency of the wave, so its really only phase and amplitude information I need. I can't find anything in the most widely known libraries (they seem to be strong on polynomial fitting, but not, apparently, on trig functions) and I wondered if any one here had recommendations? Something that implemented IEEE 1057 , or similar, would be perfect. Let's do a bit math first. Your model is A*sin(omega*t+alpha) where A and alpha are sought. Let T=(t_1,...,t_N)' and Y=(y_1,..,y_N)' your measurements (t_i,y_i) ( ' denotes transposition ) First, A*sin(omega*t+alpha) = A*cos(alpha)*sin(omega*t) + A*sin(alpha)*cos(omega*t) = B*sin(omega*t) + D*cos(omega*t) by setting B=A*cos(alpha) and D=A*sin(alpha) Once, you have B and D, tan(alpha)= D/B A=sqrt(B^2+D^2) Then in vector notation S=sin(omega*T) C=cos(omega*T) you get the 2x2 system for B and D : (S'*S) * B + (S'*C) * D= S'*Y (S'*C) * B + (C'*C) * D= C'*Y where S'*C is the scalar product of the vectors S and C and similarly. Now, for Python, to handle vectors and scalar products efficiently, have a look at numpy. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Q: paramiko/SSH/ how to get a remote host_key
2008/1/30, Charles_hans [EMAIL PROTECTED]: I tried to get what host_key has been aquired after AutoPolicy is set. I added the following code just before client.close() in rosty's final code: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' I still got 'Unable to open host keys file'. Can you tell me how to get the remote host_key under this situation? Thanks! Charles 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if ~/ssh/known_hosts exists then (since you are trying to access that file). Cheers, by Guilherme Polo Jan 21, 2008; 09:08am : 2008/1/21, DHR [EMAIL PROTECTED]: Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. by rosty Jan 21, 2008; 08:43am : Thank you! Now it works and the code looks like this: import paramiko import base64 from paramiko import AutoAddPolicy, SSHClient client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('hostIP', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Friendly Blog?
Hai Vu wrote: Why don't you try to use Code Colorizer: http://www.chamisplace.com/colorizer/cc.asp Looks like it lacks support for one important language, though... Stefan -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
17146031598 -- http://mail.python.org/mailman/listinfo/python-list
Events in Python
Hi, I have a stackless python app, using twisted in parts (.internet and .adbapi). I need a little help getting pythonic after years of c++ hell. I'd like to use a system of events and observers, like c++ boost.signal. I'd like to be able to subscribe multiple callbacks to a single function and cal them all using something like: event.invoke(some data to send with invocation) I'm thinking twisted callbacks do this: def observe(self, f); self.event.addcallback(f) Are there other ways? Thanks Si -- Linux user #458601 - http://counter.li.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Interface Recommendations
On Jan 30, 8:08 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: PurpleServerMonkey a écrit : (snip) Out of the major frameworks is there one that stands out as being particularly well suited for what I'm trying to do? Django and CherryPy are on the short list so I'll give them a detailed look although Pylons does sound rather interesting as well. I guess you'll have to try them out to find the one that best match your needs and personal preferences. Mostly: - CherryPy is more of a web application server than a framework per-se: it's it's own HTTP server - which might or not be a good thing -, and only deals with the controler part of the MVC triad. - Django is by now a mostly mature MVC framework, with more than a couple years of production use on quite a lot of sites and applications, good documentation and a somewhat large and active community. OTHO, it's a very opiniated (and somewhat monolithic) framework, with most parts of the stack (ORM, forms validation, template system etc) built specifically for this framework (which was probably the sensible thing to do by the time), so it's perhaps the less flexible of the three. - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, good default components choice (paste / Routes / SQLAlchemy / Mako / FormEncode) but let you swap what you want in and out, and FWIW I've seen so far a very sound architecture. FWIW, next Turbogears major version will switch from CherryPy to Pylons. OTHO, it's still far from being as mature and documented as Django. My 2 cents... Thanks Bruno, that's just the sort of info I was after. After reading more on the subject recently I'll be installing and testing Pylons and Turbogears first, think it will be a good fit for the project and if not there's no shortage of other offerings. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand Python web-development
Thanks for all that posts. This thread has been helpful. I have seen a lot of posts about the importance of decoupling the deployment technologies from the framework technologies. This is how I have done that in PHP. I develop on my home box. When I get something working the way I want, I ftp those files to the remote server. To me, that seems to make more sense that trying to run two different web servers on the same system. My PHP system involves no monkeying with special config files, or running special servers to couple the different environments, or setting special ports, or paths. For PHP development, I don't even need ssh access. I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night I think you may have something there. For $10 a year I can get an account at dollar-hosting.net, copy some php files there, and that's all there to it. I have been beating my brains out trying to get anything working with a python framework, and I have not been able to do it. I even bought VPS hosting just for the sake of python development. But, I still can not seem to make the quantum leap of getting something that works locally, to work remotely. BTW: with the VPS hosting, I had to install and configure my own web-hosting and PHP, including setting up lighttpd with fastcgi and php modules - and I still found that much easier than getting anything to work with python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Q: paramiko/SSH/ how to get a remote host_key
Thank you, Guilherme. I was running demo_sftp.py included in paramiko download. It seems that '.ssh/known_hosts' should be the path of a key file on my working directory on local PC. (Right?) I replaced this with 'test_rsa.key' in C:\paramiko-1.7.2\demos and this did not generate error. But the returned host_keys is empty. I traced the code to 'hostkeys.py' and found that the line e = HostKeyEntry.from_line(line) always retuned None. This means that my remote host name should have been in this key file. (Right?) I am very new to paramiko. How to create such a key file (with my remote host name)? Should I also load this key file into the remote server? Please advise. Thanks! Charles 1/30 2008/1/30, Charles_hans [EMAIL PROTECTED]: I tried to get what host_key has been aquired after AutoPolicy is set. I added the following code just before client.close() in rosty's final code: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' I still got 'Unable to open host keys file'. Can you tell me how to get the remote host_key under this situation? Thanks! Charles 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if ~/ssh/known_hosts exists then (since you are trying to access that file). Cheers, by rosty Jan 21, 2008; 08:43am : Thank you! Now it works and the code looks like this: import paramiko import base64 from paramiko import AutoAddPolicy, SSHClient client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('hostIP', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15192764.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Pubic Hair Methods
On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: Gerardo Herzig wrote: I will use genital().extend(), thats for shure ^^ Well, you never go wrong with apply(genital(), females), do you? `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Events in Python
You may need Louie (http://louie.berlios.de) Django (http://djangoproject.com) does the same in django.dispatch - and Django version works about 33% faster. Note that all those signals/events are very slow in Python. --Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Events in Python
Compared to what, did you measure something? As example, instantiation of Model classes in Django (Model.__init__) sends two signals (pre_init and post_init) - they are rarely used in practice - but they make instantiation about two times slower. Yes, I measured that. The creator of Louie (Patrick K. O'Brien) himself seems to use them only as an option that can be enabled/disabled in his projects (e.g. Schevo) - because they are slow. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fw: Undeliverable Message
On Jan 25, 5:05 am, [EMAIL PROTECTED] wrote: Hallo pyPeople, I wrote a little snippet of code that takes a list representing some 'digits', and according to a list of symbols, increments the digits through the symbol list. so for example, digits=[a,a,a] symbols=[a,b,c] increment(digits,symbols) repeatedly would return digits as aab aac aba abb abc aca etc.. Heres the code def increment(digits,symbols): overflow=True digitpos=-1 while overflow and -digitpos=len(digits): digitsymbolindex=symbols.index(digits[digitpos]) if digitsymbolindex==len(symbols)-1: overflow=True digits[digitpos]=symbols[0] digitpos=digitpos-1 else: digits[digitpos]=symbols[digitsymbolindex+1] overflow=False return digits Now, this works. All good. It's nice and simple. I'm just wondering how anyone else might approach it? I (not an expert at all) have only minor comments and one question: comments: why keep setting overflow to True, if you do not touch it will not change. digitpos -= 1 is easier to read in my mind question: Why first extract the indices and then compare (in your if statement), and why do you not just compare the symbols? Best, Bart -- http://mail.python.org/mailman/listinfo/python-list
Re: Events in Python
Ivan Illarionov wrote: Note that all those signals/events are very slow in Python. Compared to what, did you measure something? Regards, Björn -- BOFH excuse #38: secretary plugged hairdryer into UPS -- http://mail.python.org/mailman/listinfo/python-list
dynamically set up ssh -r paramiko?
Hello, I'm trying to write a script which will allow me to initiate (spawn?) an SSH reverse tunnel from an internal box (inside a firewall) to an external box, while logged into the external box. I posted to another list and was pointed in the direction of paramiko. I've read the tutorials, but cannot seem to figure out exactly how I can do this... I'm hoping someone can look at what I'm trying to do below and provide an example... #!/usr/bin/python import os, time, subprocess REMOTE_HOME='/my/remote/mount' #mounted drive to REMOTE_HOME from LOCAL_MACHINE cmd = 'while true; do ssh -R 8022:localhost:22 [EMAIL PROTECTED] ; sleep 60; done' while 1: while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'): proc= subprocess.call(cmd,shell='True') if proc: os.kill(proc.pid) if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'): break -- Note, I know the reverse tunnel script works on it's own run from the shell, but I don't want to leave it open always... furthermore it seems to be a rather 'brute force' method. It seems paramiko might provide a more elegant solution! Does anyone have any ideas on how to make this work? Thanks, john -- View this message in context: http://www.nabble.com/dynamically-set-up-ssh--r---paramiko--tp15193757p15193757.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Dictionary Keys question
I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
FireNWater wrote: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! Currently the order of dict keys depend on the hash of the object. Try hash(1) and hash('a'). -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
Well, all I will say is that many people on this list, myself included, do know Python internals, and we use the method we've been suggesting here, without problems. Ok. That is useful to know (that it is being done in practice without problems). Thanks! -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]' Key retrieval: Send an E-Mail to [EMAIL PROTECTED] E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
En Wed, 30 Jan 2008 20:47:36 -0200, FireNWater [EMAIL PROTECTED] escribió: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 Dictionaries use the hash value of the keys to distribute them in buckets. Compare these: for key in list1: print key, hash(key) for key in list2: print key, hash(key) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Jan 30, 4:47 pm, FireNWater [EMAIL PROTECTED] wrote: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 The underlying order is a result, in part, of the key's hash codes*. Integers are hash coded by their integer values, therefore, they appear in numeric order. Strings, however, use an algorithm that ensures as unique hash codes as possible. Notice the difference: map(hash, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 1, 2, 3, 4, 5, 6, 7, 8]) [-468864544, -340864157, -212863774, -84863387, 43136996, 171137383, 299137766, 427138153, 1, 2, 3, 4, 5, 6, 7, 8] * emphasis on the in part. Other factors include the amount of memory space available, order added, the current size of the underlying hash table, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater [EMAIL PROTECTED] wrote: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! I don't know the exact way Python's hash function works, but I can take a guess. I'm sorry if I explain something you already know. A hash is for quickly looking up data. Yet, you don't want to waste too much memory. So there is a limit number of spaces allocated, in which to store objects. This number of spaces can be thought of as a list. Then, if you put something into the dict, Python computes the 'hash' of this object, which basically forms the index in the list where to store it. So every object should be mapped onto some index within the list. (If you retrieve it, the hash is computed again, and the value on that index is looked up, like list indexing, these are fast operations.) Say, if you have 100 spaces, and someone puts in integer in the list, the hashfunction used might be % 100. So the first 100 integers would always be placed at consecutive places. For strings however, a more complicated hash-function would be used, which takes into account more characters, so strings don't end up in order. For integers, if you put in integers that are spread very widely apart, they won't end up in order either (see the mod 100 example, 104 will come before 10). If you replace the list2 in your example by: list2 = [1 * x for x in range(1,9)] You will see that this one doesn't end up in order either. So, there's no exception for integers when it comes to the order, yet the particular properties of the hash function will cause sequential integers to end up in order under some circumstances. Berteun PS: What happens if two values map onto the same space is of course an obvious question, and the trick is choosing your hashfunction so this occurs not very often on average. If it happens there are several strategies. Wikipedia probably has an explanation of how hash-functions can work in such a case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
It what sense will it not be? Why do you care so much about where the source code for Monkey is defined? If you actually want to read the source, you might need to follow the chain from animal, see that Monkey is imported from monkey, and go look at that. But the rest of the time, why would you care? There is a very good reason to care *in practice*: if there is code out there that assumes that the source code from Monkey is in the file it was found in. In practice, you might be stuck needing to work around that. But that's not a good reason to care *in principle*. In principle, the actual location of the source code should be an implementation detail of which we care nothing. It's possible that the source for Monkey doesn't Exactly. I *DON'T* want anything to depend on the physical location on disk. That was exactly what I was after from the beginning; a total separation of location on disk from the location in the module hiearachy. As you say, the location of the source should be an implementation detail. That is exactly what I am after. I'll have a closer look at the suggested practice of modifying __module__. For this particular use case we probably won't end up doing that, but it may come to be useful in the future. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]' Key retrieval: Send an E-Mail to [EMAIL PROTECTED] E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand Python web-development
On 30 Jan, 21:27, walterbyrd [EMAIL PROTECTED] wrote: Thanks for all that posts. This thread has been helpful. I have seen a lot of posts about the importance of decoupling the deployment technologies from the framework technologies. This is how I have done that in PHP. I develop on my home box. When I get something working the way I want, I ftp those files to the remote server. To me, that seems to make more sense that trying to run two different web servers on the same system. My PHP system involves no monkeying with special config files, or running special servers to couple the different environments, or setting special ports, or paths. For PHP development, I don't even need ssh access. Various solutions like WebStack or WSGI should permit you to choose Apache and/or other servers and hopefully not notice big differences in your application. Various WebStack examples should run out of the distribution, admittedly using their own server processes, and there's plenty of choice when it comes to configuration complexity across the supported server technologies (CGI, mod_python, Java Servlet, and so on). Perhaps the range of WSGI adapters offer a similar range of choices. In short, flexibility is definitely here for Python Web frameworks. I'd agree that PHP is usually configured to be as easy to deploy as possible, but I guess that's because the (admittedly straightforward) configuration is typically already done for users of shared hosting. I've just got into a shared hosting situation, and PHP is set up alongside CGI and static pages - you just drop the files into the directory and Apache serves them up according to their filename extensions. To configure mod_python isn't that much harder, but there are some tricky elements which often defeat people. However, some hosting providers (such as mine) do make it just as easy, but just not at less than $1 per month. I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night I think you may have something there. For $10 a year I can get an account at dollar-hosting.net, copy some php files there, and that's all there to it. I have been beating my brains out trying to get anything working with a python framework, and I have not been able to do it. I even bought VPS hosting just for the sake of python development. I have to admit that I've only fairly recently had experiences with getting Django and MoinMoin working from scratch, and the latter is mostly set up on Ubuntu systems if you install the package and know how to add a site to the Apache configuration. My observation with regard to Django 0.96 (at least, and perhaps 1.0 is a bit better) is that there's a lot of stuff that I'm moderately comfortable with - setting up mod_python, for example - but I'd be really put off doing any of it if I hadn't had the experience of doing it (and troubleshooting it) before. MoinMoin seems to be easier: you just have to copy the files into the right places. It's a lot nicer than some other solutions, notably old school Perl applications, which need lots of Apache tweaking to avoid easily overlooked insecurity issues. Nevertheless, there's potential for making mistakes, having the wrong permissions, and so on. But, I still can not seem to make the quantum leap of getting something that works locally, to work remotely. BTW: with the VPS hosting, I had to install and configure my own web-hosting and PHP, including setting up lighttpd with fastcgi and php modules - and I still found that much easier than getting anything to work with python. System packages of Python frameworks should mostly leave you with only a bit of configuration file editing to do, perhaps with some database initialisation where necessary, but I suppose that some frameworks don't have up-to-date-enough packages. Even then, perhaps it's the last bit which causes the most problems - you'll have to remind us where you got stuck, I think. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: writing Python in Emacs
Thanks Rob. Your code should basically do the trick. -- Richard -- http://mail.python.org/mailman/listinfo/python-list
Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
I do not understand why no one has answered the following question: Has anybody worked with Gene Expression Programming David Blubaugh -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Wednesday, January 30, 2008 6:10 PM To: python-list@python.org Subject: Python-list Digest, Vol 52, Issue 437 Send Python-list mailing list submissions to python-list@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to [EMAIL PROTECTED] You can reach the person managing the list at [EMAIL PROTECTED] When replying, please edit your Subject line so it is more specific than Re: Contents of Python-list digest... This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
is this some kind of joke? if you get no answers, then the answer is no On Jan 30, 2008 7:40 PM, Blubaugh, David A. [EMAIL PROTECTED] wrote: I do not understand why no one has answered the following question: Has anybody worked with Gene Expression Programming David Blubaugh -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Wednesday, January 30, 2008 6:10 PM To: python-list@python.org Subject: Python-list Digest, Vol 52, Issue 437 Send Python-list mailing list submissions to python-list@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to [EMAIL PROTECTED] You can reach the person managing the list at [EMAIL PROTECTED] When replying, please edit your Subject line so it is more specific than Re: Contents of Python-list digest... This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
I do not understand why no one has answered the following question: Has anybody worked with Gene Expression Programming Hm, maybe because nobody did? Just a thought. It can also be that everyone worked with it but everyone is part of a big conspiracy not to answer any of your emails just to make you act weird. I'm not sure, I'm really not sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Events in Python
Hey Si, The PEAK lib Trellis (http://peak.telecommunity.com/DevCenter/Trellis) is worth checking out. I haven't had a chance to use it yet but am keen to. There are several other modules that may apply, I recommend searching on the Python Package Index (http://pypi.python.org/pypi), for observer or dispatcher. Hope this helps. -alex23 -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary Keys question
On Jan 30, 3:09 pm, Berteun Damman [EMAIL PROTECTED] wrote: On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater [EMAIL PROTECTED] wrote: I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! I don't know the exact way Python's hash function works, but I can take a guess. I'm sorry if I explain something you already know. A hash is for quickly looking up data. Yet, you don't want to waste too much memory. So there is a limit number of spaces allocated, in which to store objects. This number of spaces can be thought of as a list. Then, if you put something into the dict, Python computes the 'hash' of this object, which basically forms the index in the list where to store it. So every object should be mapped onto some index within the list. (If you retrieve it, the hash is computed again, and the value on that index is looked up, like list indexing, these are fast operations.) Say, if you have 100 spaces, and someone puts in integer in the list, the hashfunction used might be % 100. So the first 100 integers would always be placed at consecutive places. For strings however, a more complicated hash-function would be used, which takes into account more characters, so strings don't end up in order. For integers, if you put in integers that are spread very widely apart, they won't end up in order either (see the mod 100 example, 104 will come before 10). If you replace the list2 in your example by: list2 = [1 * x for x in range(1,9)] You will see that this one doesn't end up in order either. So, there's no exception for integers when it comes to the order, yet the particular properties of the hash function will cause sequential integers to end up in order under some circumstances. Berteun PS: What happens if two values map onto the same space is of course an obvious question, and the trick is choosing your hashfunction so this occurs not very often on average. If it happens there are several strategies. Wikipedia probably has an explanation of how hash-functions can work in such a case. Thank you for the explanation. . . I think I now have a (foggy) understanding of hash tables. It seems to be a way to create order (an index) out of disorder (random numbers or characters) behind the scenes. . -- http://mail.python.org/mailman/listinfo/python-list